mirror of
https://github.com/expo/entity.git
synced 2026-11-15 17:32:07 -10:00
Compare commits
180
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c692afbcb | ||
|
|
17bd06e67e | ||
|
|
69ef7aa0c9 | ||
|
|
8db4fbbd8a | ||
|
|
c22ed50e80 | ||
|
|
9dcbc3da23 | ||
|
|
e87e2a3a28 | ||
|
|
68e222f512 | ||
|
|
e404297b30 | ||
|
|
cbf51c0488 | ||
|
|
243a0386fb | ||
|
|
727f16662d | ||
|
|
0e1b9f9452 | ||
|
|
52327bd56c | ||
|
|
af121ed765 | ||
|
|
ae9aab60bb | ||
|
|
9629e36e0d | ||
|
|
4af5ede87d | ||
|
|
fa5af4783f | ||
|
|
953b6a2d32 | ||
|
|
07b8abbb73 | ||
|
|
9c43369ad3 | ||
|
|
ca45510e08 | ||
|
|
4f5d13d5c7 | ||
|
|
8557eff8db | ||
|
|
ba3ba9ea89 | ||
|
|
e57cd9e6ca | ||
|
|
cab81a25e0 | ||
|
|
ada9f90a1c | ||
|
|
ee194b7110 | ||
|
|
da5f3b08e7 | ||
|
|
ddb3e848dc | ||
|
|
b79c67f88c | ||
|
|
fbdd599845 | ||
|
|
fbb161ecd2 | ||
|
|
f1b13a9840 | ||
|
|
3be085cd8f | ||
|
|
b5f6cb6e4e | ||
|
|
2e5f9ce7f5 | ||
|
|
38122c8bd2 | ||
|
|
96ead4f360 | ||
|
|
7cc580550b | ||
|
|
a4740446e0 | ||
|
|
d12496dc1b | ||
|
|
613d5d7424 | ||
|
|
dd93c0144e | ||
|
|
0137c84baf | ||
|
|
f196b0dcfb | ||
|
|
6ec73542af | ||
|
|
59e05de4dc | ||
|
|
017642a1b2 | ||
|
|
44e18b2011 | ||
|
|
a2fd6d3f3f | ||
|
|
211232d254 | ||
|
|
7d1e567cc4 | ||
|
|
0fb7ba1a36 | ||
|
|
64ef6556d0 | ||
|
|
f7e1739440 | ||
|
|
0dd046d043 | ||
|
|
e6fbffcfee | ||
|
|
0619bd1738 | ||
|
|
2454e5b91a | ||
|
|
a40f0f4574 | ||
|
|
2e8707dd32 | ||
|
|
df75910cbd | ||
|
|
06688ff789 | ||
|
|
957387b0d3 | ||
|
|
cd353dd058 | ||
|
|
b604ff7bf2 | ||
|
|
795c231dae | ||
|
|
f8eaf094b6 | ||
|
|
f4201afa86 | ||
|
|
4e07e761c0 | ||
|
|
ab0eb5525f | ||
|
|
a5e1738f5f | ||
|
|
9b8427a211 | ||
|
|
4badcf8a77 | ||
|
|
f0c01e4414 | ||
|
|
d8a6c1d8bd | ||
|
|
abe20b9168 | ||
|
|
1c17dc0f37 | ||
|
|
5bd968f698 | ||
|
|
55be94ba64 | ||
|
|
2063fc715c | ||
|
|
4454602f22 | ||
|
|
42a7912dc5 | ||
|
|
dd8c710e82 | ||
|
|
2912764a6a | ||
|
|
6879bbde9e | ||
|
|
e89e8f7b6d | ||
|
|
d5a36d1748 | ||
|
|
3f10a9e70e | ||
|
|
5561a6fcae | ||
|
|
f300d8e55a | ||
|
|
ecf1608f7b | ||
|
|
0eb8989c49 | ||
|
|
e8299e2db6 | ||
|
|
292d89167e | ||
|
|
20219752b9 | ||
|
|
717d20367f | ||
|
|
46072a37dd | ||
|
|
4ac1868d98 | ||
|
|
b1ed31b185 | ||
|
|
38ba558080 | ||
|
|
a920ed0090 | ||
|
|
df49b12a2e | ||
|
|
22d7298c84 | ||
|
|
5ef16f4340 | ||
|
|
d0e15580cc | ||
|
|
a7368a26e2 | ||
|
|
7c330773bb | ||
|
|
0e55f8066e | ||
|
|
7786c266d9 | ||
|
|
a70b27a136 | ||
|
|
9dda1bb981 | ||
|
|
9c7c0de98f | ||
|
|
05f9bcc6ce | ||
|
|
0b1fdbe207 | ||
|
|
5fc76ead20 | ||
|
|
98eaaa0298 | ||
|
|
797e33bd7b | ||
|
|
4c42f7be8f | ||
|
|
6add3fb767 | ||
|
|
7d7457a98c | ||
|
|
fccf3eb0de | ||
|
|
6ea3dae767 | ||
|
|
604353645d | ||
|
|
7a3a239313 | ||
|
|
36c58cfdf9 | ||
|
|
a0bb5b9874 | ||
|
|
9d851edf9f | ||
|
|
4519909be8 | ||
|
|
1365b11ccb | ||
|
|
226e1bfb98 | ||
|
|
b4ed49b289 | ||
|
|
5df53a0a7f | ||
|
|
b8a1f97ea8 | ||
|
|
fbd06e4368 | ||
|
|
4c569b6012 | ||
|
|
f039e71041 | ||
|
|
f60b439939 | ||
|
|
570ef6f37d | ||
|
|
26a45d3489 | ||
|
|
976f6e6434 | ||
|
|
9a4f08e31a | ||
|
|
2240e94d08 | ||
|
|
a41a95b38d | ||
|
|
9b642b31c8 | ||
|
|
64b646786b | ||
|
|
623ab6cf8a | ||
|
|
5988712332 | ||
|
|
1ed43ddaa5 | ||
|
|
dbd1cc8479 | ||
|
|
977b790ba7 | ||
|
|
2693fbc000 | ||
|
|
4709f53b45 | ||
|
|
f4496b9cc7 | ||
|
|
15ebe7d584 | ||
|
|
0d00605a93 | ||
|
|
73d45fdca3 | ||
|
|
3421a746be | ||
|
|
5ae965b736 | ||
|
|
bfa703e4ed | ||
|
|
174d6c602b | ||
|
|
0c0c6a3496 | ||
|
|
3f103e1dbd | ||
|
|
d90dce72c2 | ||
|
|
d800024283 | ||
|
|
b6c950900d | ||
|
|
4965cc2388 | ||
|
|
e3cee07091 | ||
|
|
0a1d1b5972 | ||
|
|
db887d3d7d | ||
|
|
2214f7d19a | ||
|
|
4f4243d314 | ||
|
|
a505216608 | ||
|
|
bc40501535 | ||
|
|
790e75160b | ||
|
|
cd38019789 | ||
|
|
e1c47de3a7 |
No files matched your search
+9
-2
@@ -9,23 +9,30 @@ This is Entity, a privacy-aware data layer for defining, caching, and authorizin
|
||||
## Essential Development Commands
|
||||
|
||||
### Dependencies
|
||||
|
||||
- `yarn add` - Add a dependency. Run this only if necessary and ask before running.
|
||||
|
||||
### Building and Linting
|
||||
|
||||
- `yarn tsc` - Typecheck the code
|
||||
- `yarn lint` - Run ESLint on source code
|
||||
- `yarn lint` - Run oxlint on source code
|
||||
- `yarn format` - Format code with oxfmt
|
||||
- `yarn format-check` - Check formatting without writing
|
||||
- `yarn ctix` - Build barrel index.ts files
|
||||
|
||||
### Testing
|
||||
|
||||
- `yarn test` - Run unit tests
|
||||
- `yarn integration` - Run integration tests against dockerized environment
|
||||
|
||||
### Commit messages
|
||||
|
||||
- All PRs use conventional commits for their titles: https://www.conventionalcommits.org/
|
||||
|
||||
## Code conventions
|
||||
|
||||
- Backwards compatibility is a non-goal of refactorings of this library. Consumers rely upon typescript to know what needs to be migrated, so all breaking changes should be detectable via running typescript post-entity-version-upgrade in a consumer application that makes use of this package.
|
||||
- Do not use jest's `test.skip`
|
||||
- Prefer not to use dynamic imports for now
|
||||
- Whenever technically correct, use typescript types for something instead of `any`
|
||||
- Prefer American English spellings of words over British English. For example, prefer "Adapter" over "Adaptor".
|
||||
- Prefer American English spellings of words over British English. For example, prefer "Adapter" over "Adaptor".
|
||||
@@ -0,0 +1 @@
|
||||
packages/entity-codemod/**/__testfixtures__/**
|
||||
@@ -17,4 +17,4 @@ jobs:
|
||||
steps:
|
||||
- uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6.1.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
+10
-10
@@ -7,28 +7,28 @@ on:
|
||||
|
||||
env:
|
||||
# renovate: datasource=github-releases depName=jdx/mise
|
||||
MISE_VERSION: v2026.3.8
|
||||
MISE_VERSION: v2026.9.7
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
- uses: jdx/mise-action@5228313ee0372e111a38da051671ca30fc5a96db # v3.6.3
|
||||
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
- uses: jdx/mise-action@c2a87611a18de5b3828c5652fe268e992400cb5c # v4.3.0
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
version: ${{ env.MISE_VERSION }}
|
||||
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
cache: yarn
|
||||
- run: mise run ci
|
||||
- uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2
|
||||
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v6.0.2
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
directory: ./coverage
|
||||
flags: unittest
|
||||
fail_ci_if_error: true
|
||||
- uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2
|
||||
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v6.0.2
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
directory: ./coverage-integration
|
||||
@@ -37,18 +37,18 @@ jobs:
|
||||
docs:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
- uses: jdx/mise-action@5228313ee0372e111a38da051671ca30fc5a96db # v3.6.3
|
||||
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
- uses: jdx/mise-action@c2a87611a18de5b3828c5652fe268e992400cb5c # v4.3.0
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
version: ${{ env.MISE_VERSION }}
|
||||
- uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
cache: yarn
|
||||
- run: mise run typedoc
|
||||
- name: Deploy
|
||||
if: ${{ github.ref == 'refs/heads/main' }}
|
||||
uses: peaceiris/actions-gh-pages@4f9cc6602d3f66b9c108549d475ec49e8ef4d45e # v4.0.0
|
||||
uses: peaceiris/actions-gh-pages@84c30a85c19949d7eee79c4ff27748b70285e453 # v4.1.0
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
publish_dir: ./doc
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"useTabs": false,
|
||||
"tabWidth": 2,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"sortImports": {
|
||||
"groups": [
|
||||
["builtin", "external"],
|
||||
["internal", "subpath"],
|
||||
["parent", "sibling", "index"],
|
||||
"unknown"
|
||||
],
|
||||
"ignoreCase": false
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"singleQuote": true,
|
||||
"jsxBracketSameLine": true
|
||||
}
|
||||
Vendored
+11
-2
@@ -1,3 +1,12 @@
|
||||
{
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
}
|
||||
"typescript.tsdk": "node_modules/typescript/lib",
|
||||
"oxc.fmt.configPath": ".oxfmtrc.json",
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode",
|
||||
"editor.formatOnSave": true,
|
||||
"[javascript]": {
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -3,4 +3,5 @@ nodeLinker: node-modules
|
||||
npmMinimalAgeGate: 2d
|
||||
|
||||
npmPreapprovedPackages:
|
||||
- "@expo/*"
|
||||
- '@expo/*'
|
||||
- 'oxlint-config-universe'
|
||||
@@ -3,6 +3,44 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
### Features
|
||||
|
||||
- add ID-based and field-based knex database loaders for use with locking modifiers ([#706](https://github.com/expo/entity/issues/706)) ([e87e2a3](https://github.com/expo/entity/commit/e87e2a3a28f4279f5911bfd0189964b94a2ced7f))
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
### Features
|
||||
|
||||
- add forShare and skipLocked selection modifiers to knex loader ([#705](https://github.com/expo/entity/issues/705)) ([243a038](https://github.com/expo/entity/commit/243a0386fb9755f3926ade8dcc1b92adf38cd923))
|
||||
- add forUpdate to knex loader ([#704](https://github.com/expo/entity/issues/704)) ([727f166](https://github.com/expo/entity/commit/727f16662d8baa3757bb8e94f51d837f17fd333d))
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **deps:** update dependency koa to v3.2.1 ([#634](https://github.com/expo/entity/issues/634)) ([1c17dc0](https://github.com/expo/entity/commit/1c17dc0f37ec68fb73aae1f92b3ce2c79062b93e))
|
||||
|
||||
### Features
|
||||
|
||||
- accept array of parent entity classes in cascade deletion rule ([#650](https://github.com/expo/entity/issues/650)) ([df75910](https://github.com/expo/entity/commit/df75910cbdc89df60ed2f23dbedf8862ed5c9077))
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- only throw EntityDatabaseAdapterPaginationCursorInvalidError from cursor decoding logic ([#537](https://github.com/expo/entity/issues/537)) ([e3cee07](https://github.com/expo/entity/commit/e3cee07091af8d1e6c5bb2d82f13e837c7658ea9))
|
||||
- remove unused arg from EntityInvalidationUtils ([#536](https://github.com/expo/entity/issues/536)) ([0a1d1b5](https://github.com/expo/entity/commit/0a1d1b5972c15c932f5c31015f2519163f882f83))
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
@@ -16,13 +16,11 @@ Entity is a privacy-aware data layer for defining, caching, and authorizing acce
|
||||
- Configurable, optional, full-object read-through caching using Cache Adapters.
|
||||
- [Dataloader](https://github.com/graphql/dataloader) in-memory batching and read-through caching.
|
||||
|
||||
|
||||
## Getting Started
|
||||
|
||||
- [Example application](https://github.com/expo/entity/tree/main/packages/entity-example)
|
||||
- [Documentation](https://expo.github.io/entity/)
|
||||
|
||||
|
||||
## Background
|
||||
|
||||
Authorization is the process of determining whether a user has access to a piece of data or a feature.
|
||||
@@ -56,10 +54,7 @@ The Entity framework solves this by adding an additional property to the system:
|
||||
|
||||
```typescript
|
||||
class PhotoPrivacyPolicy {
|
||||
const readRules = [
|
||||
new AllowIfOwnerRule(),
|
||||
new AllowIfOrganizationPermissionRule(),
|
||||
];
|
||||
readRules = [new AllowIfOwnerRule(), new AllowIfOrganizationPermissionRule()];
|
||||
}
|
||||
|
||||
// in the view, for example
|
||||
@@ -72,6 +67,7 @@ async function get_photo_page(viewer: ViewerContext): string {
|
||||
## Use Case
|
||||
|
||||
Entity is not limited in where it can or should be used, but was designed for use in a [Koa](https://koajs.com/)-like environment with a request and response. At Expo, we use Entity in the following manner:
|
||||
|
||||
1. A request comes into Koa router
|
||||
1. Middleware initializes the Entity framework for the request
|
||||
1. A `ViewerContext` is created identifying the individual making the request.
|
||||
@@ -81,7 +77,7 @@ Note: The entity framework instance should not be shared across multiple request
|
||||
|
||||
## Contributing
|
||||
|
||||
We control development tooling versions using [mise-en-place](https://mise.jdx.dev). If you have it installed, then:
|
||||
We control development tooling versions using [mise-en-place](https://mise.jdx.dev). If you have it installed, then:
|
||||
|
||||
- Running `mise run ci` will run all tests that our CI environment will run.
|
||||
- Running `mise t` will show a list of mise tasks you can run with `mise run <name>`.
|
||||
@@ -92,9 +88,10 @@ If you don't have `mise` installed, [you can install it](https://mise.jdx.dev/in
|
||||
## Releasing
|
||||
|
||||
To release a new version:
|
||||
|
||||
1. `git checkout main`
|
||||
1. `npm login` (to refresh token)
|
||||
1. `yarn lerna publish [patch|minor|major] -- --conventional-commits --force-publish`
|
||||
1. `yarn lerna publish [patch|minor|major] --conventional-commits --force-publish`
|
||||
1. In GitHub release interface, create a new release from the tag, copy changelog changes to release description.
|
||||
|
||||
## License
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import universeNodeConfig from 'eslint-config-universe/flat/node.js';
|
||||
import universeSharedTypescriptAnalysisConfig from 'eslint-config-universe/flat/shared/typescript-analysis.js';
|
||||
import tsdoc from 'eslint-plugin-tsdoc';
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores([
|
||||
'packages/entity-codemod/**/__testfixtures__/**',
|
||||
'packages/*/build',
|
||||
'coverage',
|
||||
'coverage-integration',
|
||||
'doc',
|
||||
]),
|
||||
universeNodeConfig,
|
||||
universeSharedTypescriptAnalysisConfig,
|
||||
{
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
tsdoc,
|
||||
},
|
||||
rules: {
|
||||
'no-restricted-imports': ['error', { paths: ['.', '..', '../..'] }],
|
||||
'tsdoc/syntax': 'warn',
|
||||
'no-console': 'warn',
|
||||
'handle-callback-err': 'off',
|
||||
eqeqeq: ['warn', 'always'],
|
||||
'no-restricted-properties': [
|
||||
'warn',
|
||||
{
|
||||
object: 'it',
|
||||
property: 'only',
|
||||
message: 'it.only should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'test',
|
||||
property: 'only',
|
||||
message: 'test.only should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'describe',
|
||||
property: 'only',
|
||||
message: 'describe.only should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'it',
|
||||
property: 'skip',
|
||||
message: 'it.skip should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'test',
|
||||
property: 'skip',
|
||||
message: 'test.skip should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'describe',
|
||||
property: 'skip',
|
||||
message: 'describe.skip should not be committed to main.',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
settings: {
|
||||
jest: {
|
||||
version: 29,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.ts', '**/*.tsx', '**/*.d.ts'],
|
||||
rules: {
|
||||
'no-void': [
|
||||
'warn',
|
||||
{
|
||||
allowAsStatement: true,
|
||||
},
|
||||
],
|
||||
'@typescript-eslint/explicit-function-return-type': [
|
||||
'warn',
|
||||
{
|
||||
allowExpressions: true,
|
||||
},
|
||||
],
|
||||
'@typescript-eslint/naming-convention': [
|
||||
'warn',
|
||||
{
|
||||
selector: 'typeLike',
|
||||
format: ['PascalCase'],
|
||||
},
|
||||
{
|
||||
selector: 'enumMember',
|
||||
format: ['UPPER_CASE'],
|
||||
},
|
||||
// async functions must have names ending with 'Async'
|
||||
{
|
||||
selector: ['function', 'classMethod', 'typeMethod'],
|
||||
format: ['camelCase'],
|
||||
modifiers: ['async'],
|
||||
suffix: ['Async'],
|
||||
},
|
||||
],
|
||||
'no-dupe-class-members': 'off',
|
||||
'@typescript-eslint/no-dupe-class-members': ['error'],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.ts', '**/*.tsx', '**/*.d.ts'],
|
||||
ignores: ['**/*tests__/**', 'packages/entity-codemod/src/transforms/**'],
|
||||
rules: {
|
||||
'no-restricted-exports': ['error', { restrictDefaultExports: { direct: true } }],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/__tests__/**/*.ts', '**/__tests__/**/*.tsx', '**/__tests__/**/*.d.ts'],
|
||||
rules: {
|
||||
// ts-mockito verify function needs void functions within verify which is a void function
|
||||
'@typescript-eslint/no-confusing-void-expression': 'off',
|
||||
},
|
||||
},
|
||||
]);
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"packages": ["packages/*"],
|
||||
"npmClient": "yarn",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
[tools]
|
||||
node = "24.14.0"
|
||||
node = "24.21.0"
|
||||
|
||||
[tasks.yarn]
|
||||
run = "yarn install --immutable"
|
||||
@@ -12,17 +12,22 @@ run = "yarn build"
|
||||
depends = "build"
|
||||
run = "yarn typedoc"
|
||||
|
||||
[tasks."checks:tsc"]
|
||||
depends = "yarn"
|
||||
run = "yarn tsc"
|
||||
|
||||
[tasks."checks:lint"]
|
||||
depends = "yarn"
|
||||
run = "yarn lint --max-warnings=0"
|
||||
run = "yarn lint"
|
||||
|
||||
[tasks."checks:format"]
|
||||
depends = "yarn"
|
||||
run = "yarn format-check"
|
||||
|
||||
[tasks."checks:barrel"]
|
||||
description = "Check if barrel files are up-to-date"
|
||||
depends = "yarn"
|
||||
run = [
|
||||
"yarn ctix",
|
||||
'[ -z "$(git status --porcelain)" ]',
|
||||
]
|
||||
run = ["yarn ctix", '[ -z "$(git status --porcelain)" ]']
|
||||
|
||||
[tasks."checks:unit"]
|
||||
depends = "yarn"
|
||||
@@ -43,5 +48,5 @@ postinstall = [
|
||||
# Enable yarn shim. Version controlled by package.json#packageManager
|
||||
# NOTE: mise can install yarn directly, but renovate does not use mise, so we
|
||||
# control yarn versions using the packageManager field.
|
||||
"corepack enable yarn"
|
||||
"corepack enable yarn",
|
||||
]
|
||||
@@ -0,0 +1,95 @@
|
||||
import { defineConfig } from 'oxlint';
|
||||
import node from 'oxlint-config-universe/node';
|
||||
import typescriptAnalysis from 'oxlint-config-universe/typescript-analysis';
|
||||
|
||||
export default defineConfig({
|
||||
extends: [node, typescriptAnalysis],
|
||||
plugins: ['jest'],
|
||||
options: {
|
||||
typeAware: true,
|
||||
},
|
||||
rules: {
|
||||
// Overrides from oxlint-config-universe defaults
|
||||
eqeqeq: ['warn', 'always'],
|
||||
'no-restricted-properties': [
|
||||
'warn',
|
||||
{
|
||||
object: 'it',
|
||||
property: 'only',
|
||||
message: 'it.only should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'test',
|
||||
property: 'only',
|
||||
message: 'test.only should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'describe',
|
||||
property: 'only',
|
||||
message: 'describe.only should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'it',
|
||||
property: 'skip',
|
||||
message: 'it.skip should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'test',
|
||||
property: 'skip',
|
||||
message: 'test.skip should not be committed to main.',
|
||||
},
|
||||
{
|
||||
object: 'describe',
|
||||
property: 'skip',
|
||||
message: 'describe.skip should not be committed to main.',
|
||||
},
|
||||
],
|
||||
'no-console': 'warn',
|
||||
'no-void': ['warn', { allowAsStatement: true }],
|
||||
'no-restricted-imports': ['error', { paths: ['.', '..', '../..'] }],
|
||||
|
||||
// TypeScript rules
|
||||
'typescript/ban-ts-comment': 'warn',
|
||||
'typescript/unbound-method': 'warn',
|
||||
'typescript/restrict-template-expressions': 'off',
|
||||
'typescript/no-base-to-string': 'off',
|
||||
'typescript/no-redundant-type-constituents': 'off',
|
||||
'typescript/require-array-sort-compare': 'off',
|
||||
'typescript/explicit-function-return-type': ['warn', { allowExpressions: true }],
|
||||
|
||||
// Jest rules
|
||||
'jest/valid-title': 'off',
|
||||
'jest/expect-expect': 'off',
|
||||
'jest/no-conditional-expect': 'off',
|
||||
'jest/no-export': 'off',
|
||||
'jest/require-to-throw-message': 'off',
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ['*.config.js'],
|
||||
env: { node: true },
|
||||
globals: { URL: 'readonly' },
|
||||
},
|
||||
{
|
||||
files: ['**/__tests__/**/*.ts', '**/__integration-tests__/**/*.ts'],
|
||||
rules: {
|
||||
'typescript/no-confusing-void-expression': 'off',
|
||||
'typescript/unbound-method': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['packages/**/*.ts'],
|
||||
excludeFiles: ['**/*tests__/**', 'packages/entity-codemod/src/transforms/**'],
|
||||
rules: {
|
||||
'no-restricted-exports': ['error', { restrictDefaultExports: { direct: true } }],
|
||||
},
|
||||
},
|
||||
],
|
||||
ignorePatterns: [
|
||||
'packages/entity-codemod/**/__testfixtures__/**',
|
||||
'packages/*/build',
|
||||
'coverage',
|
||||
'coverage-integration',
|
||||
'doc',
|
||||
],
|
||||
});
|
||||
+18
-16
@@ -4,12 +4,15 @@
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"tsc": "tsc --build",
|
||||
"build": "tsc --build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "eslint .",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"lint": "oxlint --type-aware . --max-warnings=0 && yarn format-check",
|
||||
"lint-fix": "oxlint --type-aware --fix . && yarn format",
|
||||
"format": "oxfmt --write --ignore-path .fmtignore .",
|
||||
"format-check": "oxfmt --check --ignore-path .fmtignore .",
|
||||
"test": "yarn build --noCheck && NODE_OPTIONS='--experimental-vm-modules --disable-warning=ExperimentalWarning' jest",
|
||||
"test:all": "yarn test",
|
||||
"integration": "./resources/run-with-docker yarn test --config jest-integration.config.js --runInBand",
|
||||
@@ -18,23 +21,22 @@
|
||||
"package-files": "yarn workspaces foreach --all --no-private --parallel --topological pack --dry-run",
|
||||
"typedoc": "yarn build && typedoc"
|
||||
},
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@tsconfig/bases": "1.0.23",
|
||||
"@types/node": "24.12.0",
|
||||
"ctix": "2.7.5",
|
||||
"eslint": "9.39.4",
|
||||
"eslint-config-universe": "15.0.3",
|
||||
"eslint-plugin-tsdoc": "0.5.2",
|
||||
"jest": "30.2.0",
|
||||
"lerna": "9.0.5",
|
||||
"prettier": "3.8.1",
|
||||
"prettier-plugin-organize-imports": "4.3.0",
|
||||
"typedoc": "0.28.17",
|
||||
"typescript": "5.9.3"
|
||||
"@tsconfig/bases": "1.0.28",
|
||||
"@types/node": "24.19.1",
|
||||
"ctix": "2.8.2",
|
||||
"jest": "30.5.1",
|
||||
"lerna": "9.0.7",
|
||||
"oxfmt": "0.67.0",
|
||||
"oxlint": "1.82.0",
|
||||
"oxlint-config-universe": "0.2.0",
|
||||
"oxlint-tsgolint": "0.25.0",
|
||||
"prettier": "3.9.6",
|
||||
"typedoc": "0.28.20",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"resolutions": {
|
||||
"collect-v8-coverage": "^1.0.3"
|
||||
},
|
||||
"packageManager": "[email protected]2.0+sha512.f45ab632439a67f8bc759bf32ead036a1f413287b9042726b7cc4818b7b49e14e9423ba49b18f9e06ea4941c1ad062385b1d8760a8d5091a1a31e5f6219afca8"
|
||||
"packageManager": "[email protected]3.0+sha512.5c20ba010c99815433e5c8453112165e673f1c7948d8d2b267f4b5e52097538658388ebc9f9580656d9b75c5cc996f990f611f99304a2197d4c56d21eea370e7"
|
||||
}
|
||||
@@ -3,6 +3,30 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
@@ -1,40 +1,40 @@
|
||||
{
|
||||
"name": "@expo/entity-cache-adapter-local-memory",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "Cross-request local memory cache adapter for @expo/entity",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)",
|
||||
"integration": "yarn integration:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@isaacs/ttlcache": "2.1.4",
|
||||
"@jest/globals": "30.2.0",
|
||||
"typescript": "5.9.3"
|
||||
"@isaacs/ttlcache": "2.1.5",
|
||||
"@jest/globals": "30.5.1",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,30 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
@@ -13,13 +13,7 @@ import Redis from 'ioredis';
|
||||
|
||||
const genericRedisCacherContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`)
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'ent-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
@@ -40,4 +34,4 @@ export const createDefaultEntityCompanionProvider = (
|
||||
}
|
||||
);
|
||||
};
|
||||
```
|
||||
```
|
||||
@@ -1,45 +1,45 @@
|
||||
{
|
||||
"name": "@expo/entity-cache-adapter-redis",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "Redis cache adapter for @expo/entity",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)",
|
||||
"integration": "yarn integration:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/batcher": "1.1.2",
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@jest/globals": "30.5.1",
|
||||
"ioredis": "5.11.1",
|
||||
"ts-mockito": "2.6.1",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ioredis": ">=5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/batcher": "1.0.0",
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@jest/globals": "30.2.0",
|
||||
"ioredis": "5.10.0",
|
||||
"ts-mockito": "2.6.1",
|
||||
"typescript": "5.9.3"
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,27 @@ export type GenericRedisCacheInvalidationConfig =
|
||||
cacheKeyVersionsToInvalidateFn: (cacheKeyVersion: number) => readonly number[];
|
||||
};
|
||||
|
||||
function validateGenericRedisCacheContext(context: GenericRedisCacheContext): void {
|
||||
if (context.cacheKeyDelimiter.length === 0) {
|
||||
throw new Error('GenericRedisCacheContext.cacheKeyDelimiter must be a non-empty string');
|
||||
}
|
||||
if (context.cacheKeyDelimiter.includes('\\')) {
|
||||
throw new Error(
|
||||
`GenericRedisCacheContext.cacheKeyDelimiter must not contain the escape character "\\" (got ${JSON.stringify(context.cacheKeyDelimiter)})`,
|
||||
);
|
||||
}
|
||||
if (!Number.isInteger(context.ttlSecondsPositive) || context.ttlSecondsPositive <= 0) {
|
||||
throw new Error(
|
||||
`GenericRedisCacheContext.ttlSecondsPositive must be a positive integer (got ${context.ttlSecondsPositive})`,
|
||||
);
|
||||
}
|
||||
if (!Number.isInteger(context.ttlSecondsNegative) || context.ttlSecondsNegative <= 0) {
|
||||
throw new Error(
|
||||
`GenericRedisCacheContext.ttlSecondsNegative must be a positive integer (got ${context.ttlSecondsNegative})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface GenericRedisCacheContext {
|
||||
/**
|
||||
* Instance of ioredis.Redis
|
||||
@@ -86,10 +107,15 @@ export interface GenericRedisCacheContext {
|
||||
redisClient: IRedis;
|
||||
|
||||
/**
|
||||
* Create a key string for key parts (cache key prefix, versions, entity name, etc).
|
||||
* Most commonly a simple `parts.join(':')`. See integration test for example.
|
||||
* Delimiter used to join the parts of a Redis cache key (cache key prefix,
|
||||
* versions, entity name, field values, etc). Typically `:`.
|
||||
*
|
||||
* The cacher escapes occurrences of this delimiter (and the escape character `\`)
|
||||
* within each part before joining, so the encoding is injective regardless of
|
||||
* what the parts contain. This prevents a value that happens to contain the
|
||||
* delimiter from colliding with a different (key, value) pair.
|
||||
*/
|
||||
makeKeyFn: (...parts: string[]) => string;
|
||||
cacheKeyDelimiter: string;
|
||||
|
||||
/**
|
||||
* Prefix prepended to all entity cache keys. Useful for adding a short, human-readable
|
||||
@@ -122,7 +148,9 @@ export class GenericRedisCacher<
|
||||
constructor(
|
||||
private readonly context: GenericRedisCacheContext,
|
||||
private readonly entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
) {}
|
||||
) {
|
||||
validateGenericRedisCacheContext(context);
|
||||
}
|
||||
|
||||
public async loadManyAsync(
|
||||
keys: readonly string[],
|
||||
@@ -212,14 +240,18 @@ export class GenericRedisCacher<
|
||||
TLoadValue extends IEntityLoadValue<TSerializedLoadValue>,
|
||||
>(key: TLoadKey, value: TLoadValue, cacheKeyVersion: number): string {
|
||||
const cacheKeyType = key.getLoadMethodType();
|
||||
const parts = key.createCacheKeyPartsForLoadValue(this.entityConfiguration, value);
|
||||
return this.context.makeKeyFn(
|
||||
const keyAndValueParts = key.createCacheKeyPartsForLoadValue(this.entityConfiguration, value);
|
||||
const allParts = [
|
||||
this.context.cacheKeyPrefix,
|
||||
cacheKeyType,
|
||||
this.entityConfiguration.tableName,
|
||||
`v3.${cacheKeyVersion}`,
|
||||
...parts,
|
||||
);
|
||||
`v4.${cacheKeyVersion}`,
|
||||
...keyAndValueParts,
|
||||
];
|
||||
const delimiter = this.context.cacheKeyDelimiter;
|
||||
return allParts
|
||||
.map((part) => part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`))
|
||||
.join(delimiter);
|
||||
}
|
||||
|
||||
public makeCacheKeyForStorage<
|
||||
@@ -250,12 +282,19 @@ export class GenericRedisCacher<
|
||||
).map((cacheKeyVersion) =>
|
||||
this.makeCacheKeyForCacheKeyVersion(key, value, cacheKeyVersion),
|
||||
);
|
||||
case RedisCacheInvalidationStrategy.CUSTOM:
|
||||
return this.context.invalidationConfig
|
||||
.cacheKeyVersionsToInvalidateFn(this.entityConfiguration.cacheKeyVersion)
|
||||
.map((cacheKeyVersion) =>
|
||||
this.makeCacheKeyForCacheKeyVersion(key, value, cacheKeyVersion),
|
||||
case RedisCacheInvalidationStrategy.CUSTOM: {
|
||||
const cacheKeyVersions = this.context.invalidationConfig.cacheKeyVersionsToInvalidateFn(
|
||||
this.entityConfiguration.cacheKeyVersion,
|
||||
);
|
||||
if (cacheKeyVersions.length === 0) {
|
||||
throw new Error(
|
||||
`GenericRedisCacheContext.invalidationConfig.cacheKeyVersionsToInvalidateFn returned an empty list for cacheKeyVersion ${this.entityConfiguration.cacheKeyVersion}; this would silently disable invalidation`,
|
||||
);
|
||||
}
|
||||
return cacheKeyVersions.map((cacheKeyVersion) =>
|
||||
this.makeCacheKeyForCacheKeyVersion(key, value, cacheKeyVersion),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-7
@@ -68,13 +68,7 @@ describe(GenericRedisCacher, () => {
|
||||
beforeAll(() => {
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
+1
-7
@@ -26,13 +26,7 @@ describe(GenericRedisCacher, () => {
|
||||
beforeAll(() => {
|
||||
genericRedisCacheContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
+1
-7
@@ -20,13 +20,7 @@ describe(GenericRedisCacher, () => {
|
||||
beforeAll(() => {
|
||||
genericRedisCacheContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
@@ -17,13 +17,7 @@ describe(GenericRedisCacher, () => {
|
||||
beforeAll(() => {
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import {
|
||||
CacheStatus,
|
||||
CompositeFieldHolder,
|
||||
CompositeFieldValueHolder,
|
||||
EntityConfiguration,
|
||||
SingleFieldHolder,
|
||||
SingleFieldValueHolder,
|
||||
StringField,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
import { describe, expect, it } from '@jest/globals';
|
||||
@@ -13,6 +16,8 @@ import { GenericRedisCacher, RedisCacheInvalidationStrategy } from '../GenericRe
|
||||
|
||||
type BlahFields = {
|
||||
id: string;
|
||||
fieldA: string;
|
||||
fieldB: string;
|
||||
};
|
||||
|
||||
const entityConfiguration = new EntityConfiguration<BlahFields, 'id'>({
|
||||
@@ -21,6 +26,8 @@ const entityConfiguration = new EntityConfiguration<BlahFields, 'id'>({
|
||||
cacheKeyVersion: 2,
|
||||
schema: {
|
||||
id: new UUIDField({ columnName: 'id', cache: true }),
|
||||
fieldA: new StringField({ columnName: 'field_a', cache: true }),
|
||||
fieldB: new StringField({ columnName: 'field_b', cache: true }),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
@@ -41,7 +48,7 @@ describe(GenericRedisCacher, () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mockRedisClient),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
@@ -83,7 +90,7 @@ describe(GenericRedisCacher, () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mock<Redis>()),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
@@ -118,7 +125,7 @@ describe(GenericRedisCacher, () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mockRedisClient),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
@@ -134,10 +141,12 @@ describe(GenericRedisCacher, () => {
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
|
||||
await genericCacher.cacheManyAsync(new Map([[cacheKey, { id: 'wat' }]]));
|
||||
const value = { id: 'wat', fieldA: 'a', fieldB: 'b' };
|
||||
|
||||
await genericCacher.cacheManyAsync(new Map([[cacheKey, value]]));
|
||||
|
||||
expect(redisResults.get(cacheKey)).toMatchObject({
|
||||
value: JSON.stringify({ id: 'wat' }),
|
||||
value: JSON.stringify(value),
|
||||
code: 'EX',
|
||||
ttl: 1,
|
||||
});
|
||||
@@ -163,7 +172,7 @@ describe(GenericRedisCacher, () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mockRedisClient),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
@@ -197,7 +206,7 @@ describe(GenericRedisCacher, () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mockRedisClient),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
@@ -212,12 +221,40 @@ describe(GenericRedisCacher, () => {
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
expect(cacheKeys).toHaveLength(1);
|
||||
expect(cacheKeys[0]).toBe('hello-:single:blah:v3.2:id:wat');
|
||||
expect(cacheKeys[0]).toBe('hello-:single:blah:v4.2:id:wat');
|
||||
|
||||
await genericCacher.invalidateManyAsync(cacheKeys);
|
||||
verify(mockRedisClient.del(...cacheKeys)).once();
|
||||
});
|
||||
|
||||
it('does not collapse composite cache keys with delimiter-bearing parts', () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mock<Redis>()),
|
||||
cacheKeyPrefix: 'hello-',
|
||||
cacheKeyDelimiter: ':',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationConfig: {
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION,
|
||||
},
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
|
||||
const compositeFieldHolder = new CompositeFieldHolder<BlahFields, 'id'>(['fieldA', 'fieldB']);
|
||||
const cacheKey1 = genericCacher['makeCacheKeyForStorage'](
|
||||
compositeFieldHolder,
|
||||
new CompositeFieldValueHolder({ fieldA: 'a:b', fieldB: 'c' }),
|
||||
);
|
||||
const cacheKey2 = genericCacher['makeCacheKeyForStorage'](
|
||||
compositeFieldHolder,
|
||||
new CompositeFieldValueHolder({ fieldA: 'a', fieldB: 'b:c' }),
|
||||
);
|
||||
|
||||
expect(cacheKey1).not.toEqual(cacheKey2);
|
||||
});
|
||||
|
||||
it('invalidates correctly with RedisCacheInvalidationStrategy.SURROUNDING_CACHE_KEY_VERSIONS', async () => {
|
||||
const mockRedisClient = mock<Redis>();
|
||||
when(mockRedisClient.del()).thenResolve(1);
|
||||
@@ -225,7 +262,7 @@ describe(GenericRedisCacher, () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mockRedisClient),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
@@ -240,9 +277,9 @@ describe(GenericRedisCacher, () => {
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
expect(cacheKeys).toHaveLength(3);
|
||||
expect(cacheKeys[0]).toBe('hello-:single:blah:v3.1:id:wat');
|
||||
expect(cacheKeys[1]).toBe('hello-:single:blah:v3.2:id:wat');
|
||||
expect(cacheKeys[2]).toBe('hello-:single:blah:v3.3:id:wat');
|
||||
expect(cacheKeys[0]).toBe('hello-:single:blah:v4.1:id:wat');
|
||||
expect(cacheKeys[1]).toBe('hello-:single:blah:v4.2:id:wat');
|
||||
expect(cacheKeys[2]).toBe('hello-:single:blah:v4.3:id:wat');
|
||||
|
||||
await genericCacher.invalidateManyAsync(cacheKeys);
|
||||
verify(mockRedisClient.del(...cacheKeys)).once();
|
||||
@@ -255,7 +292,7 @@ describe(GenericRedisCacher, () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mockRedisClient),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
@@ -278,10 +315,10 @@ describe(GenericRedisCacher, () => {
|
||||
new SingleFieldValueHolder('wat'),
|
||||
);
|
||||
expect(cacheKeys).toHaveLength(4);
|
||||
expect(cacheKeys[0]).toBe('hello-:single:blah:v3.2:id:wat');
|
||||
expect(cacheKeys[1]).toBe('hello-:single:blah:v3.3:id:wat');
|
||||
expect(cacheKeys[2]).toBe('hello-:single:blah:v3.4:id:wat');
|
||||
expect(cacheKeys[3]).toBe('hello-:single:blah:v3.5:id:wat');
|
||||
expect(cacheKeys[0]).toBe('hello-:single:blah:v4.2:id:wat');
|
||||
expect(cacheKeys[1]).toBe('hello-:single:blah:v4.3:id:wat');
|
||||
expect(cacheKeys[2]).toBe('hello-:single:blah:v4.4:id:wat');
|
||||
expect(cacheKeys[3]).toBe('hello-:single:blah:v4.5:id:wat');
|
||||
|
||||
await genericCacher.invalidateManyAsync(cacheKeys);
|
||||
verify(mockRedisClient.del(...cacheKeys)).once();
|
||||
@@ -291,7 +328,7 @@ describe(GenericRedisCacher, () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mock<Redis>()),
|
||||
makeKeyFn: (...parts) => parts.join(':'),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
@@ -303,5 +340,89 @@ describe(GenericRedisCacher, () => {
|
||||
);
|
||||
await genericCacher.invalidateManyAsync([]);
|
||||
});
|
||||
|
||||
it('throws when CUSTOM strategy returns an empty cacheKeyVersions list', () => {
|
||||
const genericCacher = new GenericRedisCacher(
|
||||
{
|
||||
redisClient: instance(mock<Redis>()),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationConfig: {
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CUSTOM,
|
||||
cacheKeyVersionsToInvalidateFn: () => [],
|
||||
},
|
||||
},
|
||||
entityConfiguration,
|
||||
);
|
||||
expect(() =>
|
||||
genericCacher['makeCacheKeysForInvalidation'](
|
||||
new SingleFieldHolder('id'),
|
||||
new SingleFieldValueHolder('wat'),
|
||||
),
|
||||
).toThrow(/empty list/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GenericRedisCacheContext validation', () => {
|
||||
const validContext = {
|
||||
redisClient: instance(mock<Redis>()),
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'hello-',
|
||||
ttlSecondsPositive: 1,
|
||||
ttlSecondsNegative: 2,
|
||||
invalidationConfig: {
|
||||
invalidationStrategy: RedisCacheInvalidationStrategy.CURRENT_CACHE_KEY_VERSION as const,
|
||||
},
|
||||
};
|
||||
|
||||
it('throws when cacheKeyDelimiter is empty', () => {
|
||||
expect(
|
||||
() =>
|
||||
new GenericRedisCacher({ ...validContext, cacheKeyDelimiter: '' }, entityConfiguration),
|
||||
).toThrow(/cacheKeyDelimiter must be a non-empty string/);
|
||||
});
|
||||
|
||||
it('throws when cacheKeyDelimiter contains the escape character', () => {
|
||||
expect(
|
||||
() =>
|
||||
new GenericRedisCacher({ ...validContext, cacheKeyDelimiter: '\\' }, entityConfiguration),
|
||||
).toThrow(/must not contain the escape character/);
|
||||
});
|
||||
|
||||
it('throws when ttlSecondsPositive is not a positive integer', () => {
|
||||
expect(
|
||||
() =>
|
||||
new GenericRedisCacher({ ...validContext, ttlSecondsPositive: 0 }, entityConfiguration),
|
||||
).toThrow(/ttlSecondsPositive must be a positive integer/);
|
||||
expect(
|
||||
() =>
|
||||
new GenericRedisCacher({ ...validContext, ttlSecondsPositive: -1 }, entityConfiguration),
|
||||
).toThrow(/ttlSecondsPositive must be a positive integer/);
|
||||
expect(
|
||||
() =>
|
||||
new GenericRedisCacher({ ...validContext, ttlSecondsPositive: 1.5 }, entityConfiguration),
|
||||
).toThrow(/ttlSecondsPositive must be a positive integer/);
|
||||
});
|
||||
|
||||
it('throws when ttlSecondsNegative is not a positive integer', () => {
|
||||
expect(
|
||||
() =>
|
||||
new GenericRedisCacher({ ...validContext, ttlSecondsNegative: 0 }, entityConfiguration),
|
||||
).toThrow(/ttlSecondsNegative must be a positive integer/);
|
||||
expect(
|
||||
() =>
|
||||
new GenericRedisCacher({ ...validContext, ttlSecondsNegative: -1 }, entityConfiguration),
|
||||
).toThrow(/ttlSecondsNegative must be a positive integer/);
|
||||
expect(
|
||||
() =>
|
||||
new GenericRedisCacher({ ...validContext, ttlSecondsNegative: 1.5 }, entityConfiguration),
|
||||
).toThrow(/ttlSecondsNegative must be a positive integer/);
|
||||
});
|
||||
|
||||
it('accepts a valid context', () => {
|
||||
expect(() => new GenericRedisCacher(validContext, entityConfiguration)).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,30 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-codemod
|
||||
|
||||
@@ -21,6 +21,7 @@ Then, in package.json scripts:
|
||||
```
|
||||
|
||||
And finally:
|
||||
|
||||
```sh
|
||||
yarn jscodeshift src -t node_modules/@expo/entity-codemod/build/v0.39.0-v0.40.0.js
|
||||
```
|
||||
@@ -1,37 +1,37 @@
|
||||
{
|
||||
"name": "@expo/entity-codemod",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "jscodeshift codemods for @expo/entity upgrades",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.5.1",
|
||||
"@types/jscodeshift": "17.3.0",
|
||||
"@types/node": "24.19.1",
|
||||
"jscodeshift": "17.4.0",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.2.0",
|
||||
"@types/jscodeshift": "17.3.0",
|
||||
"@types/node": "24.12.0",
|
||||
"jscodeshift": "17.3.0",
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// oxlint-disable unicorn/no-empty-file
|
||||
// placeholder file to fix tsc/typedoc
|
||||
@@ -3,6 +3,33 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex-testing-utils
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
### Features
|
||||
|
||||
- add forShare and skipLocked selection modifiers to knex loader ([#705](https://github.com/expo/entity/issues/705)) ([243a038](https://github.com/expo/entity/commit/243a0386fb9755f3926ade8dcc1b92adf38cd923))
|
||||
- add forUpdate to knex loader ([#704](https://github.com/expo/entity/issues/704)) ([727f166](https://github.com/expo/entity/commit/727f16662d8baa3757bb8e94f51d837f17fd333d))
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex-testing-utils
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex-testing-utils
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex-testing-utils
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex-testing-utils
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex-testing-utils
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# @expo/entity-database-adapter-knex-testing-utils
|
||||
|
||||
Testing utilities for applications using Entity with Knex database adapter.
|
||||
Testing utilities for applications using Entity with Knex database adapter.
|
||||
@@ -1,45 +1,45 @@
|
||||
{
|
||||
"name": "@expo/entity-database-adapter-knex-testing-utils",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "Testing utilities for applications using Entity with Knex database adapter",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn run lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^",
|
||||
"@expo/entity-database-adapter-knex": "workspace:^",
|
||||
"invariant": "^2.2.4",
|
||||
"uuid": "^13.0.0"
|
||||
"uuid": "^14.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.5.1",
|
||||
"@types/invariant": "2.2.37",
|
||||
"@types/node": "24.19.1",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@jest/globals": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.2.0",
|
||||
"@types/invariant": "2.2.37",
|
||||
"@types/node": "24.12.0",
|
||||
"typescript": "5.9.3"
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
+35
-14
@@ -75,7 +75,7 @@ export class StubPostgresDatabaseAdapter<
|
||||
): Promise<object[]> {
|
||||
const objectCollection = this.getObjectCollectionForTable(tableName);
|
||||
const results = StubPostgresDatabaseAdapter.uniqBy(tableTuples, (tuple) =>
|
||||
tuple.join(':'),
|
||||
JSON.stringify(tuple),
|
||||
).reduce(
|
||||
(acc, tableTuple) => {
|
||||
return acc.concat(
|
||||
@@ -192,16 +192,6 @@ export class StubPostgresDatabaseAdapter<
|
||||
return filteredObjects;
|
||||
}
|
||||
|
||||
protected fetchManyByRawWhereClauseInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
_rawWhereClause: string,
|
||||
_bindings: object | any[],
|
||||
_querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]> {
|
||||
throw new Error('Raw WHERE clauses not supported for StubDatabaseAdapter');
|
||||
}
|
||||
|
||||
protected fetchManyBySQLFragmentInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
@@ -211,6 +201,37 @@ export class StubPostgresDatabaseAdapter<
|
||||
throw new Error('SQL fragments not supported for StubDatabaseAdapter');
|
||||
}
|
||||
|
||||
protected async countByFieldEqualityConjunctionInternalAsync(
|
||||
queryInterface: any,
|
||||
tableName: string,
|
||||
tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[],
|
||||
tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[],
|
||||
): Promise<number> {
|
||||
const results = await this.fetchManyByFieldEqualityConjunctionInternalAsync(
|
||||
queryInterface,
|
||||
tableName,
|
||||
tableFieldSingleValueEqualityOperands,
|
||||
tableFieldMultiValueEqualityOperands,
|
||||
{
|
||||
orderBy: undefined,
|
||||
offset: undefined,
|
||||
limit: undefined,
|
||||
forUpdate: undefined,
|
||||
forShare: undefined,
|
||||
skipLocked: undefined,
|
||||
},
|
||||
);
|
||||
return results.length;
|
||||
}
|
||||
|
||||
protected countBySQLFragmentInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
_sqlFragment: SQLFragment<TFields>,
|
||||
): Promise<number> {
|
||||
throw new Error('SQL fragment count not supported for StubDatabaseAdapter');
|
||||
}
|
||||
|
||||
private generateRandomID(): any {
|
||||
const idSchemaField = this.entityConfiguration2.schema.get(this.entityConfiguration2.idField);
|
||||
invariant(
|
||||
@@ -253,7 +274,7 @@ export class StubPostgresDatabaseAdapter<
|
||||
tableIdField: string,
|
||||
id: any,
|
||||
object: object,
|
||||
): Promise<object[]> {
|
||||
): Promise<{ updatedRowCount: number }> {
|
||||
// SQL does not support empty updates, mirror behavior here for better test simulation
|
||||
if (Object.keys(object).length === 0) {
|
||||
throw new Error(`Empty update (${tableIdField} = ${id})`);
|
||||
@@ -268,14 +289,14 @@ export class StubPostgresDatabaseAdapter<
|
||||
// SQL updates to a nonexistent row succeed but affect 0 rows,
|
||||
// mirror that behavior here for better test simulation
|
||||
if (objectIndex < 0) {
|
||||
return [];
|
||||
return { updatedRowCount: 0 };
|
||||
}
|
||||
|
||||
objectCollection[objectIndex] = {
|
||||
...objectCollection[objectIndex],
|
||||
...object,
|
||||
};
|
||||
return [objectCollection[objectIndex]];
|
||||
return { updatedRowCount: 1 };
|
||||
}
|
||||
|
||||
protected async deleteInternalAsync(
|
||||
|
||||
+116
-9
@@ -174,6 +174,55 @@ describe(StubPostgresDatabaseAdapter, () => {
|
||||
const id2Results = results.get(new SingleFieldValueHolder('id2'));
|
||||
expect(id2Results?.[0]).toMatchObject({ customIdField: 'id2', stringField: 'test2' });
|
||||
});
|
||||
|
||||
it('does not collapse distinct composite tuples that stringify with the same delimiter join', async () => {
|
||||
const queryContext = instance(mock(EntityQueryContext));
|
||||
const databaseAdapter = new StubPostgresDatabaseAdapter<TestFields, 'customIdField'>(
|
||||
testEntityConfiguration,
|
||||
StubPostgresDatabaseAdapter.convertFieldObjectsToDataStore(
|
||||
testEntityConfiguration,
|
||||
new Map([
|
||||
[
|
||||
testEntityConfiguration.tableName,
|
||||
[
|
||||
{
|
||||
customIdField: 'id1',
|
||||
testIndexedField: 'b',
|
||||
intField: 5,
|
||||
stringField: 'a:b',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
{
|
||||
customIdField: 'id2',
|
||||
testIndexedField: 'b:c',
|
||||
intField: 10,
|
||||
stringField: 'a',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
const results = await databaseAdapter.fetchManyWhereAsync(
|
||||
queryContext,
|
||||
new CompositeFieldHolder<TestFields, 'customIdField'>(['stringField', 'testIndexedField']),
|
||||
[
|
||||
new CompositeFieldValueHolder({ stringField: 'a:b', testIndexedField: 'c' }),
|
||||
new CompositeFieldValueHolder({ stringField: 'a', testIndexedField: 'b:c' }),
|
||||
],
|
||||
);
|
||||
|
||||
expect(
|
||||
results.get(new CompositeFieldValueHolder({ stringField: 'a:b', testIndexedField: 'c' })),
|
||||
).toHaveLength(0);
|
||||
expect(
|
||||
results.get(new CompositeFieldValueHolder({ stringField: 'a', testIndexedField: 'b:c' })),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchOneWhereAsync', () => {
|
||||
@@ -489,16 +538,78 @@ describe(StubPostgresDatabaseAdapter, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchManyByRawWhereClauseAsync', () => {
|
||||
describe('countByFieldEqualityConjunctionAsync', () => {
|
||||
it('counts matching records', async () => {
|
||||
const queryContext = instance(mock(EntityQueryContext));
|
||||
const databaseAdapter = new StubPostgresDatabaseAdapter<TestFields, 'customIdField'>(
|
||||
testEntityConfiguration,
|
||||
StubPostgresDatabaseAdapter.convertFieldObjectsToDataStore(
|
||||
testEntityConfiguration,
|
||||
new Map([
|
||||
[
|
||||
testEntityConfiguration.tableName,
|
||||
[
|
||||
{
|
||||
customIdField: 'hello',
|
||||
testIndexedField: 'h1',
|
||||
intField: 3,
|
||||
stringField: 'a',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
{
|
||||
customIdField: 'world',
|
||||
testIndexedField: 'h2',
|
||||
intField: 3,
|
||||
stringField: 'b',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
{
|
||||
customIdField: 'other',
|
||||
testIndexedField: 'h3',
|
||||
intField: 5,
|
||||
stringField: 'c',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
const count = await databaseAdapter.countByFieldEqualityConjunctionAsync(queryContext, [
|
||||
{ fieldName: 'intField', fieldValue: 3 },
|
||||
]);
|
||||
expect(count).toBe(2);
|
||||
|
||||
const countAll = await databaseAdapter.countByFieldEqualityConjunctionAsync(queryContext, []);
|
||||
expect(countAll).toBe(3);
|
||||
|
||||
const countMultiValue = await databaseAdapter.countByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
[{ fieldName: 'customIdField', fieldValues: ['hello', 'world'] }],
|
||||
);
|
||||
expect(countMultiValue).toBe(2);
|
||||
|
||||
const countNone = await databaseAdapter.countByFieldEqualityConjunctionAsync(queryContext, [
|
||||
{ fieldName: 'intField', fieldValue: 999 },
|
||||
]);
|
||||
expect(countNone).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('countBySQLFragmentAsync', () => {
|
||||
it('throws because it is unsupported', async () => {
|
||||
const queryContext = instance(mock(EntityQueryContext));
|
||||
const databaseAdapter = new StubPostgresDatabaseAdapter<TestFields, 'customIdField'>(
|
||||
testEntityConfiguration,
|
||||
new Map(),
|
||||
);
|
||||
await expect(
|
||||
databaseAdapter.fetchManyByRawWhereClauseAsync(queryContext, '', [], {}),
|
||||
).rejects.toThrow();
|
||||
await expect(databaseAdapter.countBySQLFragmentAsync(queryContext, sql``)).rejects.toThrow(
|
||||
'SQL fragment count not supported for StubDatabaseAdapter',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -573,13 +684,9 @@ describe(StubPostgresDatabaseAdapter, () => {
|
||||
]),
|
||||
),
|
||||
);
|
||||
const result = await databaseAdapter.updateAsync(queryContext, 'customIdField', 'hello', {
|
||||
await databaseAdapter.updateAsync(queryContext, 'customIdField', 'hello', {
|
||||
stringField: 'b',
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
stringField: 'b',
|
||||
testIndexedField: 'h1',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws error when empty update to match common DBMS behavior', async () => {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["src/**/*"],
|
||||
"references": [
|
||||
{ "path": "../entity" },
|
||||
{ "path": "../entity-database-adapter-knex" }
|
||||
]
|
||||
}
|
||||
"references": [{ "path": "../entity" }, { "path": "../entity-database-adapter-knex" }]
|
||||
}
|
||||
@@ -3,6 +3,37 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
### Features
|
||||
|
||||
- add ID-based and field-based knex database loaders for use with locking modifiers ([#706](https://github.com/expo/entity/issues/706)) ([e87e2a3](https://github.com/expo/entity/commit/e87e2a3a28f4279f5911bfd0189964b94a2ced7f))
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
### Features
|
||||
|
||||
- add forShare and skipLocked selection modifiers to knex loader ([#705](https://github.com/expo/entity/issues/705)) ([243a038](https://github.com/expo/entity/commit/243a0386fb9755f3926ade8dcc1b92adf38cd923))
|
||||
- add forUpdate to knex loader ([#704](https://github.com/expo/entity/issues/704)) ([727f166](https://github.com/expo/entity/commit/727f16662d8baa3757bb8e94f51d837f17fd333d))
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- only throw EntityDatabaseAdapterPaginationCursorInvalidError from cursor decoding logic ([#537](https://github.com/expo/entity/issues/537)) ([e3cee07](https://github.com/expo/entity/commit/e3cee07091af8d1e6c5bb2d82f13e837c7658ea9))
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
### Features
|
||||
|
||||
@@ -39,4 +39,4 @@ export const createDefaultEntityCompanionProvider = (
|
||||
}
|
||||
);
|
||||
};
|
||||
```
|
||||
```
|
||||
@@ -1,42 +1,42 @@
|
||||
{
|
||||
"name": "@expo/entity-database-adapter-knex",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "Knex database adapter for @expo/entity",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)",
|
||||
"integration": "yarn integration:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^",
|
||||
"knex": "^3.1.0"
|
||||
"knex": "^3.2.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@jest/globals": "30.2.0",
|
||||
"pg": "8.20.0",
|
||||
"@jest/globals": "30.5.1",
|
||||
"pg": "8.23.1",
|
||||
"ts-mockito": "2.6.1",
|
||||
"typescript": "5.9.3"
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
+240
-18
@@ -1,12 +1,17 @@
|
||||
import type {
|
||||
EntityConfiguration,
|
||||
EntityConstructionUtils,
|
||||
EntityPrivacyPolicy,
|
||||
EntityQueryContext,
|
||||
IEntityClass,
|
||||
IEntityMetricsAdapter,
|
||||
ReadonlyEntity,
|
||||
ViewerContext,
|
||||
} from '@expo/entity';
|
||||
import { EntityNotFoundError, mapMap } from '@expo/entity';
|
||||
import type { Result } from '@expo/results';
|
||||
import { result } from '@expo/results';
|
||||
import assert from 'assert';
|
||||
|
||||
import type {
|
||||
FieldEqualityCondition,
|
||||
@@ -64,6 +69,48 @@ export type EntityLoaderOrderByClause<
|
||||
| EntityLoaderFieldNameOrderByClause<TFields, TSelectedFields>
|
||||
| EntityLoaderFieldFragmentOrderByClause<TFields, TSelectedFields>;
|
||||
|
||||
/**
|
||||
* Row locking modifier that locks the selected rows for update using `SELECT ... FOR UPDATE`.
|
||||
* The lock is held until the end of the transaction, so the query context must be transactional.
|
||||
*/
|
||||
export interface EntityLoaderForUpdateRowLockingModifier {
|
||||
forUpdate: true;
|
||||
forShare?: never;
|
||||
}
|
||||
|
||||
/**
|
||||
* Row locking modifier that locks the selected rows in share mode using `SELECT ... FOR SHARE`.
|
||||
* The lock is held until the end of the transaction, so the query context must be transactional.
|
||||
*/
|
||||
export interface EntityLoaderForShareRowLockingModifier {
|
||||
forShare: true;
|
||||
forUpdate?: never;
|
||||
}
|
||||
|
||||
/**
|
||||
* Row locking modifiers for load methods that never report a missing row as an error. Exactly one of
|
||||
* `forUpdate` or `forShare` is required. `skipLocked` may be set to skip rows already locked by another
|
||||
* transaction (using `SKIP LOCKED`) instead of waiting for them; skipped rows are reported as missing.
|
||||
*/
|
||||
export type EntityLoaderRowLockingModifiers = (
|
||||
| EntityLoaderForUpdateRowLockingModifier
|
||||
| EntityLoaderForShareRowLockingModifier
|
||||
) & {
|
||||
skipLocked?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Row locking modifiers for load methods that throw when a row is missing. Exactly one of `forUpdate`
|
||||
* or `forShare` is required. `skipLocked` is not permitted since a row skipped because another transaction
|
||||
* holds a lock on it would be indistinguishable from a row that does not exist.
|
||||
*/
|
||||
export type EntityLoaderRowLockingModifiersWithoutSkipLocked = (
|
||||
| EntityLoaderForUpdateRowLockingModifier
|
||||
| EntityLoaderForShareRowLockingModifier
|
||||
) & {
|
||||
skipLocked?: never;
|
||||
};
|
||||
|
||||
/**
|
||||
* SQL modifiers that only affect the selection but not the projection.
|
||||
*/
|
||||
@@ -85,6 +132,24 @@ export interface EntityLoaderQuerySelectionModifiers<
|
||||
* Limit the number of entities returned.
|
||||
*/
|
||||
limit?: number;
|
||||
|
||||
/**
|
||||
* Lock the selected rows for update using `SELECT ... FOR UPDATE`. The lock is held until the
|
||||
* end of the transaction, so the query context must be transactional. Mutually exclusive with `forShare`.
|
||||
*/
|
||||
forUpdate?: boolean;
|
||||
|
||||
/**
|
||||
* Lock the selected rows in share mode using `SELECT ... FOR SHARE`. The lock is held until the
|
||||
* end of the transaction, so the query context must be transactional. Mutually exclusive with `forUpdate`.
|
||||
*/
|
||||
forShare?: boolean;
|
||||
|
||||
/**
|
||||
* Skip rows that are already locked by another transaction using `SKIP LOCKED` instead of waiting for them.
|
||||
* Requires `forUpdate` or `forShare`.
|
||||
*/
|
||||
skipLocked?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,7 +216,10 @@ export type EntityLoaderSearchFieldSpecification<
|
||||
| NonNullableSelectedFields<TFields, TSelectedFields>
|
||||
| EntityLoaderSearchFieldSQLFragmentFnSpecification<TFields, TSelectedFields>;
|
||||
|
||||
interface SearchSpecificationBase<
|
||||
/**
|
||||
* Base specification shared by all search-based pagination strategies.
|
||||
*/
|
||||
export interface SearchSpecificationBase<
|
||||
TFields extends Record<string, any>,
|
||||
TSelectedFields extends keyof TFields = keyof TFields,
|
||||
> {
|
||||
@@ -166,7 +234,10 @@ interface SearchSpecificationBase<
|
||||
fields: readonly EntityLoaderSearchFieldSpecification<TFields, TSelectedFields>[];
|
||||
}
|
||||
|
||||
interface ILikeSearchSpecification<
|
||||
/**
|
||||
* Search specification for case-insensitive pattern matching using the SQL ILIKE operator.
|
||||
*/
|
||||
export interface ILikeSearchSpecification<
|
||||
TFields extends Record<string, any>,
|
||||
TSelectedFields extends keyof TFields = keyof TFields,
|
||||
> extends SearchSpecificationBase<TFields, TSelectedFields> {
|
||||
@@ -177,7 +248,10 @@ interface ILikeSearchSpecification<
|
||||
strategy: PaginationStrategy.ILIKE_SEARCH;
|
||||
}
|
||||
|
||||
interface TrigramSearchSpecification<
|
||||
/**
|
||||
* Search specification for similarity search using PostgreSQL trigram similarity.
|
||||
*/
|
||||
export interface TrigramSearchSpecification<
|
||||
TFields extends Record<string, any>,
|
||||
TSelectedFields extends keyof TFields = keyof TFields,
|
||||
> extends SearchSpecificationBase<TFields, TSelectedFields> {
|
||||
@@ -209,7 +283,10 @@ interface TrigramSearchSpecification<
|
||||
extraOrderByFields?: readonly EntityLoaderSearchFieldSpecification<TFields, TSelectedFields>[];
|
||||
}
|
||||
|
||||
interface StandardPaginationSpecification<
|
||||
/**
|
||||
* Pagination specification for standard (non-search) pagination.
|
||||
*/
|
||||
export interface StandardPaginationSpecification<
|
||||
TFields extends Record<string, any>,
|
||||
TSelectedFields extends keyof TFields = keyof TFields,
|
||||
> {
|
||||
@@ -345,6 +422,15 @@ export class AuthorizationResultBasedKnexEntityLoader<
|
||||
> {
|
||||
constructor(
|
||||
private readonly queryContext: EntityQueryContext,
|
||||
private readonly entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
private readonly entityClass: IEntityClass<
|
||||
TFields,
|
||||
TIDField,
|
||||
TViewerContext,
|
||||
TEntity,
|
||||
TPrivacyPolicy,
|
||||
TSelectedFields
|
||||
>,
|
||||
private readonly knexDataManager: EntityKnexDataManager<TFields, TIDField>,
|
||||
protected readonly metricsAdapter: IEntityMetricsAdapter,
|
||||
private readonly constructionUtils: EntityConstructionUtils<
|
||||
@@ -357,6 +443,127 @@ export class AuthorizationResultBasedKnexEntityLoader<
|
||||
>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Authorization-result-based version of the EnforcingKnexEntityLoader method by the same name.
|
||||
* @returns entity result for matching ID, where result error can be UnauthorizedError or EntityNotFoundError.
|
||||
*/
|
||||
async loadByIDFromDatabaseAsync(
|
||||
id: TFields[TIDField],
|
||||
modifiers: EntityLoaderRowLockingModifiersWithoutSkipLocked,
|
||||
): Promise<Result<TEntity>> {
|
||||
const entityResults = await this.loadManyByIDsFromDatabaseAsync([id], modifiers);
|
||||
const entityResult = entityResults.get(id);
|
||||
assert(entityResult !== undefined, `${id} should be guaranteed to be present in returned map`);
|
||||
return entityResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization-result-based version of the EnforcingKnexEntityLoader method by the same name.
|
||||
* @returns entity result for matching ID, or null if no entity exists for ID, where result error can be UnauthorizedError.
|
||||
*/
|
||||
async loadByIDNullableFromDatabaseAsync(
|
||||
id: TFields[TIDField],
|
||||
modifiers: EntityLoaderRowLockingModifiers,
|
||||
): Promise<Result<TEntity> | null> {
|
||||
const entityResults = await this.loadManyByIDsNullableFromDatabaseAsync([id], modifiers);
|
||||
return entityResults.get(id) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization-result-based version of the EnforcingKnexEntityLoader method by the same name.
|
||||
* @returns map from ID to corresponding entity result, where result error can be UnauthorizedError or EntityNotFoundError.
|
||||
*/
|
||||
async loadManyByIDsFromDatabaseAsync(
|
||||
ids: readonly TFields[TIDField][],
|
||||
modifiers: EntityLoaderRowLockingModifiersWithoutSkipLocked,
|
||||
): Promise<ReadonlyMap<TFields[TIDField], Result<TEntity>>> {
|
||||
const entityResults = await this.loadManyByIDsNullableFromDatabaseAsync(ids, modifiers);
|
||||
return mapMap(
|
||||
entityResults,
|
||||
(entityResult, id) =>
|
||||
entityResult ??
|
||||
result(
|
||||
new EntityNotFoundError({
|
||||
entityClass: this.entityClass,
|
||||
fieldName: this.entityConfiguration.idField,
|
||||
fieldValue: id,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization-result-based version of the EnforcingKnexEntityLoader method by the same name.
|
||||
* @returns map from ID to nullable corresponding entity result, where result error can be UnauthorizedError.
|
||||
*/
|
||||
async loadManyByIDsNullableFromDatabaseAsync(
|
||||
ids: readonly TFields[TIDField][],
|
||||
modifiers: EntityLoaderRowLockingModifiers,
|
||||
): Promise<ReadonlyMap<TFields[TIDField], Result<TEntity> | null>> {
|
||||
const idField = this.entityConfiguration.idField;
|
||||
this.constructionUtils.validateFieldAndValues(idField, ids);
|
||||
|
||||
const fieldObjects =
|
||||
ids.length > 0
|
||||
? await this.knexDataManager.loadManyByFieldEqualityConjunctionAsync(
|
||||
this.queryContext,
|
||||
[{ fieldName: idField, fieldValues: ids }],
|
||||
modifiers,
|
||||
)
|
||||
: [];
|
||||
|
||||
const idsToFieldObjects = new Map<TFields[TIDField], readonly Readonly<TFields>[]>(
|
||||
ids.map((id) => [id, []]),
|
||||
);
|
||||
for (const fieldObject of fieldObjects) {
|
||||
const id = fieldObject[idField];
|
||||
idsToFieldObjects.set(id, [...(idsToFieldObjects.get(id) ?? []), fieldObject]);
|
||||
}
|
||||
|
||||
const idsToEntityResults =
|
||||
await this.constructionUtils.constructAndAuthorizeEntitiesAsync(idsToFieldObjects);
|
||||
return mapMap(idsToEntityResults, (entityResults) => entityResults[0] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization-result-based version of the EnforcingKnexEntityLoader method by the same name.
|
||||
* @returns entity result where uniqueFieldName equals fieldValue, or null if no entity matches the condition, where result error can be UnauthorizedError.
|
||||
* @throws when multiple entities match the condition
|
||||
*/
|
||||
async loadByFieldEqualingFromDatabaseAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
uniqueFieldName: N,
|
||||
fieldValue: NonNullable<TFields[N]>,
|
||||
modifiers: EntityLoaderRowLockingModifiers,
|
||||
): Promise<Result<TEntity> | null> {
|
||||
const entityResults = await this.loadManyByFieldEqualingFromDatabaseAsync(
|
||||
uniqueFieldName,
|
||||
fieldValue,
|
||||
modifiers,
|
||||
);
|
||||
assert(
|
||||
entityResults.length <= 1,
|
||||
`loadByFieldEqualingFromDatabase: Multiple entities of type ${this.entityClass.name} found for ${String(
|
||||
uniqueFieldName,
|
||||
)}=${fieldValue}`,
|
||||
);
|
||||
return entityResults[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization-result-based version of the EnforcingKnexEntityLoader method by the same name.
|
||||
* @returns array of entity results where fieldName equals fieldValue, where result error can be UnauthorizedError
|
||||
*/
|
||||
async loadManyByFieldEqualingFromDatabaseAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
fieldName: N,
|
||||
fieldValue: NonNullable<TFields[N]>,
|
||||
modifiers: EntityLoaderRowLockingModifiers,
|
||||
): Promise<readonly Result<TEntity>[]> {
|
||||
return await this.loadManyByFieldEqualityConjunctionAsync(
|
||||
[{ fieldName, fieldValue }],
|
||||
modifiers,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization-result-based version of the EnforcingKnexEntityLoader method by the same name.
|
||||
* @returns the first entity results that matches the query, where result error can be
|
||||
@@ -401,24 +608,39 @@ export class AuthorizationResultBasedKnexEntityLoader<
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization-result-based version of the EnforcingKnexEntityLoader method by the same name.
|
||||
* @returns array of entity results that match the query, where result error can be UnauthorizedError
|
||||
* @throws Error when rawWhereClause or bindings are invalid
|
||||
* Count entities matching the conjunction of field equality operands.
|
||||
* This does not perform authorization since count does not load full entities.
|
||||
* Note that this should be used with the same caution as loadManyByFieldEqualityConjunctionAsync
|
||||
* regarding indexing since counts can be expensive on large datasets without appropriate indexes.
|
||||
*
|
||||
* @deprecated Use loadManyBySQL instead for safer value bindings and more flexible query building.
|
||||
* @returns count of entities matching the filters
|
||||
*/
|
||||
async loadManyByRawWhereClauseAsync(
|
||||
rawWhereClause: string,
|
||||
bindings: any[] | object,
|
||||
querySelectionModifiers: EntityLoaderQuerySelectionModifiers<TFields, TSelectedFields> = {},
|
||||
): Promise<readonly Result<TEntity>[]> {
|
||||
const fieldObjects = await this.knexDataManager.loadManyByRawWhereClauseAsync(
|
||||
async countByFieldEqualityConjunctionAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
fieldEqualityOperands: readonly FieldEqualityCondition<TFields, N>[],
|
||||
): Promise<number> {
|
||||
for (const fieldEqualityOperand of fieldEqualityOperands) {
|
||||
const fieldValues = isSingleValueFieldEqualityCondition(fieldEqualityOperand)
|
||||
? [fieldEqualityOperand.fieldValue]
|
||||
: fieldEqualityOperand.fieldValues;
|
||||
this.constructionUtils.validateFieldAndValues(fieldEqualityOperand.fieldName, fieldValues);
|
||||
}
|
||||
|
||||
return await this.knexDataManager.countByFieldEqualityConjunctionAsync(
|
||||
this.queryContext,
|
||||
rawWhereClause,
|
||||
bindings,
|
||||
querySelectionModifiers,
|
||||
fieldEqualityOperands,
|
||||
);
|
||||
return await this.constructionUtils.constructAndAuthorizeEntitiesArrayAsync(fieldObjects);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count entities matching a SQL fragment.
|
||||
* This does not perform authorization since count does not load full entities.
|
||||
* Note that this should be used with the same caution as loadManyBySQL regarding indexing
|
||||
* since counts can be expensive on large datasets without appropriate indexes.
|
||||
*
|
||||
* @returns count of entities matching the query
|
||||
*/
|
||||
async countBySQLAsync(fragment: SQLFragment<Pick<TFields, TSelectedFields>>): Promise<number> {
|
||||
return await this.knexDataManager.countBySQLFragmentAsync(this.queryContext, fragment);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -134,6 +134,21 @@ export interface PostgresQuerySelectionModifiers<TFields extends Record<string,
|
||||
* Limit the number of entities returned.
|
||||
*/
|
||||
limit?: number;
|
||||
|
||||
/**
|
||||
* Lock the selected rows for update using `SELECT ... FOR UPDATE`. Mutually exclusive with `forShare`.
|
||||
*/
|
||||
forUpdate?: boolean;
|
||||
|
||||
/**
|
||||
* Lock the selected rows in share mode using `SELECT ... FOR SHARE`. Mutually exclusive with `forUpdate`.
|
||||
*/
|
||||
forShare?: boolean;
|
||||
|
||||
/**
|
||||
* Skip rows that are already locked by another transaction using `SKIP LOCKED`. Requires `forUpdate` or `forShare`.
|
||||
*/
|
||||
skipLocked?: boolean;
|
||||
}
|
||||
|
||||
export type TableOrderByClause<TFields extends Record<string, any>> =
|
||||
@@ -152,6 +167,9 @@ export interface TableQuerySelectionModifiers<TFields extends Record<string, any
|
||||
orderBy: TableOrderByClause<TFields>[] | undefined;
|
||||
offset: number | undefined;
|
||||
limit: number | undefined;
|
||||
forUpdate: boolean | undefined;
|
||||
forShare: boolean | undefined;
|
||||
skipLocked: boolean | undefined;
|
||||
}
|
||||
|
||||
export abstract class BasePostgresEntityDatabaseAdapter<
|
||||
@@ -216,42 +234,6 @@ export abstract class BasePostgresEntityDatabaseAdapter<
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]>;
|
||||
|
||||
/**
|
||||
* Fetch many objects matching the raw WHERE clause.
|
||||
*
|
||||
* @param queryContext - query context with which to perform the fetch
|
||||
* @param rawWhereClause - parameterized SQL WHERE clause with positional binding placeholders or named binding placeholders
|
||||
* @param bindings - array of positional bindings or object of named bindings
|
||||
* @param querySelectionModifiers - limit, offset, and orderBy for the query
|
||||
* @returns array of objects matching the query
|
||||
*/
|
||||
async fetchManyByRawWhereClauseAsync(
|
||||
queryContext: EntityQueryContext,
|
||||
rawWhereClause: string,
|
||||
bindings: any[] | object,
|
||||
querySelectionModifiers: PostgresQuerySelectionModifiers<TFields>,
|
||||
): Promise<readonly Readonly<TFields>[]> {
|
||||
const results = await this.fetchManyByRawWhereClauseInternalAsync(
|
||||
queryContext.getQueryInterface(),
|
||||
this.entityConfiguration.tableName,
|
||||
rawWhereClause,
|
||||
bindings,
|
||||
this.convertToTableQueryModifiers(querySelectionModifiers),
|
||||
);
|
||||
|
||||
return results.map((result) =>
|
||||
transformDatabaseObjectToFields(this.entityConfiguration, this.fieldTransformerMap, result),
|
||||
);
|
||||
}
|
||||
|
||||
protected abstract fetchManyByRawWhereClauseInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
rawWhereClause: string,
|
||||
bindings: object | any[],
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]>;
|
||||
|
||||
/**
|
||||
* Fetch many objects matching the SQL fragment.
|
||||
*
|
||||
@@ -284,6 +266,73 @@ export abstract class BasePostgresEntityDatabaseAdapter<
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]>;
|
||||
|
||||
/**
|
||||
* Count objects matching the conjunction of where clauses constructed from
|
||||
* specified field equality operands.
|
||||
*
|
||||
* @param queryContext - query context with which to perform the count
|
||||
* @param fieldEqualityOperands - list of field equality where clause operand specifications
|
||||
* @returns count of objects matching the query
|
||||
*/
|
||||
async countByFieldEqualityConjunctionAsync<N extends keyof TFields>(
|
||||
queryContext: EntityQueryContext,
|
||||
fieldEqualityOperands: readonly FieldEqualityCondition<TFields, N>[],
|
||||
): Promise<number> {
|
||||
const tableFieldSingleValueOperands: TableFieldSingleValueEqualityCondition[] = [];
|
||||
const tableFieldMultipleValueOperands: TableFieldMultiValueEqualityCondition[] = [];
|
||||
for (const operand of fieldEqualityOperands) {
|
||||
if (isSingleValueFieldEqualityCondition(operand)) {
|
||||
tableFieldSingleValueOperands.push({
|
||||
tableField: getDatabaseFieldForEntityField(this.entityConfiguration, operand.fieldName),
|
||||
tableValue: operand.fieldValue,
|
||||
});
|
||||
} else {
|
||||
tableFieldMultipleValueOperands.push({
|
||||
tableField: getDatabaseFieldForEntityField(this.entityConfiguration, operand.fieldName),
|
||||
tableValues: operand.fieldValues,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return await this.countByFieldEqualityConjunctionInternalAsync(
|
||||
queryContext.getQueryInterface(),
|
||||
this.entityConfiguration.tableName,
|
||||
tableFieldSingleValueOperands,
|
||||
tableFieldMultipleValueOperands,
|
||||
);
|
||||
}
|
||||
|
||||
protected abstract countByFieldEqualityConjunctionInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[],
|
||||
tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[],
|
||||
): Promise<number>;
|
||||
|
||||
/**
|
||||
* Count objects matching the SQL fragment.
|
||||
*
|
||||
* @param queryContext - query context with which to perform the count
|
||||
* @param sqlFragment - SQLFragment for the WHERE clause of the query
|
||||
* @returns count of objects matching the query
|
||||
*/
|
||||
async countBySQLFragmentAsync(
|
||||
queryContext: EntityQueryContext,
|
||||
sqlFragment: SQLFragment<TFields>,
|
||||
): Promise<number> {
|
||||
return await this.countBySQLFragmentInternalAsync(
|
||||
queryContext.getQueryInterface(),
|
||||
this.entityConfiguration.tableName,
|
||||
sqlFragment,
|
||||
);
|
||||
}
|
||||
|
||||
protected abstract countBySQLFragmentInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
sqlFragment: SQLFragment<TFields>,
|
||||
): Promise<number>;
|
||||
|
||||
private convertToTableQueryModifiers(
|
||||
querySelectionModifiers: PostgresQuerySelectionModifiers<TFields>,
|
||||
): TableQuerySelectionModifiers<TFields> {
|
||||
@@ -312,6 +361,9 @@ export abstract class BasePostgresEntityDatabaseAdapter<
|
||||
: undefined,
|
||||
offset: querySelectionModifiers.offset,
|
||||
limit: querySelectionModifiers.limit,
|
||||
forUpdate: querySelectionModifiers.forUpdate,
|
||||
forShare: querySelectionModifiers.forShare,
|
||||
skipLocked: querySelectionModifiers.skipLocked,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,9 @@ export abstract class BaseSQLQueryBuilder<
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
orderBy?: readonly EntityLoaderOrderByClause<TFields, TSelectedFields>[];
|
||||
forUpdate?: boolean;
|
||||
forShare?: boolean;
|
||||
skipLocked?: boolean;
|
||||
},
|
||||
) {}
|
||||
|
||||
@@ -41,13 +44,42 @@ export abstract class BaseSQLQueryBuilder<
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lock the selected rows for update using `SELECT ... FOR UPDATE`. The lock is held until the
|
||||
* end of the transaction, so the query must be executed in a transactional query context.
|
||||
* Mutually exclusive with `forShare`.
|
||||
*/
|
||||
forUpdate(): this {
|
||||
this.modifiers.forUpdate = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lock the selected rows in share mode using `SELECT ... FOR SHARE`. The lock is held until the
|
||||
* end of the transaction, so the query must be executed in a transactional query context.
|
||||
* Mutually exclusive with `forUpdate`.
|
||||
*/
|
||||
forShare(): this {
|
||||
this.modifiers.forShare = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip rows that are already locked by another transaction using `SKIP LOCKED` instead of waiting for them.
|
||||
* Requires `forUpdate()` or `forShare()`.
|
||||
*/
|
||||
skipLocked(): this {
|
||||
this.modifiers.skipLocked = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Order by a field. Can be called multiple times to add multiple order bys.
|
||||
*/
|
||||
orderBy(
|
||||
fieldName: TSelectedFields,
|
||||
order: OrderByOrdering = OrderByOrdering.ASCENDING,
|
||||
nulls: NullsOrdering | undefined = undefined,
|
||||
nulls?: NullsOrdering,
|
||||
): this {
|
||||
this.modifiers.orderBy = [...(this.modifiers.orderBy ?? []), { fieldName, order, nulls }];
|
||||
return this;
|
||||
@@ -74,7 +106,7 @@ export abstract class BaseSQLQueryBuilder<
|
||||
orderBySQL(
|
||||
fragment: SQLFragment<Pick<TFields, TSelectedFields>>,
|
||||
order: OrderByOrdering = OrderByOrdering.ASCENDING,
|
||||
nulls: NullsOrdering | undefined = undefined,
|
||||
nulls?: NullsOrdering,
|
||||
): this {
|
||||
this.modifiers.orderBy = [
|
||||
...(this.modifiers.orderBy ?? []),
|
||||
|
||||
@@ -6,11 +6,14 @@ import type {
|
||||
ReadonlyEntity,
|
||||
ViewerContext,
|
||||
} from '@expo/entity';
|
||||
import { mapMap } from '@expo/entity';
|
||||
|
||||
import type {
|
||||
AuthorizationResultBasedKnexEntityLoader,
|
||||
EntityLoaderLoadPageArgs,
|
||||
EntityLoaderQuerySelectionModifiers,
|
||||
EntityLoaderRowLockingModifiers,
|
||||
EntityLoaderRowLockingModifiersWithoutSkipLocked,
|
||||
} from './AuthorizationResultBasedKnexEntityLoader.ts';
|
||||
import type { FieldEqualityCondition } from './BasePostgresEntityDatabaseAdapter.ts';
|
||||
import { BaseSQLQueryBuilder } from './BaseSQLQueryBuilder.ts';
|
||||
@@ -57,6 +60,140 @@ export class EnforcingKnexEntityLoader<
|
||||
>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Load an entity by ID directly from the database, bypassing the dataloader and cache.
|
||||
*
|
||||
* Unlike {@link "@expo/entity"!EnforcingEntityLoader.loadByIDAsync | EnforcingEntityLoader.loadByIDAsync}, this
|
||||
* issues one database query per call and does not read from or write to the entity cache. It exists
|
||||
* for cases that need row locking modifiers, which are required to make this intent explicit.
|
||||
* `skipLocked` is not permitted here since a skipped row would be reported as not found.
|
||||
* Use {@link loadByIDNullableFromDatabaseAsync} with `skipLocked`.
|
||||
*
|
||||
* @param id - ID of the entity
|
||||
* @param modifiers - row locking modifiers for the query
|
||||
* @returns entity matching ID
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view the returned entity
|
||||
* @throws EntityNotFoundError when no entity exists for ID
|
||||
*/
|
||||
async loadByIDFromDatabaseAsync(
|
||||
id: TFields[TIDField],
|
||||
modifiers: EntityLoaderRowLockingModifiersWithoutSkipLocked,
|
||||
): Promise<TEntity> {
|
||||
const entityResult = await this.knexEntityLoader.loadByIDFromDatabaseAsync(id, modifiers);
|
||||
return entityResult.enforceValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load an entity by ID directly from the database, or return null if non-existent.
|
||||
* See {@link loadByIDFromDatabaseAsync} for how this differs from the standard loader.
|
||||
*
|
||||
* @param id - ID of the entity
|
||||
* @param modifiers - row locking modifiers for the query
|
||||
* @returns entity for matching ID, or null if no entity exists for ID
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view the returned entity
|
||||
*/
|
||||
async loadByIDNullableFromDatabaseAsync(
|
||||
id: TFields[TIDField],
|
||||
modifiers: EntityLoaderRowLockingModifiers,
|
||||
): Promise<TEntity | null> {
|
||||
const entityResult = await this.knexEntityLoader.loadByIDNullableFromDatabaseAsync(
|
||||
id,
|
||||
modifiers,
|
||||
);
|
||||
return entityResult ? entityResult.enforceValue() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load many entities for a list of IDs directly from the database.
|
||||
* See {@link loadByIDFromDatabaseAsync} for how this differs from the standard loader.
|
||||
*
|
||||
* `skipLocked` is not permitted here since a skipped row would be reported as not found.
|
||||
* Use {@link loadManyByIDsNullableFromDatabaseAsync} with `skipLocked`.
|
||||
*
|
||||
* @param ids - IDs of the entities to load
|
||||
* @param modifiers - row locking modifiers for the query
|
||||
* @returns map from ID to corresponding entity
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view one or more of the returned entities
|
||||
* @throws EntityNotFoundError when no entity exists for one or more of the IDs
|
||||
*/
|
||||
async loadManyByIDsFromDatabaseAsync(
|
||||
ids: readonly TFields[TIDField][],
|
||||
modifiers: EntityLoaderRowLockingModifiersWithoutSkipLocked,
|
||||
): Promise<ReadonlyMap<TFields[TIDField], TEntity>> {
|
||||
const entityResults = await this.knexEntityLoader.loadManyByIDsFromDatabaseAsync(
|
||||
ids,
|
||||
modifiers,
|
||||
);
|
||||
return mapMap(entityResults, (entityResult) => entityResult.enforceValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Load many entities for a list of IDs directly from the database, returning null for any IDs that are non-existent.
|
||||
* See {@link loadByIDFromDatabaseAsync} for how this differs from the standard loader.
|
||||
*
|
||||
* @param ids - IDs of the entities to load
|
||||
* @param modifiers - row locking modifiers for the query
|
||||
* @returns map from ID to nullable corresponding entity
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view one or more of the returned entities
|
||||
*/
|
||||
async loadManyByIDsNullableFromDatabaseAsync(
|
||||
ids: readonly TFields[TIDField][],
|
||||
modifiers: EntityLoaderRowLockingModifiers,
|
||||
): Promise<ReadonlyMap<TFields[TIDField], TEntity | null>> {
|
||||
const entityResults = await this.knexEntityLoader.loadManyByIDsNullableFromDatabaseAsync(
|
||||
ids,
|
||||
modifiers,
|
||||
);
|
||||
return mapMap(entityResults, (entityResult) => entityResult?.enforceValue() ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load an entity where uniqueFieldName equals fieldValue directly from the database, or null if no entity matches.
|
||||
* See {@link loadByIDFromDatabaseAsync} for how this differs from the standard loader.
|
||||
*
|
||||
* @param uniqueFieldName - entity field being queried
|
||||
* @param fieldValue - uniqueFieldName field value being queried
|
||||
* @param modifiers - row locking modifiers for the query
|
||||
* @returns entity where uniqueFieldName equals fieldValue, or null if no entity matches the condition
|
||||
* @throws when multiple entities match the condition
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view the returned entity
|
||||
*/
|
||||
async loadByFieldEqualingFromDatabaseAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
uniqueFieldName: N,
|
||||
fieldValue: NonNullable<TFields[N]>,
|
||||
modifiers: EntityLoaderRowLockingModifiers,
|
||||
): Promise<TEntity | null> {
|
||||
const entityResult = await this.knexEntityLoader.loadByFieldEqualingFromDatabaseAsync(
|
||||
uniqueFieldName,
|
||||
fieldValue,
|
||||
modifiers,
|
||||
);
|
||||
return entityResult ? entityResult.enforceValue() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load many entities where fieldName equals fieldValue directly from the database.
|
||||
* See {@link loadByIDFromDatabaseAsync} for how this differs from the standard loader.
|
||||
*
|
||||
* @param fieldName - entity field being queried
|
||||
* @param fieldValue - fieldName field value being queried
|
||||
* @param modifiers - row locking modifiers for the query
|
||||
* @returns array of entities where fieldName equals fieldValue
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view one or more of the returned entities
|
||||
*/
|
||||
async loadManyByFieldEqualingFromDatabaseAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
fieldName: N,
|
||||
fieldValue: NonNullable<TFields[N]>,
|
||||
modifiers: EntityLoaderRowLockingModifiers,
|
||||
): Promise<readonly TEntity[]> {
|
||||
const entityResults = await this.knexEntityLoader.loadManyByFieldEqualingFromDatabaseAsync(
|
||||
fieldName,
|
||||
fieldValue,
|
||||
modifiers,
|
||||
);
|
||||
return entityResults.map((entityResult) => entityResult.enforceValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the first entity matching the conjunction of field equality operands and
|
||||
* query modifiers.
|
||||
@@ -88,7 +225,7 @@ export class EnforcingKnexEntityLoader<
|
||||
* query modifiers.
|
||||
*
|
||||
* Typically this is used for complex queries that cannot be expressed through simpler
|
||||
* convenience methods such as {@link loadManyByFieldEqualingAsync}.
|
||||
* convenience methods such as {@link "@expo/entity"!EnforcingEntityLoader.loadManyByFieldEqualingAsync | EnforcingEntityLoader.loadManyByFieldEqualingAsync}.
|
||||
*
|
||||
* @throws EntityNotAuthorizedError if viewer is not authorized to view the entity
|
||||
* @returns entities matching the filters
|
||||
@@ -105,47 +242,29 @@ export class EnforcingKnexEntityLoader<
|
||||
}
|
||||
|
||||
/**
|
||||
* Load entities with a raw SQL WHERE clause.
|
||||
* Count entities matching the conjunction of field equality operands.
|
||||
* This does not perform authorization since count does not load full entities.
|
||||
* Note that this should be used with the same caution as loadManyByFieldEqualityConjunctionAsync
|
||||
* regarding indexing since counts can be expensive on large datasets without appropriate indexes.
|
||||
*
|
||||
* @example
|
||||
* Load entities with SQL function
|
||||
* ```typescript
|
||||
* const entitiesWithJsonKey = await ExampleEntity.loader(vc)
|
||||
* .loadManyByRawWhereClauseAsync(
|
||||
* "json_column->>'key_name' = ?",
|
||||
* ['value'],
|
||||
* );
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* Load entities with tuple matching
|
||||
* ```typescript
|
||||
* const entities = await ExampleEntity.loader(vc)
|
||||
* .loadManyByRawWhereClauseAsync(
|
||||
* '(column_1, column_2) IN ((?, ?), (?, ?))',
|
||||
* [value1, value2, value3, value4],
|
||||
* );
|
||||
* ```
|
||||
* @param rawWhereClause - SQL WHERE clause. Interpolated values should be specified as ?-placeholders or :key_name
|
||||
* @param bindings - values to bind to the placeholders in the WHERE clause
|
||||
* @param querySelectionModifiers - limit, offset, and orderBy for the query.
|
||||
* @returns entities matching the WHERE clause
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view one or more of the returned entities
|
||||
* @throws Error when rawWhereClause or bindings are invalid
|
||||
*
|
||||
* @deprecated Use loadManyBySQL instead for safer value bindings and more flexible query building.
|
||||
* @returns count of entities matching the filters
|
||||
*/
|
||||
async loadManyByRawWhereClauseAsync(
|
||||
rawWhereClause: string,
|
||||
bindings: any[] | object,
|
||||
querySelectionModifiers: EntityLoaderQuerySelectionModifiers<TFields, TSelectedFields> = {},
|
||||
): Promise<readonly TEntity[]> {
|
||||
const entityResults = await this.knexEntityLoader.loadManyByRawWhereClauseAsync(
|
||||
rawWhereClause,
|
||||
bindings,
|
||||
querySelectionModifiers,
|
||||
);
|
||||
return entityResults.map((result) => result.enforceValue());
|
||||
async countByFieldEqualityConjunctionAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
fieldEqualityOperands: FieldEqualityCondition<TFields, N>[],
|
||||
): Promise<number> {
|
||||
return await this.knexEntityLoader.countByFieldEqualityConjunctionAsync(fieldEqualityOperands);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count entities matching a SQL fragment.
|
||||
* This does not perform authorization since count does not load full entity rows.
|
||||
* Note that this should be used with the same caution as loadManyBySQL regarding indexing
|
||||
* since counts can be expensive on large datasets without appropriate indexes.
|
||||
*
|
||||
* @returns count of entities matching the query
|
||||
*/
|
||||
async countBySQLAsync(fragment: SQLFragment<Pick<TFields, TSelectedFields>>): Promise<number> {
|
||||
return await this.knexEntityLoader.countBySQLAsync(fragment);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -79,6 +79,8 @@ export class KnexEntityLoaderFactory<
|
||||
|
||||
return new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
this.entityCompanion.entityCompanionDefinition.entityConfiguration,
|
||||
this.entityCompanion.entityCompanionDefinition.entityClass,
|
||||
this.knexDataManager,
|
||||
this.metricsAdapter,
|
||||
constructionUtils,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { EntityConfiguration, FieldTransformer, FieldTransformerMap } from '@expo/entity';
|
||||
import { getDatabaseFieldForEntityField } from '@expo/entity';
|
||||
import { getDatabaseFieldForEntityField, RESERVED_ENTITY_COUNT_QUERY_ALIAS } from '@expo/entity';
|
||||
import type { Knex } from 'knex';
|
||||
|
||||
import type {
|
||||
@@ -91,7 +91,7 @@ export class PostgresEntityDatabaseAdapter<
|
||||
.select()
|
||||
.from(tableName)
|
||||
.whereRaw(`(??) = ANY(?)`, [
|
||||
tableColumns[0],
|
||||
tableColumns[0]!,
|
||||
tableTuples.map((tableTuple) => tableTuple[0]),
|
||||
]),
|
||||
);
|
||||
@@ -116,7 +116,14 @@ export class PostgresEntityDatabaseAdapter<
|
||||
tableValue: tableTuple[index],
|
||||
})),
|
||||
[],
|
||||
{ limit: 1, orderBy: undefined, offset: undefined },
|
||||
{
|
||||
limit: 1,
|
||||
orderBy: undefined,
|
||||
offset: undefined,
|
||||
forUpdate: undefined,
|
||||
forShare: undefined,
|
||||
skipLocked: undefined,
|
||||
},
|
||||
);
|
||||
return results[0] ?? null;
|
||||
}
|
||||
@@ -125,7 +132,7 @@ export class PostgresEntityDatabaseAdapter<
|
||||
query: Knex.QueryBuilder,
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Knex.QueryBuilder {
|
||||
const { orderBy, offset, limit } = querySelectionModifiers;
|
||||
const { orderBy, offset, limit, forUpdate, forShare, skipLocked } = querySelectionModifiers;
|
||||
|
||||
let ret = query;
|
||||
|
||||
@@ -161,17 +168,27 @@ export class PostgresEntityDatabaseAdapter<
|
||||
ret = ret.limit(limit);
|
||||
}
|
||||
|
||||
if (forUpdate) {
|
||||
ret = ret.forUpdate();
|
||||
}
|
||||
|
||||
if (forShare) {
|
||||
ret = ret.forShare();
|
||||
}
|
||||
|
||||
if (skipLocked) {
|
||||
ret = ret.skipLocked();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
protected async fetchManyByFieldEqualityConjunctionInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
private applyFieldEqualityConjunctionWhereClause(
|
||||
query: Knex.QueryBuilder,
|
||||
tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[],
|
||||
tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[],
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]> {
|
||||
let query = queryInterface.select().from(tableName);
|
||||
): Knex.QueryBuilder {
|
||||
let result = query;
|
||||
|
||||
if (tableFieldSingleValueEqualityOperands.length > 0) {
|
||||
const whereObject: { [key: string]: any } = {};
|
||||
@@ -184,11 +201,11 @@ export class PostgresEntityDatabaseAdapter<
|
||||
for (const { tableField, tableValue } of nonNullTableFieldSingleValueEqualityOperands) {
|
||||
whereObject[tableField] = tableValue;
|
||||
}
|
||||
query = query.where(whereObject);
|
||||
result = result.where(whereObject);
|
||||
}
|
||||
if (nullTableFieldSingleValueEqualityOperands.length > 0) {
|
||||
for (const { tableField } of nullTableFieldSingleValueEqualityOperands) {
|
||||
query = query.whereNull(tableField);
|
||||
result = result.whereNull(tableField);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -196,7 +213,7 @@ export class PostgresEntityDatabaseAdapter<
|
||||
if (tableFieldMultiValueEqualityOperands.length > 0) {
|
||||
for (const { tableField, tableValues } of tableFieldMultiValueEqualityOperands) {
|
||||
const nonNullTableValues = tableValues.filter((tableValue) => tableValue !== null);
|
||||
query = query.where((builder) => {
|
||||
result = result.where((builder) => {
|
||||
builder.whereRaw('?? = ANY(?)', [tableField, [...nonNullTableValues]]);
|
||||
// there was at least one null, allow null in this equality clause
|
||||
if (nonNullTableValues.length !== tableValues.length) {
|
||||
@@ -206,20 +223,35 @@ export class PostgresEntityDatabaseAdapter<
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected async fetchManyByFieldEqualityConjunctionInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[],
|
||||
tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[],
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]> {
|
||||
let query = this.applyFieldEqualityConjunctionWhereClause(
|
||||
queryInterface.select().from(tableName),
|
||||
tableFieldSingleValueEqualityOperands,
|
||||
tableFieldMultiValueEqualityOperands,
|
||||
);
|
||||
query = this.applyQueryModifiersToQuery(query, querySelectionModifiers);
|
||||
return await wrapNativePostgresCallAsync(() => query);
|
||||
}
|
||||
|
||||
protected async fetchManyByRawWhereClauseInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
rawWhereClause: string,
|
||||
bindings: object | any[],
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]> {
|
||||
let query = queryInterface.select().from(tableName).whereRaw(rawWhereClause, bindings);
|
||||
query = this.applyQueryModifiersToQuery(query, querySelectionModifiers);
|
||||
return await wrapNativePostgresCallAsync(() => query);
|
||||
private applySQLFragmentWhereClause(
|
||||
query: Knex.QueryBuilder,
|
||||
sqlFragment: SQLFragment<TFields>,
|
||||
): Knex.QueryBuilder {
|
||||
return query.whereRaw(
|
||||
sqlFragment.sql,
|
||||
sqlFragment.getKnexBindings((fieldName) =>
|
||||
getDatabaseFieldForEntityField(this.entityConfiguration, fieldName),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
protected async fetchManyBySQLFragmentInternalAsync(
|
||||
@@ -228,19 +260,42 @@ export class PostgresEntityDatabaseAdapter<
|
||||
sqlFragment: SQLFragment<TFields>,
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]> {
|
||||
let query = queryInterface
|
||||
.select()
|
||||
.from(tableName)
|
||||
.whereRaw(
|
||||
sqlFragment.sql,
|
||||
sqlFragment.getKnexBindings((fieldName) =>
|
||||
getDatabaseFieldForEntityField(this.entityConfiguration, fieldName),
|
||||
),
|
||||
);
|
||||
let query = this.applySQLFragmentWhereClause(
|
||||
queryInterface.select().from(tableName),
|
||||
sqlFragment,
|
||||
);
|
||||
query = this.applyQueryModifiersToQuery(query, querySelectionModifiers);
|
||||
return await wrapNativePostgresCallAsync(() => query);
|
||||
}
|
||||
|
||||
protected async countByFieldEqualityConjunctionInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[],
|
||||
tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[],
|
||||
): Promise<number> {
|
||||
const query = this.applyFieldEqualityConjunctionWhereClause(
|
||||
queryInterface.count('*', { as: RESERVED_ENTITY_COUNT_QUERY_ALIAS }).from(tableName),
|
||||
tableFieldSingleValueEqualityOperands,
|
||||
tableFieldMultiValueEqualityOperands,
|
||||
);
|
||||
const result = await wrapNativePostgresCallAsync(() => query);
|
||||
return parseInt(String(result[0][RESERVED_ENTITY_COUNT_QUERY_ALIAS]), 10);
|
||||
}
|
||||
|
||||
protected async countBySQLFragmentInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
sqlFragment: SQLFragment<TFields>,
|
||||
): Promise<number> {
|
||||
const query = this.applySQLFragmentWhereClause(
|
||||
queryInterface.count('*', { as: RESERVED_ENTITY_COUNT_QUERY_ALIAS }).from(tableName),
|
||||
sqlFragment,
|
||||
);
|
||||
const result = await wrapNativePostgresCallAsync(() => query);
|
||||
return parseInt(String(result[0][RESERVED_ENTITY_COUNT_QUERY_ALIAS]), 10);
|
||||
}
|
||||
|
||||
protected async insertInternalAsync(
|
||||
queryInterface: Knex,
|
||||
tableName: string,
|
||||
@@ -257,10 +312,11 @@ export class PostgresEntityDatabaseAdapter<
|
||||
tableIdField: string,
|
||||
id: any,
|
||||
object: object,
|
||||
): Promise<object[]> {
|
||||
return await wrapNativePostgresCallAsync(() =>
|
||||
queryInterface.update(object).into(tableName).where(tableIdField, id).returning('*'),
|
||||
): Promise<{ updatedRowCount: number }> {
|
||||
const updatedRowCount = await wrapNativePostgresCallAsync(() =>
|
||||
queryInterface.update(object).into(tableName).where(tableIdField, id),
|
||||
);
|
||||
return { updatedRowCount };
|
||||
}
|
||||
|
||||
protected async deleteInternalAsync(
|
||||
|
||||
@@ -48,10 +48,8 @@ export class PostgresEntityQueryContextProvider extends EntityQueryContextProvid
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
...(transactionConfig.isolationLevel
|
||||
? { isolationLevel: convertIsolationLevel(transactionConfig.isolationLevel) }
|
||||
: {}),
|
||||
};
|
||||
return transactionConfig.isolationLevel
|
||||
? { isolationLevel: convertIsolationLevel(transactionConfig.isolationLevel) }
|
||||
: {};
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import assert from 'assert';
|
||||
import type { Knex } from 'knex';
|
||||
|
||||
/**
|
||||
* Supported SQL value types that can be safely parameterized.
|
||||
@@ -12,7 +13,6 @@ export type SupportedSQLValue =
|
||||
| Date
|
||||
| Buffer
|
||||
| bigint
|
||||
| undefined // Will be treated as NULL
|
||||
| readonly SupportedSQLValue[] // For IN clauses and array types
|
||||
| Readonly<{ [key: string]: unknown }>; // For JSON/JSONB columns
|
||||
|
||||
@@ -41,7 +41,7 @@ export class SQLFragment<TFields extends Record<string, any>> {
|
||||
*/
|
||||
getKnexBindings(
|
||||
getColumnForField: (fieldName: keyof TFields) => string,
|
||||
): readonly SupportedSQLValue[] {
|
||||
): readonly Knex.RawBinding[] {
|
||||
return this.bindings.map((b) => {
|
||||
switch (b.type) {
|
||||
case 'entityField':
|
||||
@@ -49,7 +49,10 @@ export class SQLFragment<TFields extends Record<string, any>> {
|
||||
case 'identifier':
|
||||
return b.name;
|
||||
case 'value':
|
||||
return b.value;
|
||||
// Needs a cast since bigint is supported by knex postgres dialect but not all dialects, and thus isn't included
|
||||
// in the type. Because we only use the postgres dialect in this adapter, it's safe to allow it here.
|
||||
// https://github.com/knex/knex/issues/5013#issuecomment-3368744254
|
||||
return b.value as Knex.RawBinding;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -133,8 +136,8 @@ export class SQLFragment<TFields extends Record<string, any>> {
|
||||
* Handles all SupportedSQLValue types.
|
||||
*/
|
||||
private static formatDebugValue(value: SupportedSQLValue): string {
|
||||
// Handle null and undefined
|
||||
if (value === null || value === undefined) {
|
||||
// Handle null
|
||||
if (value === null) {
|
||||
return 'NULL';
|
||||
}
|
||||
|
||||
@@ -303,7 +306,7 @@ export function sql<TFields extends Record<string, any>>(
|
||||
strings.forEach((string, i) => {
|
||||
sqlString += string;
|
||||
if (i < values.length) {
|
||||
const value = values[i];
|
||||
const value = values[i]!;
|
||||
|
||||
if (value instanceof SQLFragment) {
|
||||
// Handle nested SQL fragments
|
||||
@@ -344,10 +347,13 @@ type PickSupportedSQLValueKeys<T> = {
|
||||
}[keyof T];
|
||||
|
||||
type PickStringValueKeys<T> = {
|
||||
[K in keyof T]: T[K] extends string | null | undefined ? K : never;
|
||||
[K in keyof T]: T[K] extends string | null ? K : never;
|
||||
}[keyof T];
|
||||
|
||||
type JsonSerializable =
|
||||
/**
|
||||
* A value that can be serialized to JSON for use with JSON(B) operators.
|
||||
*/
|
||||
export type JsonSerializable =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
@@ -368,13 +374,13 @@ export class SQLChainableFragment<
|
||||
> extends SQLFragment<TFields> {
|
||||
/**
|
||||
* Generates an equality condition (`= value`).
|
||||
* Automatically converts `null`/`undefined` to `IS NULL`.
|
||||
* Automatically converts `null` to `IS NULL`.
|
||||
*
|
||||
* @param value - The value to compare against
|
||||
* @returns A {@link SQLFragment} representing the equality condition
|
||||
*/
|
||||
eq(value: TValue | null | undefined): SQLFragment<TFields> {
|
||||
if (value === null || value === undefined) {
|
||||
eq(value: TValue | null): SQLFragment<TFields> {
|
||||
if (value === null) {
|
||||
return this.isNull();
|
||||
}
|
||||
return sql`${this} = ${value}`;
|
||||
@@ -382,13 +388,13 @@ export class SQLChainableFragment<
|
||||
|
||||
/**
|
||||
* Generates an inequality condition (`!= value`).
|
||||
* Automatically converts `null`/`undefined` to `IS NOT NULL`.
|
||||
* Automatically converts `null` to `IS NOT NULL`.
|
||||
*
|
||||
* @param value - The value to compare against
|
||||
* @returns A {@link SQLFragment} representing the inequality condition
|
||||
*/
|
||||
neq(value: TValue | null | undefined): SQLFragment<TFields> {
|
||||
if (value === null || value === undefined) {
|
||||
neq(value: TValue | null): SQLFragment<TFields> {
|
||||
if (value === null) {
|
||||
return this.isNotNull();
|
||||
}
|
||||
return sql`${this} != ${value}`;
|
||||
@@ -564,7 +570,7 @@ export class SQLChainableFragment<
|
||||
* Allowed PostgreSQL type names for the cast() helper.
|
||||
* Only these types can be used to prevent SQL injection through type name interpolation.
|
||||
*/
|
||||
const ALLOWED_CAST_TYPES = [
|
||||
export const ALLOWED_CAST_TYPES = [
|
||||
'int',
|
||||
'integer',
|
||||
'int2',
|
||||
@@ -629,28 +635,52 @@ function resolveInnerExpr<TFields extends Record<string, any>>(
|
||||
// TValue from SQLChainableFragment (for type-safe value checking) while falling back to
|
||||
// SupportedSQLValue for plain SQLFragment inputs.
|
||||
|
||||
// Extract TFields from a SQLFragment type
|
||||
type ExtractFields<T> = T extends SQLFragment<infer F> ? F : never;
|
||||
/**
|
||||
* Extract TFields from a SQLFragment type.
|
||||
*/
|
||||
export type ExtractFragmentFields<T> = T extends SQLFragment<infer F> ? F : never;
|
||||
|
||||
// Conditional value types for expression overloads.
|
||||
// Uses SQLChainableFragment<any, ...> so that TExpr alone drives inference (single type param).
|
||||
type ExprValueNullable<TExpr> =
|
||||
TExpr extends SQLChainableFragment<any, infer TValue>
|
||||
? TValue | null | undefined
|
||||
: SupportedSQLValue;
|
||||
|
||||
type ExprValue<TExpr> =
|
||||
TExpr extends SQLChainableFragment<any, infer TValue> ? TValue : SupportedSQLValue;
|
||||
/**
|
||||
* The nullable value type accepted by an expression overload for the given fragment type.
|
||||
*/
|
||||
export type FragmentValueNullable<TFragment> =
|
||||
TFragment extends SQLChainableFragment<any, infer TValue> ? TValue | null : SupportedSQLValue;
|
||||
|
||||
type ExprValueArray<TExpr> =
|
||||
TExpr extends SQLChainableFragment<any, infer TValue>
|
||||
/**
|
||||
* The value type accepted by an expression overload for the given fragment type.
|
||||
*/
|
||||
export type FragmentValue<TFragment> =
|
||||
TFragment extends SQLChainableFragment<any, infer TValue> ? TValue : SupportedSQLValue;
|
||||
|
||||
/**
|
||||
* The array-of-values type accepted by an expression overload for the given fragment type.
|
||||
*/
|
||||
export type FragmentValueArray<TFragment> =
|
||||
TFragment extends SQLChainableFragment<any, infer TValue>
|
||||
? readonly TValue[]
|
||||
: readonly SupportedSQLValue[];
|
||||
|
||||
function inArrayHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
values: ExprValueArray<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates an `IN (...)` condition from a fragment and array of values.
|
||||
* Each array element becomes a separate bound parameter. Returns `FALSE` for empty arrays.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
* @param values - The values to check membership against
|
||||
*/
|
||||
function inArrayHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
values: FragmentValueArray<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates an `IN (...)` condition from a field name and array of values.
|
||||
* Each array element becomes a separate bound parameter. Returns `FALSE` for empty arrays.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
* @param values - The values to check membership against
|
||||
*/
|
||||
function inArrayHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -662,10 +692,24 @@ function inArrayHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).inArray(values);
|
||||
}
|
||||
|
||||
function anyArrayHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
values: ExprValueArray<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates an `= ANY(?)` condition from a fragment and array of values.
|
||||
* The array is bound as a single parameter for consistent query shape. Returns `FALSE` for empty arrays.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
* @param values - The values to check membership against
|
||||
*/
|
||||
function anyArrayHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
values: FragmentValueArray<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates an `= ANY(?)` condition from a field name and array of values.
|
||||
* The array is bound as a single parameter for consistent query shape. Returns `FALSE` for empty arrays.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
* @param values - The values to check membership against
|
||||
*/
|
||||
function anyArrayHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -677,10 +721,24 @@ function anyArrayHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).anyArray(values);
|
||||
}
|
||||
|
||||
function notInArrayHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
values: ExprValueArray<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates a `NOT IN (...)` condition from a fragment and array of values.
|
||||
* Each array element becomes a separate bound parameter. Returns `TRUE` for empty arrays.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
* @param values - The values to check non-membership against
|
||||
*/
|
||||
function notInArrayHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
values: FragmentValueArray<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a `NOT IN (...)` condition from a field name and array of values.
|
||||
* Each array element becomes a separate bound parameter. Returns `TRUE` for empty arrays.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
* @param values - The values to check non-membership against
|
||||
*/
|
||||
function notInArrayHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -692,11 +750,25 @@ function notInArrayHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).notInArray(values);
|
||||
}
|
||||
|
||||
function betweenHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
min: ExprValue<TExpr>,
|
||||
max: ExprValue<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates a `BETWEEN min AND max` condition (inclusive) from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
* @param min - The lower bound
|
||||
* @param max - The upper bound
|
||||
*/
|
||||
function betweenHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
min: FragmentValue<TFragment>,
|
||||
max: FragmentValue<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a `BETWEEN min AND max` condition (inclusive) from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
* @param min - The lower bound
|
||||
* @param max - The upper bound
|
||||
*/
|
||||
function betweenHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -709,11 +781,25 @@ function betweenHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).between(min, max);
|
||||
}
|
||||
|
||||
function notBetweenHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
min: ExprValue<TExpr>,
|
||||
max: ExprValue<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates a `NOT BETWEEN min AND max` condition from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
* @param min - The lower bound
|
||||
* @param max - The upper bound
|
||||
*/
|
||||
function notBetweenHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
min: FragmentValue<TFragment>,
|
||||
max: FragmentValue<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a `NOT BETWEEN min AND max` condition from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
* @param min - The lower bound
|
||||
* @param max - The upper bound
|
||||
*/
|
||||
function notBetweenHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -726,10 +812,22 @@ function notBetweenHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).notBetween(min, max);
|
||||
}
|
||||
|
||||
function likeHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* Generates a case-sensitive `LIKE` condition from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to match
|
||||
* @param pattern - The LIKE pattern (use `%` for wildcards, `_` for single character)
|
||||
*/
|
||||
function likeHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
pattern: string,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a case-sensitive `LIKE` condition from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to match
|
||||
* @param pattern - The LIKE pattern (use `%` for wildcards, `_` for single character)
|
||||
*/
|
||||
function likeHelper<TFields extends Record<string, any>, N extends PickStringValueKeys<TFields>>(
|
||||
fieldName: N,
|
||||
pattern: string,
|
||||
@@ -741,10 +839,22 @@ function likeHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).like(pattern);
|
||||
}
|
||||
|
||||
function notLikeHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* Generates a case-sensitive `NOT LIKE` condition from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to match
|
||||
* @param pattern - The LIKE pattern (use `%` for wildcards, `_` for single character)
|
||||
*/
|
||||
function notLikeHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
pattern: string,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a case-sensitive `NOT LIKE` condition from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to match
|
||||
* @param pattern - The LIKE pattern (use `%` for wildcards, `_` for single character)
|
||||
*/
|
||||
function notLikeHelper<TFields extends Record<string, any>, N extends PickStringValueKeys<TFields>>(
|
||||
fieldName: N,
|
||||
pattern: string,
|
||||
@@ -756,10 +866,22 @@ function notLikeHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).notLike(pattern);
|
||||
}
|
||||
|
||||
function ilikeHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* Generates a case-insensitive `ILIKE` condition from a fragment (PostgreSQL-specific).
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to match
|
||||
* @param pattern - The LIKE pattern (use `%` for wildcards, `_` for single character)
|
||||
*/
|
||||
function ilikeHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
pattern: string,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a case-insensitive `ILIKE` condition from a field name (PostgreSQL-specific).
|
||||
*
|
||||
* @param fieldName - The entity field name to match
|
||||
* @param pattern - The LIKE pattern (use `%` for wildcards, `_` for single character)
|
||||
*/
|
||||
function ilikeHelper<TFields extends Record<string, any>, N extends PickStringValueKeys<TFields>>(
|
||||
fieldName: N,
|
||||
pattern: string,
|
||||
@@ -771,10 +893,22 @@ function ilikeHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).ilike(pattern);
|
||||
}
|
||||
|
||||
function notIlikeHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* Generates a case-insensitive `NOT ILIKE` condition from a fragment (PostgreSQL-specific).
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to match
|
||||
* @param pattern - The LIKE pattern (use `%` for wildcards, `_` for single character)
|
||||
*/
|
||||
function notIlikeHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
pattern: string,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a case-insensitive `NOT ILIKE` condition from a field name (PostgreSQL-specific).
|
||||
*
|
||||
* @param fieldName - The entity field name to match
|
||||
* @param pattern - The LIKE pattern (use `%` for wildcards, `_` for single character)
|
||||
*/
|
||||
function notIlikeHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickStringValueKeys<TFields>,
|
||||
@@ -786,9 +920,19 @@ function notIlikeHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).notIlike(pattern);
|
||||
}
|
||||
|
||||
function isNullHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates an `IS NULL` condition from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
*/
|
||||
function isNullHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates an `IS NULL` condition from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
*/
|
||||
function isNullHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
): SQLFragment<TFields>;
|
||||
@@ -798,9 +942,19 @@ function isNullHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).isNull();
|
||||
}
|
||||
|
||||
function isNotNullHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates an `IS NOT NULL` condition from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
*/
|
||||
function isNotNullHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates an `IS NOT NULL` condition from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
*/
|
||||
function isNotNullHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
): SQLFragment<TFields>;
|
||||
@@ -810,10 +964,24 @@ function isNotNullHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).isNotNull();
|
||||
}
|
||||
|
||||
function eqHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
value: ExprValueNullable<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates an equality condition (`= value`) from a fragment.
|
||||
* Automatically converts `null` to `IS NULL`.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function eqHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
value: FragmentValueNullable<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates an equality condition (`= value`) from a field name.
|
||||
* Automatically converts `null` to `IS NULL`.
|
||||
*
|
||||
* @param fieldName - The entity field name to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function eqHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -825,10 +993,24 @@ function eqHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).eq(value);
|
||||
}
|
||||
|
||||
function neqHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
value: ExprValueNullable<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates an inequality condition (`!= value`) from a fragment.
|
||||
* Automatically converts `null` to `IS NOT NULL`.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function neqHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
value: FragmentValueNullable<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates an inequality condition (`!= value`) from a field name.
|
||||
* Automatically converts `null` to `IS NOT NULL`.
|
||||
*
|
||||
* @param fieldName - The entity field name to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function neqHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -840,10 +1022,22 @@ function neqHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).neq(value);
|
||||
}
|
||||
|
||||
function gtHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
value: ExprValue<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates a greater-than condition (`> value`) from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function gtHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
value: FragmentValue<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a greater-than condition (`> value`) from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function gtHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -855,10 +1049,22 @@ function gtHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).gt(value);
|
||||
}
|
||||
|
||||
function gteHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
value: ExprValue<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates a greater-than-or-equal-to condition (`>= value`) from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function gteHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
value: FragmentValue<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a greater-than-or-equal-to condition (`>= value`) from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function gteHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -870,10 +1076,22 @@ function gteHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).gte(value);
|
||||
}
|
||||
|
||||
function ltHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
value: ExprValue<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates a less-than condition (`< value`) from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function ltHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
value: FragmentValue<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a less-than condition (`< value`) from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function ltHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -885,10 +1103,22 @@ function ltHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).lt(value);
|
||||
}
|
||||
|
||||
function lteHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
value: ExprValue<TExpr>,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
/**
|
||||
* Generates a less-than-or-equal-to condition (`<= value`) from a fragment.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function lteHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
value: FragmentValue<TFragment>,
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a less-than-or-equal-to condition (`<= value`) from a field name.
|
||||
*
|
||||
* @param fieldName - The entity field name to compare
|
||||
* @param value - The value to compare against
|
||||
*/
|
||||
function lteHelper<
|
||||
TFields extends Record<string, any>,
|
||||
N extends PickSupportedSQLValueKeys<TFields>,
|
||||
@@ -900,10 +1130,24 @@ function lteHelper<TFields extends Record<string, any>>(
|
||||
return resolveInnerExpr(expressionOrFieldName).lte(value);
|
||||
}
|
||||
|
||||
function jsonContainsHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* Generates a JSON contains condition (`@>`) from a fragment.
|
||||
* Tests whether the JSON value contains the given value.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
* @param value - The JSON value to check containment of
|
||||
*/
|
||||
function jsonContainsHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
value: JsonSerializable,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a JSON contains condition (`@>`) from a field name.
|
||||
* Tests whether the JSON value contains the given value.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
* @param value - The JSON value to check containment of
|
||||
*/
|
||||
function jsonContainsHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
value: JsonSerializable,
|
||||
@@ -921,10 +1165,24 @@ function jsonContainsHelper<TFields extends Record<string, any>>(
|
||||
return sql`${inner} @> ${serialized}::jsonb`;
|
||||
}
|
||||
|
||||
function jsonContainedByHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* Generates a JSON contained-by condition (`<@`) from a fragment.
|
||||
* Tests whether the JSON value is contained by the given value.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to check
|
||||
* @param value - The JSON value to check containment against
|
||||
*/
|
||||
function jsonContainedByHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
value: JsonSerializable,
|
||||
): SQLFragment<ExtractFields<TExpr>>;
|
||||
): SQLFragment<ExtractFragmentFields<TFragment>>;
|
||||
/**
|
||||
* Generates a JSON contained-by condition (`<@`) from a field name.
|
||||
* Tests whether the JSON value is contained by the given value.
|
||||
*
|
||||
* @param fieldName - The entity field name to check
|
||||
* @param value - The JSON value to check containment against
|
||||
*/
|
||||
function jsonContainedByHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
value: JsonSerializable,
|
||||
@@ -942,10 +1200,24 @@ function jsonContainedByHelper<TFields extends Record<string, any>>(
|
||||
return sql`${inner} <@ ${serialized}::jsonb`;
|
||||
}
|
||||
|
||||
function jsonPathHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* JSON path extraction (`->`) from a fragment. Returns JSON.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to extract from
|
||||
* @param path - The JSON key to extract
|
||||
*/
|
||||
function jsonPathHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
path: string,
|
||||
): SQLChainableFragment<ExtractFields<TExpr>, SupportedSQLValue>;
|
||||
): SQLChainableFragment<ExtractFragmentFields<TFragment>, SupportedSQLValue>;
|
||||
/**
|
||||
* JSON path extraction (`->`) from a field name. Returns JSON.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fieldName - The entity field name to extract from
|
||||
* @param path - The JSON key to extract
|
||||
*/
|
||||
function jsonPathHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
path: string,
|
||||
@@ -959,10 +1231,24 @@ function jsonPathHelper<TFields extends Record<string, any>>(
|
||||
return new SQLChainableFragment(wrapped.sql, wrapped.bindings);
|
||||
}
|
||||
|
||||
function jsonPathTextHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* JSON path text extraction (`->>`) from a fragment. Returns text.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to extract from
|
||||
* @param path - The JSON key to extract as text
|
||||
*/
|
||||
function jsonPathTextHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
path: string,
|
||||
): SQLChainableFragment<ExtractFields<TExpr>, SupportedSQLValue>;
|
||||
): SQLChainableFragment<ExtractFragmentFields<TFragment>, SupportedSQLValue>;
|
||||
/**
|
||||
* JSON path text extraction (`->>`) from a field name. Returns text.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fieldName - The entity field name to extract from
|
||||
* @param path - The JSON key to extract as text
|
||||
*/
|
||||
function jsonPathTextHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
path: string,
|
||||
@@ -976,10 +1262,24 @@ function jsonPathTextHelper<TFields extends Record<string, any>>(
|
||||
return new SQLChainableFragment(wrapped.sql, wrapped.bindings);
|
||||
}
|
||||
|
||||
function jsonDeepPathHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* JSON deep path extraction (`#>`) from a fragment. Returns JSON at the specified key path.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to extract from
|
||||
* @param path - Array of keys forming the path (e.g., ['user', 'address', 'city'])
|
||||
*/
|
||||
function jsonDeepPathHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
path: readonly string[],
|
||||
): SQLChainableFragment<ExtractFields<TExpr>, SupportedSQLValue>;
|
||||
): SQLChainableFragment<ExtractFragmentFields<TFragment>, SupportedSQLValue>;
|
||||
/**
|
||||
* JSON deep path extraction (`#>`) from a field name. Returns JSON at the specified key path.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fieldName - The entity field name to extract from
|
||||
* @param path - Array of keys forming the path (e.g., ['user', 'address', 'city'])
|
||||
*/
|
||||
function jsonDeepPathHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
path: readonly string[],
|
||||
@@ -994,10 +1294,24 @@ function jsonDeepPathHelper<TFields extends Record<string, any>>(
|
||||
return new SQLChainableFragment(wrapped.sql, wrapped.bindings);
|
||||
}
|
||||
|
||||
function jsonDeepPathTextHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* JSON deep path text extraction (`#>>`) from a fragment. Returns text at the specified key path.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to extract from
|
||||
* @param path - Array of keys forming the path (e.g., ['user', 'address', 'city'])
|
||||
*/
|
||||
function jsonDeepPathTextHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
path: readonly string[],
|
||||
): SQLChainableFragment<ExtractFields<TExpr>, SupportedSQLValue>;
|
||||
): SQLChainableFragment<ExtractFragmentFields<TFragment>, SupportedSQLValue>;
|
||||
/**
|
||||
* JSON deep path text extraction (`#>>`) from a field name. Returns text at the specified key path.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fieldName - The entity field name to extract from
|
||||
* @param path - Array of keys forming the path (e.g., ['user', 'address', 'city'])
|
||||
*/
|
||||
function jsonDeepPathTextHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
path: readonly string[],
|
||||
@@ -1012,10 +1326,24 @@ function jsonDeepPathTextHelper<TFields extends Record<string, any>>(
|
||||
return new SQLChainableFragment(wrapped.sql, wrapped.bindings);
|
||||
}
|
||||
|
||||
function castHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
/**
|
||||
* SQL type cast (`::type`) from a fragment.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to cast
|
||||
* @param typeName - The PostgreSQL type name (e.g., 'int', 'text', 'timestamptz')
|
||||
*/
|
||||
function castHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
typeName: PostgresCastType,
|
||||
): SQLChainableFragment<ExtractFields<TExpr>, SupportedSQLValue>;
|
||||
): SQLChainableFragment<ExtractFragmentFields<TFragment>, SupportedSQLValue>;
|
||||
/**
|
||||
* SQL type cast (`::type`) from a field name.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fieldName - The entity field name to cast
|
||||
* @param typeName - The PostgreSQL type name (e.g., 'int', 'text', 'timestamptz')
|
||||
*/
|
||||
function castHelper<TFields extends Record<string, any>, N extends keyof TFields>(
|
||||
fieldName: N,
|
||||
typeName: PostgresCastType,
|
||||
@@ -1033,9 +1361,21 @@ function castHelper<TFields extends Record<string, any>>(
|
||||
return new SQLChainableFragment(wrapped.sql, wrapped.bindings);
|
||||
}
|
||||
|
||||
function lowerHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
): SQLChainableFragment<ExtractFields<TExpr>, SupportedSQLValue>;
|
||||
/**
|
||||
* Wraps a fragment in `LOWER()` to convert to lowercase.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to convert
|
||||
*/
|
||||
function lowerHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
): SQLChainableFragment<ExtractFragmentFields<TFragment>, SupportedSQLValue>;
|
||||
/**
|
||||
* Wraps a field in `LOWER()` to convert to lowercase.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fieldName - The entity field name to convert
|
||||
*/
|
||||
function lowerHelper<TFields extends Record<string, any>, N extends PickStringValueKeys<TFields>>(
|
||||
fieldName: N,
|
||||
): SQLChainableFragment<TFields, TFields[N]>;
|
||||
@@ -1047,9 +1387,21 @@ function lowerHelper<TFields extends Record<string, any>>(
|
||||
return new SQLChainableFragment(wrapped.sql, wrapped.bindings);
|
||||
}
|
||||
|
||||
function upperHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
): SQLChainableFragment<ExtractFields<TExpr>, SupportedSQLValue>;
|
||||
/**
|
||||
* Wraps a fragment in `UPPER()` to convert to uppercase.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to convert
|
||||
*/
|
||||
function upperHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
): SQLChainableFragment<ExtractFragmentFields<TFragment>, SupportedSQLValue>;
|
||||
/**
|
||||
* Wraps a field in `UPPER()` to convert to uppercase.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fieldName - The entity field name to convert
|
||||
*/
|
||||
function upperHelper<TFields extends Record<string, any>, N extends PickStringValueKeys<TFields>>(
|
||||
fieldName: N,
|
||||
): SQLChainableFragment<TFields, TFields[N]>;
|
||||
@@ -1061,9 +1413,21 @@ function upperHelper<TFields extends Record<string, any>>(
|
||||
return new SQLChainableFragment(wrapped.sql, wrapped.bindings);
|
||||
}
|
||||
|
||||
function trimHelper<TExpr extends SQLFragment<any>>(
|
||||
expression: TExpr,
|
||||
): SQLChainableFragment<ExtractFields<TExpr>, SupportedSQLValue>;
|
||||
/**
|
||||
* Wraps a fragment in `TRIM()` to remove leading and trailing whitespace.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fragment - A SQLFragment or SQLChainableFragment to trim
|
||||
*/
|
||||
function trimHelper<TFragment extends SQLFragment<any>>(
|
||||
fragment: TFragment,
|
||||
): SQLChainableFragment<ExtractFragmentFields<TFragment>, SupportedSQLValue>;
|
||||
/**
|
||||
* Wraps a field in `TRIM()` to remove leading and trailing whitespace.
|
||||
* Returns an SQLChainableFragment for fluent chaining.
|
||||
*
|
||||
* @param fieldName - The entity field name to trim
|
||||
*/
|
||||
function trimHelper<TFields extends Record<string, any>, N extends PickStringValueKeys<TFields>>(
|
||||
fieldName: N,
|
||||
): SQLChainableFragment<TFields, TFields[N]>;
|
||||
@@ -1173,12 +1537,12 @@ export const SQLExpression = {
|
||||
isNotNull: isNotNullHelper,
|
||||
|
||||
/**
|
||||
* Equality operator. Automatically converts null/undefined to IS NULL.
|
||||
* Equality operator. Automatically converts null to IS NULL.
|
||||
*/
|
||||
eq: eqHelper,
|
||||
|
||||
/**
|
||||
* Inequality operator. Automatically converts null/undefined to IS NOT NULL.
|
||||
* Inequality operator. Automatically converts null to IS NOT NULL.
|
||||
*/
|
||||
neq: neqHelper,
|
||||
|
||||
|
||||
+652
-116
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
EntityDatabaseAdapterEmptyUpdateResultError,
|
||||
EntityNotFoundError,
|
||||
TransactionIsolationLevel,
|
||||
ViewerContext,
|
||||
} from '@expo/entity';
|
||||
@@ -211,6 +212,491 @@ describe('postgres entity integration', () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe('row locking modifiers (forUpdate, forShare, skipLocked)', () => {
|
||||
// Attempts to lock the row from a separate connection without waiting. Postgres raises
|
||||
// lock_not_available (55P03) when another transaction already holds a conflicting lock on the row.
|
||||
const tryLockRowFromOtherConnectionAsync = async (
|
||||
id: string,
|
||||
lockMode: 'FOR UPDATE' | 'FOR SHARE' = 'FOR UPDATE',
|
||||
): Promise<string | null> => {
|
||||
try {
|
||||
await knexInstance.raw(
|
||||
`SELECT * FROM postgres_test_entities WHERE id = ? ${lockMode} NOWAIT`,
|
||||
[id],
|
||||
);
|
||||
return null;
|
||||
} catch (e) {
|
||||
return (e as any).code ?? null;
|
||||
}
|
||||
};
|
||||
|
||||
it('locks rows loaded with loadManyByFieldEqualityConjunctionAsync until the transaction ends', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'locked')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
// not locked before the transaction
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBeNull();
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
const results = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadManyByFieldEqualityConjunctionAsync([{ fieldName: 'name', fieldValue: 'locked' }], {
|
||||
forUpdate: true,
|
||||
});
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0]!.getID()).toBe(entity.getID());
|
||||
|
||||
// locked while the transaction is open
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBe('55P03');
|
||||
});
|
||||
|
||||
// unlocked after the transaction commits
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBeNull();
|
||||
});
|
||||
|
||||
it('locks rows loaded with loadFirstByFieldEqualityConjunctionAsync', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'locked-first')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
const result = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadFirstByFieldEqualityConjunctionAsync(
|
||||
[{ fieldName: 'name', fieldValue: 'locked-first' }],
|
||||
{
|
||||
orderBy: [{ fieldName: 'name', order: OrderByOrdering.ASCENDING }],
|
||||
forUpdate: true,
|
||||
},
|
||||
);
|
||||
expect(result?.getID()).toBe(entity.getID());
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBe('55P03');
|
||||
});
|
||||
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBeNull();
|
||||
});
|
||||
|
||||
it('locks rows loaded with the loadManyBySQL query builder', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'locked-sql')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
// via the fluent builder method
|
||||
const results = await PostgresTestEntity.knexLoader(vc1, queryContext)
|
||||
.loadManyBySQL(sql`name = ${'locked-sql'}`)
|
||||
.forUpdate()
|
||||
.executeAsync();
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0]!.getID()).toBe(entity.getID());
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBe('55P03');
|
||||
|
||||
// via the modifiers argument on the authorization-result-based loader
|
||||
const authorizationResults = await PostgresTestEntity.knexLoaderWithAuthorizationResults(
|
||||
vc1,
|
||||
queryContext,
|
||||
)
|
||||
.loadManyBySQL(sql`name = ${'locked-sql'}`, { forUpdate: true })
|
||||
.executeAsync();
|
||||
expect(authorizationResults).toHaveLength(1);
|
||||
expect(authorizationResults[0]!.enforceValue().getID()).toBe(entity.getID());
|
||||
});
|
||||
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBeNull();
|
||||
});
|
||||
|
||||
it('blocks a concurrent forUpdate load until the first transaction completes', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'counter')
|
||||
.setField('hasADog', false)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const events: string[] = [];
|
||||
const lockAndUpdateAsync = async (label: string, holdDuration: number): Promise<void> => {
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync(
|
||||
'postgres',
|
||||
async (queryContext) => {
|
||||
const locked = await PostgresTestEntity.knexLoader(vc1, queryContext)
|
||||
.loadManyBySQL(sql`id = ${entity.getID()}`)
|
||||
.forUpdate()
|
||||
.executeAsync();
|
||||
events.push(`${label}:locked`);
|
||||
await setTimeout(holdDuration);
|
||||
await PostgresTestEntity.updater(locked[0]!, queryContext)
|
||||
.setField('name', locked[0]!.getField('name') + ',' + label)
|
||||
.updateAsync();
|
||||
events.push(`${label}:updated`);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
await Promise.all([
|
||||
lockAndUpdateAsync('a', 200),
|
||||
setTimeout(50).then(() => lockAndUpdateAsync('b', 0)),
|
||||
]);
|
||||
|
||||
// b cannot acquire the lock until a commits, so a's update always lands before b locks
|
||||
expect(events).toEqual(['a:locked', 'a:updated', 'b:locked', 'b:updated']);
|
||||
|
||||
const reloaded = await PostgresTestEntity.loader(vc1).loadByIDAsync(entity.getID());
|
||||
expect(reloaded.getField('name')).toBe('counter,a,b');
|
||||
});
|
||||
|
||||
it('forShare allows concurrent share locks but blocks update locks', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'shared')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
const results = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadManyByFieldEqualityConjunctionAsync([{ fieldName: 'name', fieldValue: 'shared' }], {
|
||||
forShare: true,
|
||||
});
|
||||
expect(results).toHaveLength(1);
|
||||
|
||||
// another share lock is compatible, an update lock is not
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID(), 'FOR SHARE')).toBeNull();
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID(), 'FOR UPDATE')).toBe(
|
||||
'55P03',
|
||||
);
|
||||
|
||||
// via the fluent builder method
|
||||
const builderResults = await PostgresTestEntity.knexLoader(vc1, queryContext)
|
||||
.loadManyBySQL(sql`name = ${'shared'}`)
|
||||
.forShare()
|
||||
.executeAsync();
|
||||
expect(builderResults).toHaveLength(1);
|
||||
});
|
||||
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID(), 'FOR UPDATE')).toBeNull();
|
||||
});
|
||||
|
||||
it('skipLocked skips rows locked by another transaction', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entityA = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'queue')
|
||||
.createAsync(),
|
||||
);
|
||||
const entityB = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'queue')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync(
|
||||
'postgres',
|
||||
async (outerQueryContext) => {
|
||||
// lock entityA in the outer transaction
|
||||
const locked = await PostgresTestEntity.knexLoader(vc1, outerQueryContext)
|
||||
.loadManyBySQL(sql`id = ${entityA.getID()}`)
|
||||
.forUpdate()
|
||||
.executeAsync();
|
||||
expect(locked.map((e) => e.getID())).toEqual([entityA.getID()]);
|
||||
|
||||
// a second transaction on another connection sees only the unlocked row
|
||||
const vc2 = new ViewerContext(
|
||||
createKnexIntegrationTestEntityCompanionProvider(knexInstance),
|
||||
);
|
||||
await vc2.runInTransactionForDatabaseAdapterFlavorAsync(
|
||||
'postgres',
|
||||
async (innerQueryContext) => {
|
||||
const skipLockedResults = await PostgresTestEntity.knexLoader(
|
||||
vc2,
|
||||
innerQueryContext,
|
||||
).loadManyByFieldEqualityConjunctionAsync(
|
||||
[{ fieldName: 'name', fieldValue: 'queue' }],
|
||||
{ forUpdate: true, skipLocked: true },
|
||||
);
|
||||
expect(skipLockedResults.map((e) => e.getID())).toEqual([entityB.getID()]);
|
||||
|
||||
const builderResults = await PostgresTestEntity.knexLoader(vc2, innerQueryContext)
|
||||
.loadManyBySQL(sql`name = ${'queue'}`)
|
||||
.forShare()
|
||||
.skipLocked()
|
||||
.executeAsync();
|
||||
expect(builderResults.map((e) => e.getID())).toEqual([entityB.getID()]);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// both rows are visible once the outer transaction commits
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
const results = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadManyByFieldEqualityConjunctionAsync([{ fieldName: 'name', fieldValue: 'queue' }], {
|
||||
forUpdate: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
expect(results).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when forUpdate or forShare is used outside of a transaction', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1).loadManyByFieldEqualityConjunctionAsync([], {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).rejects.toThrow('require a transactional query context');
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1).loadManyByFieldEqualityConjunctionAsync([], {
|
||||
forShare: true,
|
||||
}),
|
||||
).rejects.toThrow('require a transactional query context');
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1)
|
||||
.loadManyBySQL(sql`TRUE`)
|
||||
.forUpdate()
|
||||
.executeAsync(),
|
||||
).rejects.toThrow('require a transactional query context');
|
||||
});
|
||||
|
||||
it('throws for invalid row locking modifier combinations', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1, queryContext)
|
||||
.loadManyBySQL(sql`TRUE`)
|
||||
.forUpdate()
|
||||
.forShare()
|
||||
.executeAsync(),
|
||||
).rejects.toThrow('forUpdate and forShare are mutually exclusive');
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1, queryContext)
|
||||
.loadManyBySQL(sql`TRUE`)
|
||||
.skipLocked()
|
||||
.executeAsync(),
|
||||
).rejects.toThrow('skipLocked requires forUpdate or forShare');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FromDatabase load methods', () => {
|
||||
const tryLockRowFromOtherConnectionAsync = async (id: string): Promise<string | null> => {
|
||||
try {
|
||||
await knexInstance.raw(
|
||||
'SELECT * FROM postgres_test_entities WHERE id = ? FOR UPDATE NOWAIT',
|
||||
[id],
|
||||
);
|
||||
return null;
|
||||
} catch (e) {
|
||||
return (e as any).code ?? null;
|
||||
}
|
||||
};
|
||||
|
||||
it('loadByIDFromDatabaseAsync locks the row and throws EntityNotFoundError when missing', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'by-id')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
const loaded = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadByIDFromDatabaseAsync(entity.getID(), { forUpdate: true });
|
||||
expect(loaded.getID()).toBe(entity.getID());
|
||||
expect(loaded.getField('name')).toBe('by-id');
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBe('55P03');
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1, queryContext).loadByIDFromDatabaseAsync(
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
{ forUpdate: true },
|
||||
),
|
||||
).rejects.toThrow(EntityNotFoundError);
|
||||
|
||||
const nullable = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadByIDNullableFromDatabaseAsync('00000000-0000-0000-0000-000000000000', {
|
||||
forUpdate: true,
|
||||
});
|
||||
expect(nullable).toBeNull();
|
||||
});
|
||||
|
||||
expect(await tryLockRowFromOtherConnectionAsync(entity.getID())).toBeNull();
|
||||
});
|
||||
|
||||
it('loadManyByIDsFromDatabaseAsync returns a map and throws for missing IDs', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entityA = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1).setField('name', 'a').createAsync(),
|
||||
);
|
||||
const entityB = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1).setField('name', 'b').createAsync(),
|
||||
);
|
||||
const missingId = '00000000-0000-0000-0000-000000000000';
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
const loaded = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadManyByIDsFromDatabaseAsync([entityA.getID(), entityB.getID()], { forShare: true });
|
||||
expect(loaded.size).toBe(2);
|
||||
expect(loaded.get(entityA.getID())!.getField('name')).toBe('a');
|
||||
expect(loaded.get(entityB.getID())!.getField('name')).toBe('b');
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1, queryContext).loadManyByIDsFromDatabaseAsync(
|
||||
[entityA.getID(), missingId],
|
||||
{ forShare: true },
|
||||
),
|
||||
).rejects.toThrow(EntityNotFoundError);
|
||||
|
||||
const nullable = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadManyByIDsNullableFromDatabaseAsync([entityA.getID(), missingId], {
|
||||
forShare: true,
|
||||
});
|
||||
expect(nullable.size).toBe(2);
|
||||
expect(nullable.get(entityA.getID())!.getField('name')).toBe('a');
|
||||
expect(nullable.get(missingId)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('loadManyByIDsNullableFromDatabaseAsync with skipLocked returns null for locked rows', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const entityA = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1).setField('name', 'a').createAsync(),
|
||||
);
|
||||
const entityB = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1).setField('name', 'b').createAsync(),
|
||||
);
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync(
|
||||
'postgres',
|
||||
async (outerQueryContext) => {
|
||||
await PostgresTestEntity.knexLoader(vc1, outerQueryContext).loadByIDFromDatabaseAsync(
|
||||
entityA.getID(),
|
||||
{ forUpdate: true },
|
||||
);
|
||||
|
||||
const vc2 = new ViewerContext(
|
||||
createKnexIntegrationTestEntityCompanionProvider(knexInstance),
|
||||
);
|
||||
await vc2.runInTransactionForDatabaseAdapterFlavorAsync(
|
||||
'postgres',
|
||||
async (innerQueryContext) => {
|
||||
const results = await PostgresTestEntity.knexLoader(
|
||||
vc2,
|
||||
innerQueryContext,
|
||||
).loadManyByIDsNullableFromDatabaseAsync([entityA.getID(), entityB.getID()], {
|
||||
forUpdate: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
expect(results.get(entityA.getID())).toBeNull();
|
||||
expect(results.get(entityB.getID())!.getField('name')).toBe('b');
|
||||
|
||||
// the throwing variants do not permit skipLocked since a skipped row would be reported as not found
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc2, innerQueryContext).loadByIDFromDatabaseAsync(
|
||||
entityB.getID(),
|
||||
// @ts-expect-error skipLocked is not permitted for throwing FromDatabase methods
|
||||
{ forUpdate: true, skipLocked: true },
|
||||
),
|
||||
).resolves.toBeDefined();
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('loadByFieldEqualingFromDatabaseAsync and loadManyByFieldEqualingFromDatabaseAsync lock matching rows', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
const unique = await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'unique')
|
||||
.createAsync(),
|
||||
);
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'dup')
|
||||
.createAsync(),
|
||||
);
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'dup')
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdapterFlavorAsync('postgres', async (queryContext) => {
|
||||
const loaded = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadByFieldEqualingFromDatabaseAsync('name', 'unique', { forUpdate: true });
|
||||
expect(loaded!.getID()).toBe(unique.getID());
|
||||
expect(await tryLockRowFromOtherConnectionAsync(unique.getID())).toBe('55P03');
|
||||
|
||||
const missing = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadByFieldEqualingFromDatabaseAsync('name', 'nope', { forUpdate: true });
|
||||
expect(missing).toBeNull();
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1, queryContext).loadByFieldEqualingFromDatabaseAsync(
|
||||
'name',
|
||||
'dup',
|
||||
{ forUpdate: true },
|
||||
),
|
||||
).rejects.toThrow('Multiple entities of type PostgresTestEntity found for name=dup');
|
||||
|
||||
const many = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
queryContext,
|
||||
).loadManyByFieldEqualingFromDatabaseAsync('name', 'dup', { forUpdate: true });
|
||||
expect(many).toHaveLength(2);
|
||||
for (const e of many) {
|
||||
expect(await tryLockRowFromOtherConnectionAsync(e.getID())).toBe('55P03');
|
||||
}
|
||||
});
|
||||
|
||||
expect(await tryLockRowFromOtherConnectionAsync(unique.getID())).toBeNull();
|
||||
});
|
||||
|
||||
it('FromDatabase methods require a transaction when a lock is requested', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1).loadByIDFromDatabaseAsync(
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
{ forUpdate: true },
|
||||
),
|
||||
).rejects.toThrow('require a transactional query context');
|
||||
});
|
||||
});
|
||||
|
||||
describe('JSON fields', () => {
|
||||
it('supports both types of array fields', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
@@ -959,6 +1445,103 @@ describe('postgres entity integration', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('counting with countBySQLAsync', () => {
|
||||
it('counts entities matching a SQL fragment', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'Alice')
|
||||
.setField('hasACat', true)
|
||||
.setField('hasADog', false)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'Bob')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'Charlie')
|
||||
.setField('hasACat', true)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const catOwnerCount = await PostgresTestEntity.knexLoader(vc1).countBySQLAsync(
|
||||
sql`has_a_cat = ${true}`,
|
||||
);
|
||||
expect(catOwnerCount).toBe(2);
|
||||
|
||||
const dogOwnerCount = await PostgresTestEntity.knexLoader(vc1).countBySQLAsync(
|
||||
sql`has_a_dog = ${true}`,
|
||||
);
|
||||
expect(dogOwnerCount).toBe(2);
|
||||
|
||||
const allCount = await PostgresTestEntity.knexLoader(vc1).countBySQLAsync(sql`TRUE`);
|
||||
expect(allCount).toBe(3);
|
||||
|
||||
const noneCount = await PostgresTestEntity.knexLoader(vc1).countBySQLAsync(sql`FALSE`);
|
||||
expect(noneCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('counting with countByFieldEqualityConjunctionAsync', () => {
|
||||
it('counts entities matching field equality conditions', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'world')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'wat')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', false)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const count1 = await PostgresTestEntity.knexLoader(vc1).countByFieldEqualityConjunctionAsync([
|
||||
{ fieldName: 'hasACat', fieldValue: false },
|
||||
{ fieldName: 'hasADog', fieldValue: true },
|
||||
]);
|
||||
expect(count1).toBe(2);
|
||||
|
||||
const count2 = await PostgresTestEntity.knexLoader(vc1).countByFieldEqualityConjunctionAsync([
|
||||
{ fieldName: 'hasADog', fieldValues: [true, false] },
|
||||
]);
|
||||
expect(count2).toBe(3);
|
||||
|
||||
const count3 = await PostgresTestEntity.knexLoader(vc1).countByFieldEqualityConjunctionAsync([
|
||||
{ fieldName: 'name', fieldValue: 'hello' },
|
||||
]);
|
||||
expect(count3).toBe(1);
|
||||
|
||||
const count4 = await PostgresTestEntity.knexLoader(vc1).countByFieldEqualityConjunctionAsync(
|
||||
[],
|
||||
);
|
||||
expect(count4).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('conjunction field equality loading', () => {
|
||||
it('supports single fieldValue and multiple fieldValues', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
@@ -1085,6 +1668,49 @@ describe('postgres entity integration', () => {
|
||||
expect(results.map((e) => e.getField('name'))).toEqual(['alpha', 'gamma', 'beta']);
|
||||
});
|
||||
|
||||
it('supports fieldFragment orderBy with entityField', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'alpha')
|
||||
.setField('hasACat', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'beta')
|
||||
.setField('hasACat', false)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'gamma')
|
||||
.setField('hasACat', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
// Order by entityField references, which translate entity field names to DB column names
|
||||
const results = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
).loadManyByFieldEqualityConjunctionAsync([], {
|
||||
orderBy: [
|
||||
{
|
||||
fieldFragment: sql`${entityField('hasACat')}`,
|
||||
order: OrderByOrdering.DESCENDING,
|
||||
},
|
||||
{
|
||||
fieldFragment: sql`${entityField('name')}`,
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(results).toHaveLength(3);
|
||||
expect(results.map((e) => e.getField('name'))).toEqual(['alpha', 'gamma', 'beta']);
|
||||
});
|
||||
|
||||
it('rejects fieldFragment containing trailing ASC or DESC', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
@@ -1165,122 +1791,6 @@ describe('postgres entity integration', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('raw where clause loading', () => {
|
||||
it('loads by raw where clause', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const results = await PostgresTestEntity.knexLoader(vc1).loadManyByRawWhereClauseAsync(
|
||||
'name = ?',
|
||||
['hello'],
|
||||
);
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('throws with invalid where clause', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'hello')
|
||||
.setField('hasACat', false)
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc1).loadManyByRawWhereClauseAsync('invalid_column = ?', [
|
||||
'hello',
|
||||
]),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('supports query modifiers', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'a')
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'b')
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
await enforceAsyncResult(
|
||||
PostgresTestEntity.creatorWithAuthorizationResults(vc1)
|
||||
.setField('name', 'c')
|
||||
.setField('hasADog', true)
|
||||
.createAsync(),
|
||||
);
|
||||
|
||||
const results = await PostgresTestEntity.knexLoader(vc1).loadManyByRawWhereClauseAsync(
|
||||
'has_a_dog = ?',
|
||||
[true],
|
||||
{
|
||||
limit: 2,
|
||||
offset: 1,
|
||||
orderBy: [
|
||||
{
|
||||
fieldName: 'name',
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results.map((e) => e.getField('name'))).toEqual(['b', 'c']);
|
||||
|
||||
const resultsMultipleOrderBy = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
).loadManyByRawWhereClauseAsync('has_a_dog = ?', [true], {
|
||||
orderBy: [
|
||||
{
|
||||
fieldName: 'hasADog',
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
},
|
||||
{
|
||||
fieldName: 'name',
|
||||
order: OrderByOrdering.DESCENDING,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(resultsMultipleOrderBy).toHaveLength(3);
|
||||
expect(resultsMultipleOrderBy.map((e) => e.getField('name'))).toEqual(['c', 'b', 'a']);
|
||||
|
||||
const resultsOrderByRaw = await PostgresTestEntity.knexLoader(
|
||||
vc1,
|
||||
).loadManyByRawWhereClauseAsync('has_a_dog = ?', [true], {
|
||||
orderBy: [
|
||||
{
|
||||
fieldFragment: sql`${entityField('hasADog')}`,
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
},
|
||||
{
|
||||
fieldFragment: sql`${entityField('name')}`,
|
||||
order: OrderByOrdering.DESCENDING,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(resultsOrderByRaw).toHaveLength(3);
|
||||
expect(resultsOrderByRaw.map((e) => e.getField('name'))).toEqual(['c', 'b', 'a']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trigger transaction behavior', () => {
|
||||
describe('create', () => {
|
||||
it('rolls back transaction when trigger throws except afterCommit', async () => {
|
||||
@@ -2196,6 +2706,32 @@ describe('postgres entity integration', () => {
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("Cursor is missing required 'id' field.");
|
||||
|
||||
// Try with valid base64-encoded JSON that decodes to a non-object primitive
|
||||
const primitiveCursor = Buffer.from(JSON.stringify(12345)).toString('base64url');
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc).loadPageAsync({
|
||||
first: 10,
|
||||
after: primitiveCursor,
|
||||
pagination: {
|
||||
strategy: PaginationStrategy.STANDARD,
|
||||
orderBy: [],
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("Cursor is missing required 'id' field.");
|
||||
|
||||
// Try with valid base64-encoded JSON string primitive
|
||||
const stringPrimitiveCursor = Buffer.from(JSON.stringify('hello')).toString('base64url');
|
||||
await expect(
|
||||
PostgresTestEntity.knexLoader(vc).loadPageAsync({
|
||||
first: 10,
|
||||
after: stringPrimitiveCursor,
|
||||
pagination: {
|
||||
strategy: PaginationStrategy.STANDARD,
|
||||
orderBy: [],
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("Cursor is missing required 'id' field.");
|
||||
});
|
||||
|
||||
it('performs pagination with both loader types', async () => {
|
||||
|
||||
+353
-77
@@ -3,9 +3,14 @@ import type {
|
||||
EntityQueryContext,
|
||||
IEntityMetricsAdapter,
|
||||
} from '@expo/entity';
|
||||
import { enforceResultsAsync, EntityConstructionUtils, ViewerContext } from '@expo/entity';
|
||||
import {
|
||||
enforceResultsAsync,
|
||||
EntityConstructionUtils,
|
||||
EntityNotFoundError,
|
||||
ViewerContext,
|
||||
} from '@expo/entity';
|
||||
import { describe, expect, it } from '@jest/globals';
|
||||
import { anyOfClass, anything, instance, mock, spy, verify, when } from 'ts-mockito';
|
||||
import { anyOfClass, anything, deepEqual, instance, mock, spy, verify, when } from 'ts-mockito';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { AuthorizationResultBasedKnexEntityLoader } from '../AuthorizationResultBasedKnexEntityLoader.ts';
|
||||
@@ -87,6 +92,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
);
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -170,6 +177,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
);
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -205,81 +214,6 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
).once();
|
||||
});
|
||||
|
||||
it('loads entities with loadManyByRawWhereClauseAsync', async () => {
|
||||
const privacyPolicy = new TestEntityPrivacyPolicy();
|
||||
const spiedPrivacyPolicy = spy(privacyPolicy);
|
||||
const viewerContext = instance(mock(ViewerContext));
|
||||
const privacyPolicyEvaluationContext =
|
||||
instance(
|
||||
mock<
|
||||
EntityPrivacyPolicyEvaluationContext<
|
||||
TestFields,
|
||||
'customIdField',
|
||||
ViewerContext,
|
||||
TestEntity
|
||||
>
|
||||
>(),
|
||||
);
|
||||
const metricsAdapter = instance(mock<IEntityMetricsAdapter>());
|
||||
const queryContext = instance(mock<EntityQueryContext>());
|
||||
|
||||
const knexDataManagerMock =
|
||||
mock<EntityKnexDataManager<TestFields, 'customIdField'>>(EntityKnexDataManager);
|
||||
when(
|
||||
knexDataManagerMock.loadManyByRawWhereClauseAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([
|
||||
{
|
||||
customIdField: 'id',
|
||||
stringField: 'huh',
|
||||
intField: 4,
|
||||
testIndexedField: '4',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
]);
|
||||
const knexDataManager = instance(knexDataManagerMock);
|
||||
|
||||
const constructionUtils = new EntityConstructionUtils(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
privacyPolicyEvaluationContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
/* entitySelectedFields */ undefined,
|
||||
privacyPolicy,
|
||||
metricsAdapter,
|
||||
);
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
knexDataManager,
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
);
|
||||
|
||||
const result = await knexEntityLoader.loadManyByRawWhereClauseAsync('id = ?', [1], {
|
||||
orderBy: [{ fieldName: 'testIndexedField', order: OrderByOrdering.DESCENDING }],
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).not.toBeNull();
|
||||
expect(result[0]!.ok).toBe(true);
|
||||
expect(result[0]!.enforceValue().getField('testIndexedField')).toEqual('4');
|
||||
|
||||
verify(
|
||||
spiedPrivacyPolicy.authorizeReadAsync(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
privacyPolicyEvaluationContext,
|
||||
anyOfClass(TestEntity),
|
||||
anything(),
|
||||
),
|
||||
).once();
|
||||
});
|
||||
|
||||
describe('loads entities with loadManyBySQL', () => {
|
||||
it('returns entities with authorization results', async () => {
|
||||
const privacyPolicy = new TestEntityPrivacyPolicy();
|
||||
@@ -338,6 +272,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -419,6 +355,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -505,6 +443,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -620,6 +560,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testPaginationEntityConfiguration,
|
||||
TestPaginationEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -706,6 +648,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -806,6 +750,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testPaginationEntityConfiguration,
|
||||
TestPaginationEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -900,6 +846,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testPaginationEntityConfiguration,
|
||||
TestPaginationEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -991,6 +939,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testPaginationEntityConfiguration,
|
||||
TestPaginationEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -1055,6 +1005,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testPaginationEntityConfiguration,
|
||||
TestPaginationEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -1142,6 +1094,8 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testPaginationEntityConfiguration,
|
||||
TestPaginationEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
@@ -1162,4 +1116,326 @@ describe(AuthorizationResultBasedKnexEntityLoader, () => {
|
||||
expect(connection.pageInfo.endCursor).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('FromDatabase load methods', () => {
|
||||
const makeFieldObject = (id: string, testIndexedField: string): TestFields => ({
|
||||
customIdField: id,
|
||||
stringField: 'huh',
|
||||
intField: 4,
|
||||
testIndexedField,
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
});
|
||||
|
||||
const setup = (): {
|
||||
knexEntityLoader: AuthorizationResultBasedKnexEntityLoader<
|
||||
TestFields,
|
||||
'customIdField',
|
||||
ViewerContext,
|
||||
TestEntity,
|
||||
TestEntityPrivacyPolicy,
|
||||
keyof TestFields
|
||||
>;
|
||||
knexDataManagerMock: EntityKnexDataManager<TestFields, 'customIdField'>;
|
||||
queryContext: EntityQueryContext;
|
||||
} => {
|
||||
const privacyPolicy = new TestEntityPrivacyPolicy();
|
||||
const viewerContext = instance(mock(ViewerContext));
|
||||
const privacyPolicyEvaluationContext =
|
||||
instance(
|
||||
mock<
|
||||
EntityPrivacyPolicyEvaluationContext<
|
||||
TestFields,
|
||||
'customIdField',
|
||||
ViewerContext,
|
||||
TestEntity
|
||||
>
|
||||
>(),
|
||||
);
|
||||
const metricsAdapter = instance(mock<IEntityMetricsAdapter>());
|
||||
const queryContext = instance(mock<EntityQueryContext>());
|
||||
const knexDataManagerMock =
|
||||
mock<EntityKnexDataManager<TestFields, 'customIdField'>>(EntityKnexDataManager);
|
||||
const constructionUtils = new EntityConstructionUtils(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
privacyPolicyEvaluationContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
/* entitySelectedFields */ undefined,
|
||||
privacyPolicy,
|
||||
metricsAdapter,
|
||||
);
|
||||
const knexEntityLoader = new AuthorizationResultBasedKnexEntityLoader(
|
||||
queryContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
instance(knexDataManagerMock),
|
||||
metricsAdapter,
|
||||
constructionUtils,
|
||||
);
|
||||
return { knexEntityLoader, knexDataManagerMock, queryContext };
|
||||
};
|
||||
|
||||
it('loads entities with loadManyByIDsNullableFromDatabaseAsync', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock, queryContext } = setup();
|
||||
const id1 = uuidv4();
|
||||
const id2 = uuidv4();
|
||||
const missingId = uuidv4();
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([makeFieldObject(id1, '1'), makeFieldObject(id2, '2')]);
|
||||
|
||||
const results = await knexEntityLoader.loadManyByIDsNullableFromDatabaseAsync(
|
||||
[id1, id2, missingId],
|
||||
{ forUpdate: true },
|
||||
);
|
||||
expect(results.size).toBe(3);
|
||||
expect(results.get(id1)!.enforceValue().getID()).toBe(id1);
|
||||
expect(results.get(id2)!.enforceValue().getID()).toBe(id2);
|
||||
expect(results.get(missingId)).toBeNull();
|
||||
|
||||
verify(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'customIdField', fieldValues: [id1, id2, missingId] }]),
|
||||
deepEqual({ forUpdate: true }),
|
||||
),
|
||||
).once();
|
||||
});
|
||||
|
||||
it('returns an empty map and does not query for an empty list of IDs', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock } = setup();
|
||||
const results = await knexEntityLoader.loadManyByIDsNullableFromDatabaseAsync([], {
|
||||
forUpdate: true,
|
||||
});
|
||||
expect(results.size).toBe(0);
|
||||
verify(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).never();
|
||||
});
|
||||
|
||||
it('returns EntityNotFoundError results for missing IDs with loadManyByIDsFromDatabaseAsync', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock, queryContext } = setup();
|
||||
const id1 = uuidv4();
|
||||
const missingId = uuidv4();
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([makeFieldObject(id1, '1')]);
|
||||
|
||||
const results = await knexEntityLoader.loadManyByIDsFromDatabaseAsync([id1, missingId], {
|
||||
forShare: true,
|
||||
});
|
||||
expect(results.size).toBe(2);
|
||||
expect(results.get(id1)!.ok).toBe(true);
|
||||
const missingResult = results.get(missingId)!;
|
||||
expect(missingResult.ok).toBe(false);
|
||||
expect(missingResult.enforceError()).toBeInstanceOf(EntityNotFoundError);
|
||||
});
|
||||
|
||||
it('loads an entity with loadByIDFromDatabaseAsync', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock, queryContext } = setup();
|
||||
const id1 = uuidv4();
|
||||
const missingId = uuidv4();
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'customIdField', fieldValues: [id1] }]),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([makeFieldObject(id1, '1')]);
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'customIdField', fieldValues: [missingId] }]),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([]);
|
||||
|
||||
const found = await knexEntityLoader.loadByIDFromDatabaseAsync(id1, { forUpdate: true });
|
||||
expect(found.enforceValue().getID()).toBe(id1);
|
||||
|
||||
const missing = await knexEntityLoader.loadByIDFromDatabaseAsync(missingId, {
|
||||
forUpdate: true,
|
||||
});
|
||||
expect(missing.ok).toBe(false);
|
||||
expect(missing.enforceError()).toBeInstanceOf(EntityNotFoundError);
|
||||
});
|
||||
|
||||
it('loads an entity or null with loadByIDNullableFromDatabaseAsync', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock, queryContext } = setup();
|
||||
const id1 = uuidv4();
|
||||
const missingId = uuidv4();
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'customIdField', fieldValues: [id1] }]),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([makeFieldObject(id1, '1')]);
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'customIdField', fieldValues: [missingId] }]),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([]);
|
||||
|
||||
const found = await knexEntityLoader.loadByIDNullableFromDatabaseAsync(id1, {
|
||||
forUpdate: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
expect(found!.enforceValue().getID()).toBe(id1);
|
||||
|
||||
const missing = await knexEntityLoader.loadByIDNullableFromDatabaseAsync(missingId, {
|
||||
forUpdate: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
expect(missing).toBeNull();
|
||||
});
|
||||
|
||||
it('requires exactly one lock mode at the type level', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock, queryContext } = setup();
|
||||
const id1 = uuidv4();
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([makeFieldObject(id1, '1')]);
|
||||
|
||||
// valid: exactly one lock mode, optional skipLocked on nullable variants
|
||||
await knexEntityLoader.loadByIDNullableFromDatabaseAsync(id1, { forUpdate: true });
|
||||
await knexEntityLoader.loadByIDNullableFromDatabaseAsync(id1, { forShare: true });
|
||||
await knexEntityLoader.loadByIDNullableFromDatabaseAsync(id1, {
|
||||
forShare: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
await knexEntityLoader.loadByIDFromDatabaseAsync(id1, { forUpdate: true });
|
||||
|
||||
// @ts-expect-error a lock mode is required
|
||||
await knexEntityLoader.loadByIDNullableFromDatabaseAsync(id1, {});
|
||||
// @ts-expect-error skipLocked alone is not a lock mode
|
||||
await knexEntityLoader.loadByIDNullableFromDatabaseAsync(id1, { skipLocked: true });
|
||||
// @ts-expect-error forUpdate must be true
|
||||
await knexEntityLoader.loadByIDNullableFromDatabaseAsync(id1, { forUpdate: false });
|
||||
await knexEntityLoader.loadByIDNullableFromDatabaseAsync(id1, {
|
||||
forUpdate: true,
|
||||
// @ts-expect-error forUpdate and forShare are mutually exclusive
|
||||
forShare: true,
|
||||
});
|
||||
// @ts-expect-error skipLocked is not permitted on throwing variants
|
||||
await knexEntityLoader.loadByIDFromDatabaseAsync(id1, { forUpdate: true, skipLocked: true });
|
||||
await knexEntityLoader.loadManyByIDsFromDatabaseAsync([id1], {
|
||||
forShare: true,
|
||||
// @ts-expect-error skipLocked is not permitted on throwing variants
|
||||
skipLocked: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('validates ID values for FromDatabase ID loads', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock } = setup();
|
||||
await expect(
|
||||
knexEntityLoader.loadByIDFromDatabaseAsync('not-a-uuid', { forUpdate: true }),
|
||||
).rejects.toThrow('Entity field not valid: TestEntity (customIdField = not-a-uuid)');
|
||||
verify(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).never();
|
||||
});
|
||||
|
||||
it('loads entities with loadManyByFieldEqualingFromDatabaseAsync', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock, queryContext } = setup();
|
||||
const id1 = uuidv4();
|
||||
const id2 = uuidv4();
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([makeFieldObject(id1, '1'), makeFieldObject(id2, '2')]);
|
||||
|
||||
const results = await knexEntityLoader.loadManyByFieldEqualingFromDatabaseAsync(
|
||||
'stringField',
|
||||
'huh',
|
||||
{ forUpdate: true },
|
||||
);
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results.map((r) => r.enforceValue().getID())).toEqual([id1, id2]);
|
||||
|
||||
verify(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'stringField', fieldValue: 'huh' }]),
|
||||
deepEqual({ forUpdate: true }),
|
||||
),
|
||||
).once();
|
||||
});
|
||||
|
||||
it('loads an entity or null with loadByFieldEqualingFromDatabaseAsync and throws on multiple matches', async () => {
|
||||
const { knexEntityLoader, knexDataManagerMock, queryContext } = setup();
|
||||
const id1 = uuidv4();
|
||||
const id2 = uuidv4();
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'testIndexedField', fieldValue: 'one' }]),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([makeFieldObject(id1, 'one')]);
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'testIndexedField', fieldValue: 'none' }]),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([]);
|
||||
when(
|
||||
knexDataManagerMock.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
deepEqual([{ fieldName: 'testIndexedField', fieldValue: 'many' }]),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([makeFieldObject(id1, 'many'), makeFieldObject(id2, 'many')]);
|
||||
|
||||
const found = await knexEntityLoader.loadByFieldEqualingFromDatabaseAsync(
|
||||
'testIndexedField',
|
||||
'one',
|
||||
{ forShare: true },
|
||||
);
|
||||
expect(found!.enforceValue().getID()).toBe(id1);
|
||||
|
||||
const missing = await knexEntityLoader.loadByFieldEqualingFromDatabaseAsync(
|
||||
'testIndexedField',
|
||||
'none',
|
||||
{ forShare: true },
|
||||
);
|
||||
expect(missing).toBeNull();
|
||||
|
||||
await expect(
|
||||
knexEntityLoader.loadByFieldEqualingFromDatabaseAsync('testIndexedField', 'many', {
|
||||
forShare: true,
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
'loadByFieldEqualingFromDatabase: Multiple entities of type TestEntity found for testIndexedField=many',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
+86
-23
@@ -6,8 +6,10 @@ import { instance, mock } from 'ts-mockito';
|
||||
import type {
|
||||
TableFieldMultiValueEqualityCondition,
|
||||
TableFieldSingleValueEqualityCondition,
|
||||
TableQuerySelectionModifiers,
|
||||
} from '../BasePostgresEntityDatabaseAdapter.ts';
|
||||
import { BasePostgresEntityDatabaseAdapter } from '../BasePostgresEntityDatabaseAdapter.ts';
|
||||
import { sql } from '../SQLOperator.ts';
|
||||
import type { TestFields } from './fixtures/TestEntity.ts';
|
||||
import { testEntityConfiguration } from './fixtures/TestEntity.ts';
|
||||
|
||||
@@ -18,28 +20,31 @@ class TestEntityDatabaseAdapter extends BasePostgresEntityDatabaseAdapter<
|
||||
private readonly fetchResults: object[];
|
||||
private readonly fetchOneResult: object | null;
|
||||
private readonly insertResults: object[];
|
||||
private readonly updateResults: object[];
|
||||
private readonly updateResults: { updatedRowCount: number };
|
||||
private readonly fetchEqualityConditionResults: object[];
|
||||
private readonly fetchRawWhereResults: object[];
|
||||
private readonly fetchSQLFragmentResults: object[];
|
||||
private readonly deleteCount: number;
|
||||
public lastEqualityConditionQuerySelectionModifiers:
|
||||
| TableQuerySelectionModifiers<TestFields>
|
||||
| undefined;
|
||||
public lastSQLFragmentQuerySelectionModifiers:
|
||||
| TableQuerySelectionModifiers<TestFields>
|
||||
| undefined;
|
||||
|
||||
constructor({
|
||||
fetchResults = [],
|
||||
fetchOneResult = null,
|
||||
insertResults = [],
|
||||
updateResults = [],
|
||||
updateResults = { updatedRowCount: 0 },
|
||||
fetchEqualityConditionResults = [],
|
||||
fetchRawWhereResults = [],
|
||||
fetchSQLFragmentResults = [],
|
||||
deleteCount = 0,
|
||||
}: {
|
||||
fetchResults?: object[];
|
||||
fetchOneResult?: object | null;
|
||||
insertResults?: object[];
|
||||
updateResults?: object[];
|
||||
updateResults?: { updatedRowCount: number };
|
||||
fetchEqualityConditionResults?: object[];
|
||||
fetchRawWhereResults?: object[];
|
||||
fetchSQLFragmentResults?: object[];
|
||||
deleteCount?: number;
|
||||
}) {
|
||||
@@ -49,7 +54,6 @@ class TestEntityDatabaseAdapter extends BasePostgresEntityDatabaseAdapter<
|
||||
this.insertResults = insertResults;
|
||||
this.updateResults = updateResults;
|
||||
this.fetchEqualityConditionResults = fetchEqualityConditionResults;
|
||||
this.fetchRawWhereResults = fetchRawWhereResults;
|
||||
this.fetchSQLFragmentResults = fetchSQLFragmentResults;
|
||||
this.deleteCount = deleteCount;
|
||||
}
|
||||
@@ -76,20 +80,13 @@ class TestEntityDatabaseAdapter extends BasePostgresEntityDatabaseAdapter<
|
||||
return this.fetchOneResult;
|
||||
}
|
||||
|
||||
protected async fetchManyByRawWhereClauseInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
_rawWhereClause: string,
|
||||
_bindings: object | any[],
|
||||
): Promise<object[]> {
|
||||
return this.fetchRawWhereResults;
|
||||
}
|
||||
|
||||
protected async fetchManyBySQLFragmentInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
_sqlFragment: any,
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TestFields>,
|
||||
): Promise<object[]> {
|
||||
this.lastSQLFragmentQuerySelectionModifiers = querySelectionModifiers;
|
||||
return this.fetchSQLFragmentResults;
|
||||
}
|
||||
|
||||
@@ -98,10 +95,29 @@ class TestEntityDatabaseAdapter extends BasePostgresEntityDatabaseAdapter<
|
||||
_tableName: string,
|
||||
_tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[],
|
||||
_tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[],
|
||||
querySelectionModifiers: TableQuerySelectionModifiers<TestFields>,
|
||||
): Promise<object[]> {
|
||||
this.lastEqualityConditionQuerySelectionModifiers = querySelectionModifiers;
|
||||
return this.fetchEqualityConditionResults;
|
||||
}
|
||||
|
||||
protected async countByFieldEqualityConjunctionInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
_tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[],
|
||||
_tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[],
|
||||
): Promise<number> {
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected async countBySQLFragmentInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
_sqlFragment: any,
|
||||
): Promise<number> {
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected async insertInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
@@ -116,7 +132,7 @@ class TestEntityDatabaseAdapter extends BasePostgresEntityDatabaseAdapter<
|
||||
_tableIdField: string,
|
||||
_id: any,
|
||||
_object: object,
|
||||
): Promise<object[]> {
|
||||
): Promise<{ updatedRowCount: number }> {
|
||||
return this.updateResults;
|
||||
}
|
||||
|
||||
@@ -147,16 +163,63 @@ describe(BasePostgresEntityDatabaseAdapter, () => {
|
||||
const results = await adapter.fetchManyByFieldEqualityConjunctionAsync(queryContext, [], {});
|
||||
expect(results).toEqual([{ stringField: 'hello' }]);
|
||||
});
|
||||
|
||||
it('converts query selection modifiers including row locking modifiers', async () => {
|
||||
const queryContext = instance(mock(EntityQueryContext));
|
||||
const adapter = new TestEntityDatabaseAdapter({});
|
||||
await adapter.fetchManyByFieldEqualityConjunctionAsync(queryContext, [], {
|
||||
limit: 2,
|
||||
offset: 1,
|
||||
forUpdate: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
expect(adapter.lastEqualityConditionQuerySelectionModifiers).toEqual({
|
||||
orderBy: undefined,
|
||||
limit: 2,
|
||||
offset: 1,
|
||||
forUpdate: true,
|
||||
forShare: undefined,
|
||||
skipLocked: true,
|
||||
});
|
||||
|
||||
await adapter.fetchManyByFieldEqualityConjunctionAsync(queryContext, [], { forShare: true });
|
||||
expect(adapter.lastEqualityConditionQuerySelectionModifiers).toEqual({
|
||||
orderBy: undefined,
|
||||
limit: undefined,
|
||||
offset: undefined,
|
||||
forUpdate: undefined,
|
||||
forShare: true,
|
||||
skipLocked: undefined,
|
||||
});
|
||||
|
||||
await adapter.fetchManyByFieldEqualityConjunctionAsync(queryContext, [], {});
|
||||
expect(adapter.lastEqualityConditionQuerySelectionModifiers).toEqual({
|
||||
orderBy: undefined,
|
||||
limit: undefined,
|
||||
offset: undefined,
|
||||
forUpdate: undefined,
|
||||
forShare: undefined,
|
||||
skipLocked: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchManyWithRawWhereClause', () => {
|
||||
it('transforms object', async () => {
|
||||
describe('fetchManyBySQLFragmentAsync', () => {
|
||||
it('converts query selection modifiers including row locking modifiers', async () => {
|
||||
const queryContext = instance(mock(EntityQueryContext));
|
||||
const adapter = new TestEntityDatabaseAdapter({
|
||||
fetchRawWhereResults: [{ string_field: 'hello' }],
|
||||
const adapter = new TestEntityDatabaseAdapter({});
|
||||
await adapter.fetchManyBySQLFragmentAsync(queryContext, sql`TRUE`, {
|
||||
forShare: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
expect(adapter.lastSQLFragmentQuerySelectionModifiers).toEqual({
|
||||
orderBy: undefined,
|
||||
limit: undefined,
|
||||
offset: undefined,
|
||||
forUpdate: undefined,
|
||||
forShare: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
const results = await adapter.fetchManyByRawWhereClauseAsync(queryContext, 'hello', [], {});
|
||||
expect(results).toEqual([{ stringField: 'hello' }]);
|
||||
});
|
||||
});
|
||||
});
|
||||
+289
-53
@@ -2,7 +2,7 @@ import type { IEntityMetricsAdapter } from '@expo/entity';
|
||||
import { EntityConstructionUtils, EntityQueryContext } from '@expo/entity';
|
||||
import { result } from '@expo/results';
|
||||
import { describe, expect, it } from '@jest/globals';
|
||||
import { anything, instance, mock, when } from 'ts-mockito';
|
||||
import { anything, deepEqual, instance, mock, when } from 'ts-mockito';
|
||||
|
||||
import {
|
||||
AuthorizationResultBasedKnexEntityLoader,
|
||||
@@ -137,58 +137,6 @@ describe(EnforcingKnexEntityLoader, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadManyByRawWhereClause', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const rejection = new Error();
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadManyByRawWhereClauseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([result(rejection)]);
|
||||
const nonEnforcingKnexEntityLoader = instance(nonEnforcingKnexEntityLoaderMock);
|
||||
const enforcingKnexEntityLoader = new EnforcingKnexEntityLoader(
|
||||
nonEnforcingKnexEntityLoader,
|
||||
instance(mock(EntityQueryContext)),
|
||||
instance(mock(EntityKnexDataManager)),
|
||||
instance(mock<IEntityMetricsAdapter>()),
|
||||
instance(mock(EntityConstructionUtils)),
|
||||
);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadManyByRawWhereClauseAsync(anything(), anything(), anything()),
|
||||
).rejects.toThrow(rejection);
|
||||
});
|
||||
|
||||
it('returns value when result is successful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const resolved = {};
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadManyByRawWhereClauseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([result(resolved)]);
|
||||
const nonEnforcingKnexEntityLoader = instance(nonEnforcingKnexEntityLoaderMock);
|
||||
const enforcingKnexEntityLoader = new EnforcingKnexEntityLoader(
|
||||
nonEnforcingKnexEntityLoader,
|
||||
instance(mock(EntityQueryContext)),
|
||||
instance(mock(EntityKnexDataManager)),
|
||||
instance(mock<IEntityMetricsAdapter>()),
|
||||
instance(mock(EntityConstructionUtils)),
|
||||
);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadManyByRawWhereClauseAsync(anything(), anything(), anything()),
|
||||
).resolves.toEqual([resolved]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadManyBySQL', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
@@ -250,6 +198,294 @@ describe(EnforcingKnexEntityLoader, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('FromDatabase load methods', () => {
|
||||
const makeLoader = (
|
||||
nonEnforcingKnexEntityLoaderMock: AuthorizationResultBasedKnexEntityLoader<
|
||||
any,
|
||||
any,
|
||||
any,
|
||||
any,
|
||||
any,
|
||||
any
|
||||
>,
|
||||
): EnforcingKnexEntityLoader<any, any, any, any, any, any> =>
|
||||
new EnforcingKnexEntityLoader(
|
||||
instance(nonEnforcingKnexEntityLoaderMock),
|
||||
instance(mock(EntityQueryContext)),
|
||||
instance(mock(EntityKnexDataManager)),
|
||||
instance(mock<IEntityMetricsAdapter>()),
|
||||
instance(mock(EntityConstructionUtils)),
|
||||
);
|
||||
|
||||
describe('loadByIDFromDatabaseAsync', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const rejection = new Error();
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadByIDFromDatabaseAsync(anything(), anything()),
|
||||
).thenResolve(result(rejection));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadByIDFromDatabaseAsync('id', { forUpdate: true }),
|
||||
).rejects.toThrow(rejection);
|
||||
});
|
||||
|
||||
it('returns value when result is successful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const resolved = {};
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadByIDFromDatabaseAsync(
|
||||
'id',
|
||||
deepEqual({ forUpdate: true }),
|
||||
),
|
||||
).thenResolve(result(resolved));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadByIDFromDatabaseAsync('id', { forUpdate: true }),
|
||||
).resolves.toEqual(resolved);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadByIDNullableFromDatabaseAsync', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const rejection = new Error();
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadByIDNullableFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve(result(rejection));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadByIDNullableFromDatabaseAsync('id', { forUpdate: true }),
|
||||
).rejects.toThrow(rejection);
|
||||
});
|
||||
|
||||
it('returns value when result is successful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const resolved = {};
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadByIDNullableFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve(result(resolved));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadByIDNullableFromDatabaseAsync('id', { forUpdate: true }),
|
||||
).resolves.toEqual(resolved);
|
||||
});
|
||||
|
||||
it('returns null when result is null', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadByIDNullableFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve(null);
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadByIDNullableFromDatabaseAsync('id', { forUpdate: true }),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadManyByIDsFromDatabaseAsync', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const rejection = new Error();
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadManyByIDsFromDatabaseAsync(anything(), anything()),
|
||||
).thenResolve(new Map([['id', result(rejection)]]));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadManyByIDsFromDatabaseAsync(['id'], { forUpdate: true }),
|
||||
).rejects.toThrow(rejection);
|
||||
});
|
||||
|
||||
it('returns value when result is successful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const resolved = {};
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadManyByIDsFromDatabaseAsync(anything(), anything()),
|
||||
).thenResolve(new Map([['id', result(resolved)]]));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadManyByIDsFromDatabaseAsync(['id'], { forUpdate: true }),
|
||||
).resolves.toEqual(new Map([['id', resolved]]));
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadManyByIDsNullableFromDatabaseAsync', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const rejection = new Error();
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadManyByIDsNullableFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve(new Map([['id', result(rejection)]]));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadManyByIDsNullableFromDatabaseAsync(['id'], {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).rejects.toThrow(rejection);
|
||||
});
|
||||
|
||||
it('returns values and nulls when results are successful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const resolved = {};
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadManyByIDsNullableFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve(
|
||||
new Map([
|
||||
['id', result(resolved)],
|
||||
['missing', null],
|
||||
]),
|
||||
);
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadManyByIDsNullableFromDatabaseAsync(['id', 'missing'], {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).resolves.toEqual(
|
||||
new Map([
|
||||
['id', resolved],
|
||||
['missing', null],
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadByFieldEqualingFromDatabaseAsync', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const rejection = new Error();
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadByFieldEqualingFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve(result(rejection));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadByFieldEqualingFromDatabaseAsync('field', 'value', {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).rejects.toThrow(rejection);
|
||||
});
|
||||
|
||||
it('returns value when result is successful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const resolved = {};
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadByFieldEqualingFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve(result(resolved));
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadByFieldEqualingFromDatabaseAsync('field', 'value', {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).resolves.toEqual(resolved);
|
||||
});
|
||||
|
||||
it('returns null when result is null', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadByFieldEqualingFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve(null);
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadByFieldEqualingFromDatabaseAsync('field', 'value', {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadManyByFieldEqualingFromDatabaseAsync', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const rejection = new Error();
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadManyByFieldEqualingFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([result(rejection)]);
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadManyByFieldEqualingFromDatabaseAsync('field', 'value', {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).rejects.toThrow(rejection);
|
||||
});
|
||||
|
||||
it('returns values when results are successful', async () => {
|
||||
const nonEnforcingKnexEntityLoaderMock = mock(
|
||||
AuthorizationResultBasedKnexEntityLoader<any, any, any, any, any, any>,
|
||||
);
|
||||
const resolved = {};
|
||||
when(
|
||||
nonEnforcingKnexEntityLoaderMock.loadManyByFieldEqualingFromDatabaseAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([result(resolved)]);
|
||||
const enforcingKnexEntityLoader = makeLoader(nonEnforcingKnexEntityLoaderMock);
|
||||
await expect(
|
||||
enforcingKnexEntityLoader.loadManyByFieldEqualingFromDatabaseAsync('field', 'value', {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).resolves.toEqual([resolved]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadPageAsync', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const queryContext = instance(mock(EntityQueryContext));
|
||||
|
||||
@@ -258,12 +258,11 @@ describe('SQLOperator', () => {
|
||||
});
|
||||
|
||||
it('handles all SupportedSQLValue types in getDebugString', () => {
|
||||
const fragment = new SQLFragment('INSERT INTO test VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [
|
||||
const fragment = new SQLFragment('INSERT INTO test VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [
|
||||
{ type: 'value', value: 'string' },
|
||||
{ type: 'value', value: 123 },
|
||||
{ type: 'value', value: true },
|
||||
{ type: 'value', value: null },
|
||||
{ type: 'value', value: undefined },
|
||||
{ type: 'value', value: new Date('2024-01-01T00:00:00.000Z') },
|
||||
{ type: 'value', value: Buffer.from('hello') },
|
||||
{ type: 'value', value: BigInt(999) },
|
||||
@@ -272,7 +271,7 @@ describe('SQLOperator', () => {
|
||||
|
||||
const text = fragment.getDebugString();
|
||||
expect(text).toBe(
|
||||
"INSERT INTO test VALUES ('string', 123, TRUE, NULL, NULL, '2024-01-01T00:00:00.000Z', '\\x68656c6c6f', 999, ARRAY[1, 2, 3])",
|
||||
"INSERT INTO test VALUES ('string', 123, TRUE, NULL, '2024-01-01T00:00:00.000Z', '\\x68656c6c6f', 999, ARRAY[1, 2, 3])",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -763,13 +762,6 @@ describe('SQLOperator', () => {
|
||||
expect(fragment.getKnexBindings(getColumnForField)).toEqual(['nullable_field']);
|
||||
});
|
||||
|
||||
it('handles undefined in equality check', () => {
|
||||
const fragment = SQLExpression.eq('nullableField', undefined);
|
||||
|
||||
expect(fragment.sql).toBe('?? IS NULL');
|
||||
expect(fragment.getKnexBindings(getColumnForField)).toEqual(['nullable_field']);
|
||||
});
|
||||
|
||||
it('accepts a SQLFragment expression', () => {
|
||||
const fragment = SQLExpression.eq(sql<TestFields>`${entityField('stringField')}`, 'active');
|
||||
expect(fragment.sql).toBe('?? = ?');
|
||||
@@ -801,13 +793,6 @@ describe('SQLOperator', () => {
|
||||
expect(fragment.getKnexBindings(getColumnForField)).toEqual(['nullable_field']);
|
||||
});
|
||||
|
||||
it('handles undefined in inequality check', () => {
|
||||
const fragment = SQLExpression.neq('nullableField', undefined);
|
||||
|
||||
expect(fragment.sql).toBe('?? IS NOT NULL');
|
||||
expect(fragment.getKnexBindings(getColumnForField)).toEqual(['nullable_field']);
|
||||
});
|
||||
|
||||
it('accepts a SQLFragment expression', () => {
|
||||
const fragment = SQLExpression.neq(
|
||||
sql<TestFields>`${entityField('stringField')}`,
|
||||
@@ -1131,12 +1116,6 @@ describe('SQLOperator', () => {
|
||||
expect(fragment.getKnexBindings(getColumnForField)).toEqual(['string_field']);
|
||||
});
|
||||
|
||||
it('eq(undefined) uses IS NULL', () => {
|
||||
const fragment = makeExpr<string>(stringFieldFragment()).eq(undefined);
|
||||
expect(fragment.sql).toBe('?? IS NULL');
|
||||
expect(fragment.getKnexBindings(getColumnForField)).toEqual(['string_field']);
|
||||
});
|
||||
|
||||
it('neq(value)', () => {
|
||||
const fragment = makeExpr<string>(stringFieldFragment()).neq('deleted');
|
||||
expect(fragment.sql).toBe('?? != ?');
|
||||
@@ -1149,12 +1128,6 @@ describe('SQLOperator', () => {
|
||||
expect(fragment.getKnexBindings(getColumnForField)).toEqual(['string_field']);
|
||||
});
|
||||
|
||||
it('neq(undefined) uses IS NOT NULL', () => {
|
||||
const fragment = makeExpr<string>(stringFieldFragment()).neq(undefined);
|
||||
expect(fragment.sql).toBe('?? IS NOT NULL');
|
||||
expect(fragment.getKnexBindings(getColumnForField)).toEqual(['string_field']);
|
||||
});
|
||||
|
||||
it('gt(value)', () => {
|
||||
const fragment = makeExpr<number>(intFieldFragment()).gt(10);
|
||||
expect(fragment.sql).toBe('?? > ?');
|
||||
|
||||
+35
-14
@@ -76,7 +76,7 @@ export class StubPostgresDatabaseAdapter<
|
||||
): Promise<object[]> {
|
||||
const objectCollection = this.getObjectCollectionForTable(tableName);
|
||||
const results = StubPostgresDatabaseAdapter.uniqBy(tableTuples, (tuple) =>
|
||||
tuple.join(':'),
|
||||
JSON.stringify(tuple),
|
||||
).reduce(
|
||||
(acc, tableTuple) => {
|
||||
return acc.concat(
|
||||
@@ -193,16 +193,6 @@ export class StubPostgresDatabaseAdapter<
|
||||
return filteredObjects;
|
||||
}
|
||||
|
||||
protected fetchManyByRawWhereClauseInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
_rawWhereClause: string,
|
||||
_bindings: object | any[],
|
||||
_querySelectionModifiers: TableQuerySelectionModifiers<TFields>,
|
||||
): Promise<object[]> {
|
||||
throw new Error('Raw WHERE clauses not supported for StubDatabaseAdapter');
|
||||
}
|
||||
|
||||
protected fetchManyBySQLFragmentInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
@@ -212,6 +202,37 @@ export class StubPostgresDatabaseAdapter<
|
||||
throw new Error('SQL fragments not supported for StubDatabaseAdapter');
|
||||
}
|
||||
|
||||
protected async countByFieldEqualityConjunctionInternalAsync(
|
||||
queryInterface: any,
|
||||
tableName: string,
|
||||
tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[],
|
||||
tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[],
|
||||
): Promise<number> {
|
||||
const results = await this.fetchManyByFieldEqualityConjunctionInternalAsync(
|
||||
queryInterface,
|
||||
tableName,
|
||||
tableFieldSingleValueEqualityOperands,
|
||||
tableFieldMultiValueEqualityOperands,
|
||||
{
|
||||
orderBy: undefined,
|
||||
offset: undefined,
|
||||
limit: undefined,
|
||||
forUpdate: undefined,
|
||||
forShare: undefined,
|
||||
skipLocked: undefined,
|
||||
},
|
||||
);
|
||||
return results.length;
|
||||
}
|
||||
|
||||
protected countBySQLFragmentInternalAsync(
|
||||
_queryInterface: any,
|
||||
_tableName: string,
|
||||
_sqlFragment: SQLFragment<TFields>,
|
||||
): Promise<number> {
|
||||
throw new Error('SQL fragment count not supported for StubDatabaseAdapter');
|
||||
}
|
||||
|
||||
private generateRandomID(): any {
|
||||
const idSchemaField = this.entityConfiguration2.schema.get(this.entityConfiguration2.idField);
|
||||
invariant(
|
||||
@@ -254,7 +275,7 @@ export class StubPostgresDatabaseAdapter<
|
||||
tableIdField: string,
|
||||
id: any,
|
||||
object: object,
|
||||
): Promise<object[]> {
|
||||
): Promise<{ updatedRowCount: number }> {
|
||||
// SQL does not support empty updates, mirror behavior here for better test simulation
|
||||
if (Object.keys(object).length === 0) {
|
||||
throw new Error(`Empty update (${tableIdField} = ${id})`);
|
||||
@@ -269,14 +290,14 @@ export class StubPostgresDatabaseAdapter<
|
||||
// SQL updates to a nonexistent row succeed but affect 0 rows,
|
||||
// mirror that behavior here for better test simulation
|
||||
if (objectIndex < 0) {
|
||||
return [];
|
||||
return { updatedRowCount: 0 };
|
||||
}
|
||||
|
||||
objectCollection[objectIndex] = {
|
||||
...objectCollection[objectIndex],
|
||||
...object,
|
||||
};
|
||||
return [objectCollection[objectIndex]];
|
||||
return { updatedRowCount: 1 };
|
||||
}
|
||||
|
||||
protected async deleteInternalAsync(
|
||||
|
||||
+18
@@ -1,8 +1,26 @@
|
||||
import { EntityDatabaseAdapterTransientError, EntityErrorState } from '@expo/entity';
|
||||
import { describe, expect, it } from '@jest/globals';
|
||||
|
||||
import { wrapNativePostgresCallAsync } from '../wrapNativePostgresCallAsync.ts';
|
||||
|
||||
describe(wrapNativePostgresCallAsync, () => {
|
||||
it('classifies a PostgreSQL lock timeout as transient and preserves the cause', async () => {
|
||||
const error = Object.assign(new Error('canceling statement due to lock timeout'), {
|
||||
code: '55P03',
|
||||
});
|
||||
const result = wrapNativePostgresCallAsync(async () => {
|
||||
throw error;
|
||||
});
|
||||
|
||||
await expect(result).rejects.toBeInstanceOf(EntityDatabaseAdapterTransientError);
|
||||
await expect(result).rejects.toMatchObject({
|
||||
state: EntityErrorState.TRANSIENT,
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
cause: error,
|
||||
});
|
||||
});
|
||||
|
||||
it('rethrows literals', async () => {
|
||||
const throwingFn = async (): Promise<void> => {
|
||||
// eslint-disable-next-line no-throw-literal,@typescript-eslint/only-throw-error
|
||||
|
||||
@@ -38,6 +38,8 @@ function translatePostgresError(
|
||||
return new EntityDatabaseAdapterCheckConstraintError(error.message, error);
|
||||
case '23P01':
|
||||
return new EntityDatabaseAdapterExclusionConstraintError(error.message, error);
|
||||
case '55P03':
|
||||
return new EntityDatabaseAdapterTransientError(error.message, error);
|
||||
default:
|
||||
return new EntityDatabaseAdapterUnknownError(error.message, error);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { EntityConfiguration, EntityQueryContext, IEntityMetricsAdapter } from '@expo/entity';
|
||||
import {
|
||||
EntityDatabaseAdapterPaginationCursorInvalidError,
|
||||
EntityMetricsCountType,
|
||||
EntityMetricsLoadType,
|
||||
getDatabaseFieldForEntityField,
|
||||
timeAndLogCountEventAsync,
|
||||
timeAndLogLoadEventAsync,
|
||||
} from '@expo/entity';
|
||||
import assert from 'assert';
|
||||
@@ -175,6 +177,7 @@ export class EntityKnexDataManager<
|
||||
querySelectionModifiers: PostgresQuerySelectionModifiers<TFields>,
|
||||
): Promise<readonly Readonly<TFields>[]> {
|
||||
EntityKnexDataManager.validateOrderByClauses(querySelectionModifiers.orderBy);
|
||||
EntityKnexDataManager.validateRowLockingModifiers(queryContext, querySelectionModifiers);
|
||||
|
||||
return await timeAndLogLoadEventAsync(
|
||||
this.metricsAdapter,
|
||||
@@ -190,34 +193,19 @@ export class EntityKnexDataManager<
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads many objects matching the raw WHERE clause.
|
||||
*
|
||||
* @param queryContext - query context in which to perform the load
|
||||
* @param rawWhereClause - parameterized SQL WHERE clause with positional binding placeholders or named binding placeholders
|
||||
* @param bindings - array of positional bindings or object of named bindings
|
||||
* @param querySelectionModifiers - limit, offset, orderBy, and orderByRaw for the query
|
||||
* @returns array of objects matching the query
|
||||
*/
|
||||
async loadManyByRawWhereClauseAsync(
|
||||
async countByFieldEqualityConjunctionAsync<N extends keyof TFields>(
|
||||
queryContext: EntityQueryContext,
|
||||
rawWhereClause: string,
|
||||
bindings: readonly any[] | object,
|
||||
querySelectionModifiers: PostgresQuerySelectionModifiers<TFields>,
|
||||
): Promise<readonly Readonly<TFields>[]> {
|
||||
EntityKnexDataManager.validateOrderByClauses(querySelectionModifiers.orderBy);
|
||||
|
||||
return await timeAndLogLoadEventAsync(
|
||||
fieldEqualityOperands: readonly FieldEqualityCondition<TFields, N>[],
|
||||
): Promise<number> {
|
||||
return await timeAndLogCountEventAsync(
|
||||
this.metricsAdapter,
|
||||
EntityMetricsLoadType.LOAD_MANY_RAW,
|
||||
EntityMetricsCountType.COUNT_EQUALITY_CONJUNCTION,
|
||||
this.entityClassName,
|
||||
queryContext,
|
||||
)(
|
||||
this.databaseAdapter.fetchManyByRawWhereClauseAsync(
|
||||
this.databaseAdapter.countByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
rawWhereClause,
|
||||
bindings,
|
||||
querySelectionModifiers,
|
||||
fieldEqualityOperands,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -228,6 +216,7 @@ export class EntityKnexDataManager<
|
||||
querySelectionModifiers: PostgresQuerySelectionModifiers<TFields>,
|
||||
): Promise<readonly Readonly<TFields>[]> {
|
||||
EntityKnexDataManager.validateOrderByClauses(querySelectionModifiers.orderBy);
|
||||
EntityKnexDataManager.validateRowLockingModifiers(queryContext, querySelectionModifiers);
|
||||
|
||||
return await timeAndLogLoadEventAsync(
|
||||
this.metricsAdapter,
|
||||
@@ -243,6 +232,18 @@ export class EntityKnexDataManager<
|
||||
);
|
||||
}
|
||||
|
||||
async countBySQLFragmentAsync(
|
||||
queryContext: EntityQueryContext,
|
||||
sqlFragment: SQLFragment<TFields>,
|
||||
): Promise<number> {
|
||||
return await timeAndLogCountEventAsync(
|
||||
this.metricsAdapter,
|
||||
EntityMetricsCountType.COUNT_SQL,
|
||||
this.entityClassName,
|
||||
queryContext,
|
||||
)(this.databaseAdapter.countBySQLFragmentAsync(queryContext, sqlFragment));
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a page of objects using cursor-based pagination with unified pagination specification.
|
||||
*
|
||||
@@ -292,18 +293,16 @@ export class EntityKnexDataManager<
|
||||
// 3. Reverse the final array to present items in name ASC order
|
||||
return direction === PaginationDirection.FORWARD
|
||||
? augmentedOrderByClauses
|
||||
: augmentedOrderByClauses.map(
|
||||
(clause): PostgresOrderByClause<TFields> => ({
|
||||
...clause,
|
||||
order:
|
||||
clause.order === OrderByOrdering.ASCENDING
|
||||
? OrderByOrdering.DESCENDING
|
||||
: OrderByOrdering.ASCENDING,
|
||||
nulls: clause.nulls
|
||||
? EntityKnexDataManager.flipNullsOrderingSpread(clause.nulls)
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
: augmentedOrderByClauses.map((clause): PostgresOrderByClause<TFields> => ({
|
||||
...clause,
|
||||
order:
|
||||
clause.order === OrderByOrdering.ASCENDING
|
||||
? OrderByOrdering.DESCENDING
|
||||
: OrderByOrdering.ASCENDING,
|
||||
nulls: clause.nulls
|
||||
? EntityKnexDataManager.flipNullsOrderingSpread(clause.nulls)
|
||||
: undefined,
|
||||
}));
|
||||
},
|
||||
buildCursorCondition: (decodedCursorId, _direction, orderByClauses) => {
|
||||
// all clauses are guaranteed to have the same order due to validation, so we can just look at the first one for effective ordering
|
||||
@@ -482,17 +481,16 @@ export class EntityKnexDataManager<
|
||||
baseWhere: SQLFragment<TFields> | undefined,
|
||||
cursorCondition: SQLFragment<TFields> | null,
|
||||
): SQLFragment<TFields> {
|
||||
const conditions = [baseWhere, cursorCondition].filter((it) => !!it);
|
||||
if (conditions.length === 0) {
|
||||
return sql`TRUE`;
|
||||
if (!baseWhere) {
|
||||
return cursorCondition ?? sql`TRUE`;
|
||||
}
|
||||
if (conditions.length === 1) {
|
||||
return conditions[0]!;
|
||||
|
||||
if (!cursorCondition) {
|
||||
return baseWhere;
|
||||
}
|
||||
// Wrap baseWhere in parens if combining with cursor condition
|
||||
// We know we have exactly 2 conditions at this point
|
||||
const [first, second] = conditions;
|
||||
return sql`(${first}) AND ${second}`;
|
||||
|
||||
// Wrap baseWhere in parens when combining with cursor condition
|
||||
return sql`(${baseWhere}) AND ${cursorCondition}`;
|
||||
}
|
||||
|
||||
private augmentOrderByIfNecessary(
|
||||
@@ -535,6 +533,30 @@ export class EntityKnexDataManager<
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates row locking modifiers (forUpdate, forShare, skipLocked).
|
||||
*
|
||||
* `SELECT ... FOR UPDATE` and `SELECT ... FOR SHARE` row locks are released at the end of the
|
||||
* transaction. Outside of a transaction the lock is released as soon as the statement completes,
|
||||
* which makes it useless, so require a transactional query context. FOR UPDATE and FOR SHARE
|
||||
* cannot be combined in a single statement, and SKIP LOCKED is only valid with a row lock.
|
||||
*/
|
||||
private static validateRowLockingModifiers<TFields extends Record<string, any>>(
|
||||
queryContext: EntityQueryContext,
|
||||
querySelectionModifiers: PostgresQuerySelectionModifiers<TFields>,
|
||||
): void {
|
||||
const { forUpdate, forShare, skipLocked } = querySelectionModifiers;
|
||||
if (!forUpdate && !forShare) {
|
||||
assert(!skipLocked, 'skipLocked requires forUpdate or forShare.');
|
||||
return;
|
||||
}
|
||||
assert(!(forUpdate && forShare), 'forUpdate and forShare are mutually exclusive.');
|
||||
assert(
|
||||
queryContext.isInTransaction(),
|
||||
'forUpdate and forShare require a transactional query context since row locks are released at the end of the transaction.',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cursor-based pagination uses Postgres tuple comparison (e.g., (a, b) \> (x, y)) which
|
||||
* applies a single comparison direction to all columns. Mixed ordering directions would
|
||||
@@ -559,6 +581,7 @@ export class EntityKnexDataManager<
|
||||
|
||||
private decodeOpaqueCursor(cursor: string): TFields[TIDField] {
|
||||
let parsedCursor: any;
|
||||
|
||||
try {
|
||||
const decoded = Buffer.from(cursor, 'base64url').toString();
|
||||
parsedCursor = JSON.parse(decoded);
|
||||
@@ -569,13 +592,13 @@ export class EntityKnexDataManager<
|
||||
);
|
||||
}
|
||||
|
||||
if (!('id' in parsedCursor)) {
|
||||
throw new EntityDatabaseAdapterPaginationCursorInvalidError(
|
||||
`Cursor is missing required 'id' field. Parsed cursor: ${JSON.stringify(parsedCursor)}`,
|
||||
);
|
||||
if (typeof parsedCursor === 'object' && 'id' in parsedCursor) {
|
||||
return parsedCursor.id;
|
||||
}
|
||||
|
||||
return parsedCursor.id;
|
||||
throw new EntityDatabaseAdapterPaginationCursorInvalidError(
|
||||
`Cursor is missing required 'id' field. Parsed cursor: ${JSON.stringify(parsedCursor)}`,
|
||||
);
|
||||
}
|
||||
|
||||
private resolveSearchFieldToSQLFragment(
|
||||
@@ -759,12 +782,10 @@ export class EntityKnexDataManager<
|
||||
|
||||
// Order by search fields + ID to match cursor fields
|
||||
const searchOrderByClauses: PostgresOrderByClause<TFields>[] = [
|
||||
...search.fields.map(
|
||||
(field): PostgresOrderByClause<TFields> => ({
|
||||
fieldFragment: this.resolveSearchFieldToSQLFragment(field),
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
}),
|
||||
),
|
||||
...search.fields.map((field): PostgresOrderByClause<TFields> => ({
|
||||
fieldFragment: this.resolveSearchFieldToSQLFragment(field),
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
})),
|
||||
{
|
||||
fieldName: this.entityConfiguration.idField,
|
||||
order: OrderByOrdering.ASCENDING,
|
||||
|
||||
+275
-57
@@ -2,21 +2,12 @@ import type { EntityQueryContext, IEntityMetricsAdapter } from '@expo/entity';
|
||||
import { EntityMetricsLoadType, NoOpEntityMetricsAdapter } from '@expo/entity';
|
||||
import { StubQueryContextProvider } from '@expo/entity-testing-utils';
|
||||
import { describe, expect, it } from '@jest/globals';
|
||||
import {
|
||||
anyNumber,
|
||||
anyString,
|
||||
anything,
|
||||
deepEqual,
|
||||
instance,
|
||||
mock,
|
||||
resetCalls,
|
||||
verify,
|
||||
when,
|
||||
} from 'ts-mockito';
|
||||
import { anyNumber, anything, deepEqual, instance, mock, verify, when } from 'ts-mockito';
|
||||
|
||||
import { OrderByOrdering } from '../../BasePostgresEntityDatabaseAdapter.ts';
|
||||
import { PaginationStrategy } from '../../PaginationStrategy.ts';
|
||||
import { PostgresEntityDatabaseAdapter } from '../../PostgresEntityDatabaseAdapter.ts';
|
||||
import { sql } from '../../SQLOperator.ts';
|
||||
import type { TestFields } from '../../__tests__/fixtures/TestEntity.ts';
|
||||
import { TestEntity, testEntityConfiguration } from '../../__tests__/fixtures/TestEntity.ts';
|
||||
import { EntityKnexDataManager } from '../EntityKnexDataManager.ts';
|
||||
@@ -110,14 +101,6 @@ describe(EntityKnexDataManager, () => {
|
||||
nullableField: null,
|
||||
},
|
||||
]);
|
||||
when(
|
||||
databaseAdapterMock.fetchManyByRawWhereClauseAsync(
|
||||
anything(),
|
||||
anyString(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([]);
|
||||
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
@@ -148,21 +131,6 @@ describe(EntityKnexDataManager, () => {
|
||||
),
|
||||
).once();
|
||||
|
||||
resetCalls(metricsAdapterMock);
|
||||
|
||||
await entityDataManager.loadManyByRawWhereClauseAsync(queryContext, '', [], {});
|
||||
verify(
|
||||
metricsAdapterMock.logDataManagerLoadEvent(
|
||||
deepEqual({
|
||||
type: EntityMetricsLoadType.LOAD_MANY_RAW,
|
||||
isInTransaction: false,
|
||||
entityClassName: TestEntity.name,
|
||||
duration: anyNumber(),
|
||||
count: 0,
|
||||
}),
|
||||
),
|
||||
).once();
|
||||
|
||||
verify(metricsAdapterMock.incrementDataManagerLoadCount(anything())).never();
|
||||
});
|
||||
|
||||
@@ -190,14 +158,6 @@ describe(EntityKnexDataManager, () => {
|
||||
nullableField: null,
|
||||
},
|
||||
]);
|
||||
when(
|
||||
databaseAdapterMock.fetchManyByRawWhereClauseAsync(
|
||||
anything(),
|
||||
anyString(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([]);
|
||||
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
@@ -229,26 +189,284 @@ describe(EntityKnexDataManager, () => {
|
||||
),
|
||||
).once();
|
||||
|
||||
resetCalls(metricsAdapterMock);
|
||||
|
||||
await entityDataManager.loadManyByRawWhereClauseAsync(queryContext, '', [], {});
|
||||
verify(
|
||||
metricsAdapterMock.logDataManagerLoadEvent(
|
||||
deepEqual({
|
||||
type: EntityMetricsLoadType.LOAD_MANY_RAW,
|
||||
isInTransaction: true,
|
||||
entityClassName: TestEntity.name,
|
||||
duration: anyNumber(),
|
||||
count: 0,
|
||||
}),
|
||||
),
|
||||
).once();
|
||||
|
||||
verify(metricsAdapterMock.incrementDataManagerLoadCount(anything())).never();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('row locking modifiers', () => {
|
||||
const fieldObject = {
|
||||
customIdField: '1',
|
||||
testIndexedField: 'unique1',
|
||||
stringField: 'hello',
|
||||
intField: 1,
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
};
|
||||
|
||||
it('throws when loading by field equality conjunction outside of a transaction', async () => {
|
||||
const queryContext = new StubQueryContextProvider().getQueryContext();
|
||||
const databaseAdapterMock = mock<PostgresEntityDatabaseAdapter<TestFields, 'customIdField'>>(
|
||||
PostgresEntityDatabaseAdapter,
|
||||
);
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
instance(databaseAdapterMock),
|
||||
new NoOpEntityMetricsAdapter(),
|
||||
TestEntity.name,
|
||||
);
|
||||
|
||||
await expect(
|
||||
entityDataManager.loadManyByFieldEqualityConjunctionAsync(queryContext, [], {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).rejects.toThrow('require a transactional query context');
|
||||
verify(
|
||||
databaseAdapterMock.fetchManyByFieldEqualityConjunctionAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).never();
|
||||
});
|
||||
|
||||
it('throws when loading by SQL fragment outside of a transaction', async () => {
|
||||
const queryContext = new StubQueryContextProvider().getQueryContext();
|
||||
const databaseAdapterMock = mock<PostgresEntityDatabaseAdapter<TestFields, 'customIdField'>>(
|
||||
PostgresEntityDatabaseAdapter,
|
||||
);
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
instance(databaseAdapterMock),
|
||||
new NoOpEntityMetricsAdapter(),
|
||||
TestEntity.name,
|
||||
);
|
||||
|
||||
await expect(
|
||||
entityDataManager.loadManyBySQLFragmentAsync(queryContext, sql`TRUE`, {
|
||||
forUpdate: true,
|
||||
}),
|
||||
).rejects.toThrow('require a transactional query context');
|
||||
verify(
|
||||
databaseAdapterMock.fetchManyBySQLFragmentAsync(anything(), anything(), anything()),
|
||||
).never();
|
||||
});
|
||||
|
||||
it('passes forUpdate through to the database adapter inside of a transaction', async () => {
|
||||
const databaseAdapterMock = mock<PostgresEntityDatabaseAdapter<TestFields, 'customIdField'>>(
|
||||
PostgresEntityDatabaseAdapter,
|
||||
);
|
||||
when(
|
||||
databaseAdapterMock.fetchManyByFieldEqualityConjunctionAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([fieldObject]);
|
||||
when(
|
||||
databaseAdapterMock.fetchManyBySQLFragmentAsync(anything(), anything(), anything()),
|
||||
).thenResolve([fieldObject]);
|
||||
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
instance(databaseAdapterMock),
|
||||
new NoOpEntityMetricsAdapter(),
|
||||
TestEntity.name,
|
||||
);
|
||||
|
||||
await new StubQueryContextProvider().runInTransactionAsync(async (queryContext) => {
|
||||
const equalityResults = await entityDataManager.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
[{ fieldName: 'stringField', fieldValue: 'hello' }],
|
||||
{ forUpdate: true, limit: 1 },
|
||||
);
|
||||
expect(equalityResults).toHaveLength(1);
|
||||
|
||||
const sqlResults = await entityDataManager.loadManyBySQLFragmentAsync(
|
||||
queryContext,
|
||||
sql`TRUE`,
|
||||
{ forUpdate: true },
|
||||
);
|
||||
expect(sqlResults).toHaveLength(1);
|
||||
|
||||
verify(
|
||||
databaseAdapterMock.fetchManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
deepEqual({ forUpdate: true, limit: 1 }),
|
||||
),
|
||||
).once();
|
||||
verify(
|
||||
databaseAdapterMock.fetchManyBySQLFragmentAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
deepEqual({ forUpdate: true }),
|
||||
),
|
||||
).once();
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when forShare is used outside of a transaction', async () => {
|
||||
const queryContext = new StubQueryContextProvider().getQueryContext();
|
||||
const databaseAdapterMock = mock<PostgresEntityDatabaseAdapter<TestFields, 'customIdField'>>(
|
||||
PostgresEntityDatabaseAdapter,
|
||||
);
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
instance(databaseAdapterMock),
|
||||
new NoOpEntityMetricsAdapter(),
|
||||
TestEntity.name,
|
||||
);
|
||||
|
||||
await expect(
|
||||
entityDataManager.loadManyByFieldEqualityConjunctionAsync(queryContext, [], {
|
||||
forShare: true,
|
||||
}),
|
||||
).rejects.toThrow('require a transactional query context');
|
||||
await expect(
|
||||
entityDataManager.loadManyBySQLFragmentAsync(queryContext, sql`TRUE`, { forShare: true }),
|
||||
).rejects.toThrow('require a transactional query context');
|
||||
});
|
||||
|
||||
it('throws when forUpdate and forShare are both set', async () => {
|
||||
const databaseAdapterMock = mock<PostgresEntityDatabaseAdapter<TestFields, 'customIdField'>>(
|
||||
PostgresEntityDatabaseAdapter,
|
||||
);
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
instance(databaseAdapterMock),
|
||||
new NoOpEntityMetricsAdapter(),
|
||||
TestEntity.name,
|
||||
);
|
||||
|
||||
await new StubQueryContextProvider().runInTransactionAsync(async (queryContext) => {
|
||||
await expect(
|
||||
entityDataManager.loadManyByFieldEqualityConjunctionAsync(queryContext, [], {
|
||||
forUpdate: true,
|
||||
forShare: true,
|
||||
}),
|
||||
).rejects.toThrow('forUpdate and forShare are mutually exclusive');
|
||||
await expect(
|
||||
entityDataManager.loadManyBySQLFragmentAsync(queryContext, sql`TRUE`, {
|
||||
forUpdate: true,
|
||||
forShare: true,
|
||||
}),
|
||||
).rejects.toThrow('forUpdate and forShare are mutually exclusive');
|
||||
});
|
||||
verify(
|
||||
databaseAdapterMock.fetchManyByFieldEqualityConjunctionAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).never();
|
||||
verify(
|
||||
databaseAdapterMock.fetchManyBySQLFragmentAsync(anything(), anything(), anything()),
|
||||
).never();
|
||||
});
|
||||
|
||||
it('throws when skipLocked is set without forUpdate or forShare', async () => {
|
||||
const databaseAdapterMock = mock<PostgresEntityDatabaseAdapter<TestFields, 'customIdField'>>(
|
||||
PostgresEntityDatabaseAdapter,
|
||||
);
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
instance(databaseAdapterMock),
|
||||
new NoOpEntityMetricsAdapter(),
|
||||
TestEntity.name,
|
||||
);
|
||||
|
||||
await new StubQueryContextProvider().runInTransactionAsync(async (queryContext) => {
|
||||
await expect(
|
||||
entityDataManager.loadManyByFieldEqualityConjunctionAsync(queryContext, [], {
|
||||
skipLocked: true,
|
||||
}),
|
||||
).rejects.toThrow('skipLocked requires forUpdate or forShare');
|
||||
await expect(
|
||||
entityDataManager.loadManyBySQLFragmentAsync(queryContext, sql`TRUE`, {
|
||||
skipLocked: true,
|
||||
}),
|
||||
).rejects.toThrow('skipLocked requires forUpdate or forShare');
|
||||
});
|
||||
});
|
||||
|
||||
it('passes forShare and skipLocked through to the database adapter inside of a transaction', async () => {
|
||||
const databaseAdapterMock = mock<PostgresEntityDatabaseAdapter<TestFields, 'customIdField'>>(
|
||||
PostgresEntityDatabaseAdapter,
|
||||
);
|
||||
when(
|
||||
databaseAdapterMock.fetchManyByFieldEqualityConjunctionAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([fieldObject]);
|
||||
when(
|
||||
databaseAdapterMock.fetchManyBySQLFragmentAsync(anything(), anything(), anything()),
|
||||
).thenResolve([fieldObject]);
|
||||
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
instance(databaseAdapterMock),
|
||||
new NoOpEntityMetricsAdapter(),
|
||||
TestEntity.name,
|
||||
);
|
||||
|
||||
await new StubQueryContextProvider().runInTransactionAsync(async (queryContext) => {
|
||||
await entityDataManager.loadManyByFieldEqualityConjunctionAsync(queryContext, [], {
|
||||
forShare: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
await entityDataManager.loadManyBySQLFragmentAsync(queryContext, sql`TRUE`, {
|
||||
forUpdate: true,
|
||||
skipLocked: true,
|
||||
});
|
||||
|
||||
verify(
|
||||
databaseAdapterMock.fetchManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
deepEqual({ forShare: true, skipLocked: true }),
|
||||
),
|
||||
).once();
|
||||
verify(
|
||||
databaseAdapterMock.fetchManyBySQLFragmentAsync(
|
||||
queryContext,
|
||||
anything(),
|
||||
deepEqual({ forUpdate: true, skipLocked: true }),
|
||||
),
|
||||
).once();
|
||||
});
|
||||
});
|
||||
|
||||
it('does not require a transaction when no row locking modifier is set', async () => {
|
||||
const queryContext = new StubQueryContextProvider().getQueryContext();
|
||||
const databaseAdapterMock = mock<PostgresEntityDatabaseAdapter<TestFields, 'customIdField'>>(
|
||||
PostgresEntityDatabaseAdapter,
|
||||
);
|
||||
when(
|
||||
databaseAdapterMock.fetchManyByFieldEqualityConjunctionAsync(
|
||||
anything(),
|
||||
anything(),
|
||||
anything(),
|
||||
),
|
||||
).thenResolve([fieldObject]);
|
||||
const entityDataManager = new EntityKnexDataManager(
|
||||
testEntityConfiguration,
|
||||
instance(databaseAdapterMock),
|
||||
new NoOpEntityMetricsAdapter(),
|
||||
TestEntity.name,
|
||||
);
|
||||
|
||||
const results = await entityDataManager.loadManyByFieldEqualityConjunctionAsync(
|
||||
queryContext,
|
||||
[],
|
||||
{ forUpdate: false, forShare: false, skipLocked: false },
|
||||
);
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pagination', () => {
|
||||
describe('max page size validation', () => {
|
||||
it('should throw when first exceeds maxPageSize', async () => {
|
||||
|
||||
@@ -3,6 +3,32 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **deps:** update dependency koa to v3.2.1 ([#634](https://github.com/expo/entity/issues/634)) ([1c17dc0](https://github.com/expo/entity/commit/1c17dc0f37ec68fb73aae1f92b3ce2c79062b93e))
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# @expo/entity-example
|
||||
|
||||
> Example usage of @expo/entity.
|
||||
|
||||
## Summary
|
||||
@@ -7,4 +8,4 @@ This is a simple API server application built with [Koa](https://koajs.com/). Th
|
||||
|
||||
For demonstration purposes, the application stores its data in-memory, and the memory is cleared when the application is terminated. In a production application, data would be persisted to persistent storage (Postgres) and optionally cached (Redis).
|
||||
|
||||
In this demonstration, all tests are able to be run as unit tests, but in a production application the router test would most likely need to be an integration test. That being said, any entity-related business logic can be unit tested as is demonstrated in `NoteEntity-test`.
|
||||
In this demonstration, all tests are able to be run as unit tests, but in a production application the router test would most likely need to be an integration test. That being said, any entity-related business logic can be unit tested as is demonstrated in `NoteEntity-test`.
|
||||
@@ -1,44 +1,44 @@
|
||||
{
|
||||
"name": "@expo/entity-example",
|
||||
"type": "module",
|
||||
"version": "0.69.0",
|
||||
"private": true,
|
||||
"version": "0.61.0",
|
||||
"description": "An example integration of the @expo/entity framework",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)",
|
||||
"integration": "yarn integration:all --rootDir $(pwd)",
|
||||
"start": "yarn build --noCheck && node --watch --experimental-transform-types --inspect --async-stack-traces --throw-deprecation src/index.ts"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@apollo/server": "5.4.0",
|
||||
"@apollo/server": "5.5.1",
|
||||
"@as-integrations/koa": "1.1.1",
|
||||
"@expo/entity": "workspace:^",
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@koa/bodyparser": "6.1.0",
|
||||
"@koa/cors": "5.0.0",
|
||||
"@koa/router": "15.3.1",
|
||||
"graphql": "16.13.1",
|
||||
"koa": "3.1.2"
|
||||
"@koa/router": "15.4.0",
|
||||
"graphql": "16.13.2",
|
||||
"koa": "3.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.2.0",
|
||||
"@types/koa": "3.0.1",
|
||||
"@jest/globals": "30.5.1",
|
||||
"@types/koa": "3.0.3",
|
||||
"@types/koa__cors": "5.0.1",
|
||||
"@types/koa__router": "12.0.5",
|
||||
"@types/supertest": "7.2.0",
|
||||
"@types/supertest": "7.2.1",
|
||||
"supertest": "7.2.2",
|
||||
"typescript": "5.9.3"
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ class InMemoryDatabaseAdapter<
|
||||
tableIdField: string,
|
||||
id: any,
|
||||
object: object,
|
||||
): Promise<object[]> {
|
||||
): Promise<{ updatedRowCount: number }> {
|
||||
// SQL does not support empty updates, mirror behavior here for better test simulation
|
||||
if (Object.keys(object).length === 0) {
|
||||
throw new Error(`Empty update (${tableIdField} = ${id})`);
|
||||
@@ -98,14 +98,14 @@ class InMemoryDatabaseAdapter<
|
||||
// SQL updates to a nonexistent row succeed but affect 0 rows,
|
||||
// mirror that behavior here for better test simulation
|
||||
if (objectIndex < 0) {
|
||||
return [];
|
||||
return { updatedRowCount: 0 };
|
||||
}
|
||||
|
||||
dbObjects[objectIndex] = {
|
||||
...dbObjects[objectIndex],
|
||||
...object,
|
||||
};
|
||||
return [dbObjects[objectIndex]];
|
||||
return { updatedRowCount: 1 };
|
||||
}
|
||||
|
||||
protected async deleteInternalAsync(
|
||||
|
||||
@@ -3,6 +3,30 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
Full integration tests for testing combinations of database and cache adapters.
|
||||
|
||||
[Documentation](https://expo.github.io/entity/modules/_expo_entity_full_integration_tests.html)
|
||||
[Documentation](https://expo.github.io/entity/modules/_expo_entity_full_integration_tests.html)
|
||||
@@ -1,31 +1,31 @@
|
||||
{
|
||||
"name": "@expo/entity-full-integration-tests",
|
||||
"version": "0.69.0",
|
||||
"private": true,
|
||||
"version": "0.61.0",
|
||||
"description": "Full redis and knex integration tests for the entity framework",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"integration": "yarn integration:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"integration": "yarn integration:all --rootDir $(pwd)"
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^",
|
||||
"@expo/entity-cache-adapter-redis": "workspace:^",
|
||||
"@expo/entity-database-adapter-knex": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.2.0",
|
||||
"typescript": "5.9.3"
|
||||
"@jest/globals": "30.5.1",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
+1
-7
@@ -114,13 +114,7 @@ describe('Entity cache inconsistency', () => {
|
||||
});
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
+2
-14
@@ -114,13 +114,7 @@ describe('Lack of entity cache push safety with RedisCacheInvalidationStrategy.C
|
||||
});
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
@@ -206,13 +200,7 @@ describe('Entity cache push safety with RedisCacheInvalidationStrategy.SURROUNDI
|
||||
});
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
+1
-7
@@ -52,13 +52,7 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
});
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
+1
-7
@@ -103,13 +103,7 @@ describe('Entity integrity', () => {
|
||||
});
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
+1
-7
@@ -191,13 +191,7 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
});
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`),
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
// placeholder file to fix tsc
|
||||
// oxlint-disable unicorn/no-empty-file
|
||||
// placeholder file to fix tsc/typedoc
|
||||
@@ -3,6 +3,30 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
@@ -1,39 +1,39 @@
|
||||
{
|
||||
"name": "@expo/entity-ip-address-field",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "IP address EntityField definitions for @expo/entity",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^",
|
||||
"ip-address": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity-testing-utils": "workspace:^",
|
||||
"@jest/globals": "30.2.0",
|
||||
"typescript": "5.9.3"
|
||||
"@jest/globals": "30.5.1",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,30 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
@@ -9,16 +9,16 @@ this cache with caution - it is nonstandard. The cache is shared between request
|
||||
|
||||
1. Create a concrete implementation of abstract class `EntitySecondaryCacheLoader`, in this example `TestEntitySecondaryCacheLoader`. The underlying data can come from anywhere, but an entity is constructed from the data and then authorized for the viewer.
|
||||
2. Create an instance of your `EntitySecondaryCacheLoader`, passing in a `LocalMemorySecondaryEntityCache`.
|
||||
```typescript
|
||||
const secondaryCacheLoader = new TestSecondaryLocalMemoryCacheLoader(
|
||||
new LocalMemorySecondaryEntityCache(
|
||||
GenericLocalMemoryCacher.createLRUCache<LocalMemoryTestEntityFields>({})
|
||||
),
|
||||
LocalMemoryTestEntity.loader(viewerContext)
|
||||
);
|
||||
```
|
||||
```typescript
|
||||
const secondaryCacheLoader = new TestSecondaryLocalMemoryCacheLoader(
|
||||
new LocalMemorySecondaryEntityCache(
|
||||
GenericLocalMemoryCacher.createLRUCache<LocalMemoryTestEntityFields>({}),
|
||||
),
|
||||
LocalMemoryTestEntity.loader(viewerContext),
|
||||
);
|
||||
```
|
||||
3. Load entities through it:
|
||||
```typescript
|
||||
const loadParams = { id: createdEntity.getID() };
|
||||
const results = await secondaryCacheLoader.loadManyAsync([loadParams]);
|
||||
```
|
||||
```typescript
|
||||
const loadParams = { id: createdEntity.getID() };
|
||||
const results = await secondaryCacheLoader.loadManyAsync([loadParams]);
|
||||
```
|
||||
@@ -1,41 +1,41 @@
|
||||
{
|
||||
"name": "@expo/entity-secondary-cache-local-memory",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "Local memory secondary cache for @expo/entity",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn run lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)",
|
||||
"integration": "yarn integration:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^",
|
||||
"@expo/entity-cache-adapter-local-memory": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/nullthrows": "2.1.0",
|
||||
"@isaacs/ttlcache": "2.1.4",
|
||||
"@jest/globals": "30.2.0",
|
||||
"typescript": "5.9.3"
|
||||
"@isaacs/ttlcache": "2.1.5",
|
||||
"@jest/globals": "30.5.1",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,30 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
@@ -8,18 +8,18 @@
|
||||
|
||||
1. Create a concrete implementation of abstract class `EntitySecondaryCacheLoader`, in this example `TestEntitySecondaryCacheLoader`. The underlying data can come from anywhere, but an entity is constructed from the data and then authorized for the viewer.
|
||||
2. Create an instance of your `EntitySecondaryCacheLoader`, passing in a `RedisSecondaryEntityCache`.
|
||||
```typescript
|
||||
const secondaryCacheLoader = new TestSecondaryRedisCacheLoader(
|
||||
new RedisSecondaryEntityCache(
|
||||
redisTestEntityConfiguration,
|
||||
genericRedisCacheContext,
|
||||
(loadParams) => `${loadParams.id}`
|
||||
),
|
||||
RedisTestEntity.loader(viewerContext)
|
||||
);
|
||||
```
|
||||
```typescript
|
||||
const secondaryCacheLoader = new TestSecondaryRedisCacheLoader(
|
||||
new RedisSecondaryEntityCache(
|
||||
redisTestEntityConfiguration,
|
||||
genericRedisCacheContext,
|
||||
(loadParams) => `${loadParams.id}`,
|
||||
),
|
||||
RedisTestEntity.loader(viewerContext),
|
||||
);
|
||||
```
|
||||
3. Load entities through it:
|
||||
```typescript
|
||||
const loadParams = { id: createdEntity.getID() };
|
||||
const results = await secondaryCacheLoader.loadManyAsync([loadParams]);
|
||||
```
|
||||
```typescript
|
||||
const loadParams = { id: createdEntity.getID() };
|
||||
const results = await secondaryCacheLoader.loadManyAsync([loadParams]);
|
||||
```
|
||||
@@ -1,40 +1,40 @@
|
||||
{
|
||||
"name": "@expo/entity-secondary-cache-redis",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "Redis secondary cache for @expo/entity",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn run lint --fix",
|
||||
"integration": "yarn integration:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^",
|
||||
"@expo/entity-cache-adapter-redis": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/nullthrows": "2.1.0",
|
||||
"@jest/globals": "30.2.0",
|
||||
"ioredis": "5.10.0",
|
||||
"typescript": "5.9.3"
|
||||
"@jest/globals": "30.5.1",
|
||||
"ioredis": "5.11.1",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,21 @@ export class RedisSecondaryEntityCache<
|
||||
constructor(
|
||||
entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
genericRedisCacheContext: GenericRedisCacheContext,
|
||||
constructRedisKey: (params: Readonly<TLoadParams>) => string,
|
||||
cacheKeyNamespace: string,
|
||||
constructRedisKeyParts: (params: Readonly<TLoadParams>) => readonly string[],
|
||||
) {
|
||||
const constructRedisKey = (params: Readonly<TLoadParams>): string => {
|
||||
const cacheKeyParts = [
|
||||
genericRedisCacheContext.cacheKeyPrefix,
|
||||
'secondary',
|
||||
cacheKeyNamespace,
|
||||
...constructRedisKeyParts(params),
|
||||
];
|
||||
const delimiter = genericRedisCacheContext.cacheKeyDelimiter;
|
||||
const escape = (s: string): string =>
|
||||
s.replaceAll('\\', '\\\\').replaceAll(delimiter, `\\${delimiter}`);
|
||||
return cacheKeyParts.map(escape).join(delimiter);
|
||||
};
|
||||
super(new GenericRedisCacher(genericRedisCacheContext, entityConfiguration), constructRedisKey);
|
||||
}
|
||||
}
|
||||
+40
-5
@@ -82,9 +82,7 @@ describe(RedisSecondaryEntityCache, () => {
|
||||
beforeAll(() => {
|
||||
genericRedisCacheContext = {
|
||||
redisClient,
|
||||
makeKeyFn(..._parts: string[]): string {
|
||||
throw new Error('should not be used by this test');
|
||||
},
|
||||
cacheKeyDelimiter: ':',
|
||||
cacheKeyPrefix: 'test-',
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
@@ -114,7 +112,8 @@ describe(RedisSecondaryEntityCache, () => {
|
||||
new RedisSecondaryEntityCache(
|
||||
redisTestEntityConfiguration,
|
||||
genericRedisCacheContext,
|
||||
(loadParams) => `test-key-${loadParams.id}`,
|
||||
'test-namespace',
|
||||
(loadParams) => ['test-key', loadParams.id],
|
||||
),
|
||||
EntitySecondaryCacheLoader.getConstructionUtilsForEntityClass(RedisTestEntity, viewerContext),
|
||||
RedisTestEntity.loaderWithAuthorizationResults(viewerContext),
|
||||
@@ -154,7 +153,8 @@ describe(RedisSecondaryEntityCache, () => {
|
||||
new RedisSecondaryEntityCache(
|
||||
redisTestEntityConfiguration,
|
||||
genericRedisCacheContext,
|
||||
(loadParams) => `test-key-${loadParams.id}`,
|
||||
'test-namespace',
|
||||
(loadParams) => ['test-key', loadParams.id],
|
||||
),
|
||||
EntitySecondaryCacheLoader.getConstructionUtilsForEntityClass(RedisTestEntity, viewerContext),
|
||||
RedisTestEntity.loaderWithAuthorizationResults(viewerContext),
|
||||
@@ -165,4 +165,39 @@ describe(RedisSecondaryEntityCache, () => {
|
||||
expect(results.size).toBe(1);
|
||||
expect(results.get(loadParams)).toBe(null);
|
||||
});
|
||||
|
||||
it('does not collapse cache keys with delimiter-bearing parts and uses namespace', async () => {
|
||||
const viewerContext = new TestViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(genericRedisCacheContext),
|
||||
);
|
||||
|
||||
const id = 'id-with-delimiter-' + genericRedisCacheContext.cacheKeyDelimiter;
|
||||
|
||||
const createdEntity = await RedisTestEntity.creator(viewerContext)
|
||||
.setField('id', id)
|
||||
.setField('name', 'wat')
|
||||
.createAsync();
|
||||
|
||||
const secondaryCacheLoader = new TestSecondaryRedisCacheLoader(
|
||||
new RedisSecondaryEntityCache(
|
||||
redisTestEntityConfiguration,
|
||||
genericRedisCacheContext,
|
||||
'test-namespace',
|
||||
(loadParams) => ['test-key', loadParams.id],
|
||||
),
|
||||
EntitySecondaryCacheLoader.getConstructionUtilsForEntityClass(RedisTestEntity, viewerContext),
|
||||
RedisTestEntity.loaderWithAuthorizationResults(viewerContext),
|
||||
);
|
||||
|
||||
const loadParams = { id };
|
||||
const results = await secondaryCacheLoader.loadManyAsync([loadParams]);
|
||||
expect(results.size).toBe(1);
|
||||
expect(nullthrows(results.get(loadParams)).enforceValue().getID()).toEqual(
|
||||
createdEntity.getID(),
|
||||
);
|
||||
|
||||
const redisKey = `${genericRedisCacheContext.cacheKeyPrefix}:secondary:test-namespace:test-key:id-with-delimiter-\\${genericRedisCacheContext.cacheKeyDelimiter}`;
|
||||
const redisValues = await genericRedisCacheContext.redisClient.mget(redisKey);
|
||||
expect(redisValues[0]).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
EntityConfiguration,
|
||||
EntityPrivacyPolicy,
|
||||
StringField,
|
||||
UUIDField,
|
||||
} from '@expo/entity';
|
||||
|
||||
export type RedisTestEntityFields = {
|
||||
@@ -53,7 +52,7 @@ export const redisTestEntityConfiguration = new EntityConfiguration<RedisTestEnt
|
||||
idField: 'id',
|
||||
tableName: 'redis_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
id: new StringField({
|
||||
columnName: 'id',
|
||||
cache: false,
|
||||
}),
|
||||
|
||||
@@ -3,6 +3,30 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-testing-utils
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-testing-utils
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-testing-utils
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-testing-utils
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-testing-utils
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-testing-utils
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-testing-utils
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# @expo/entity-testing-utils
|
||||
|
||||
A package containing utilities for testing applications that use Entity.
|
||||
A package containing utilities for testing applications that use Entity.
|
||||
@@ -1,44 +1,44 @@
|
||||
{
|
||||
"name": "@expo/entity-testing-utils",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "A package containing utilities for testing applications that use Entity",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn run lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/entity": "workspace:^",
|
||||
"lodash-es": "^4.17.23",
|
||||
"ts-mockito": "^2.6.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.5.1",
|
||||
"@types/lodash-es": "4.17.12",
|
||||
"@types/node": "24.19.1",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@jest/globals": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.2.0",
|
||||
"@types/lodash-es": "4.17.12",
|
||||
"@types/node": "24.12.0",
|
||||
"typescript": "5.9.3"
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
PrivacyPolicyRule,
|
||||
EntityPrivacyPolicyRuleEvaluationContext,
|
||||
} from '@expo/entity';
|
||||
import { RuleEvaluationResult } from '@expo/entity';
|
||||
import { RuleEvaluationResult, normalizeRuleEvaluationOutcome } from '@expo/entity';
|
||||
import { describe, expect, test } from '@jest/globals';
|
||||
|
||||
export interface Case<
|
||||
@@ -25,6 +25,12 @@ export interface Case<
|
||||
TSelectedFields
|
||||
>;
|
||||
entity: TEntity;
|
||||
/**
|
||||
* For skip and deny cases: the exact reason codes the rule must attach to its result, in order.
|
||||
* Omit to assert only the result. An empty array asserts that no reasons were attached.
|
||||
* Ignored for allow cases.
|
||||
*/
|
||||
expectedReasons?: readonly string[];
|
||||
}
|
||||
|
||||
export type CaseMap<
|
||||
@@ -62,9 +68,15 @@ export const describePrivacyPolicyRuleWithAsyncTestCase = <
|
||||
test.each(Array.from(allowCases.keys()))('%p', async (caseKey) => {
|
||||
const { viewerContext, queryContext, evaluationContext, entity } =
|
||||
await allowCases.get(caseKey)!();
|
||||
await expect(
|
||||
privacyPolicyRule.evaluateAsync(viewerContext, queryContext, evaluationContext, entity),
|
||||
).resolves.toEqual(RuleEvaluationResult.ALLOW);
|
||||
const outcome = await privacyPolicyRule.evaluateAsync(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
evaluationContext,
|
||||
entity,
|
||||
);
|
||||
expect(normalizeRuleEvaluationOutcome(outcome).result).toEqual(
|
||||
RuleEvaluationResult.ALLOW,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -72,11 +84,20 @@ export const describePrivacyPolicyRuleWithAsyncTestCase = <
|
||||
if (skipCases && skipCases.size > 0) {
|
||||
describe('skip cases', () => {
|
||||
test.each(Array.from(skipCases.keys()))('%p', async (caseKey) => {
|
||||
const { viewerContext, queryContext, evaluationContext, entity } =
|
||||
const { viewerContext, queryContext, evaluationContext, entity, expectedReasons } =
|
||||
await skipCases.get(caseKey)!();
|
||||
await expect(
|
||||
privacyPolicyRule.evaluateAsync(viewerContext, queryContext, evaluationContext, entity),
|
||||
).resolves.toEqual(RuleEvaluationResult.SKIP);
|
||||
const outcome = normalizeRuleEvaluationOutcome(
|
||||
await privacyPolicyRule.evaluateAsync(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
evaluationContext,
|
||||
entity,
|
||||
),
|
||||
);
|
||||
expect(outcome.result).toEqual(RuleEvaluationResult.SKIP);
|
||||
if (expectedReasons !== undefined) {
|
||||
expect(outcome.reasons).toEqual(expectedReasons);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -84,11 +105,20 @@ export const describePrivacyPolicyRuleWithAsyncTestCase = <
|
||||
if (denyCases && denyCases.size > 0) {
|
||||
describe('deny cases', () => {
|
||||
test.each(Array.from(denyCases.keys()))('%p', async (caseKey) => {
|
||||
const { viewerContext, queryContext, evaluationContext, entity } =
|
||||
const { viewerContext, queryContext, evaluationContext, entity, expectedReasons } =
|
||||
await denyCases.get(caseKey)!();
|
||||
await expect(
|
||||
privacyPolicyRule.evaluateAsync(viewerContext, queryContext, evaluationContext, entity),
|
||||
).resolves.toEqual(RuleEvaluationResult.DENY);
|
||||
const outcome = normalizeRuleEvaluationOutcome(
|
||||
await privacyPolicyRule.evaluateAsync(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
evaluationContext,
|
||||
entity,
|
||||
),
|
||||
);
|
||||
expect(outcome.result).toEqual(RuleEvaluationResult.DENY);
|
||||
if (expectedReasons !== undefined) {
|
||||
expect(outcome.reasons).toEqual(expectedReasons);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -63,7 +63,9 @@ export class StubDatabaseAdapter<
|
||||
tableTuples: (readonly any[])[],
|
||||
): Promise<object[]> {
|
||||
const objectCollection = this.getObjectCollectionForTable(tableName);
|
||||
const results = StubDatabaseAdapter.uniqBy(tableTuples, (tuple) => tuple.join(':')).reduce(
|
||||
const results = StubDatabaseAdapter.uniqBy(tableTuples, (tuple) =>
|
||||
JSON.stringify(tuple),
|
||||
).reduce(
|
||||
(acc, tableTuple) => {
|
||||
return acc.concat(
|
||||
objectCollection.filter((obj) => {
|
||||
@@ -135,7 +137,7 @@ export class StubDatabaseAdapter<
|
||||
tableIdField: string,
|
||||
id: any,
|
||||
object: object,
|
||||
): Promise<object[]> {
|
||||
): Promise<{ updatedRowCount: number }> {
|
||||
// SQL does not support empty updates, mirror behavior here for better test simulation
|
||||
if (Object.keys(object).length === 0) {
|
||||
throw new Error(`Empty update (${tableIdField} = ${id})`);
|
||||
@@ -150,14 +152,14 @@ export class StubDatabaseAdapter<
|
||||
// SQL updates to a nonexistent row succeed but affect 0 rows,
|
||||
// mirror that behavior here for better test simulation
|
||||
if (objectIndex < 0) {
|
||||
return [];
|
||||
return { updatedRowCount: 0 };
|
||||
}
|
||||
|
||||
objectCollection[objectIndex] = {
|
||||
...objectCollection[objectIndex],
|
||||
...object,
|
||||
};
|
||||
return [objectCollection[objectIndex]];
|
||||
return { updatedRowCount: 1 };
|
||||
}
|
||||
|
||||
protected async deleteInternalAsync(
|
||||
|
||||
@@ -34,8 +34,11 @@ export function isEqualWithEntityAware(expected: any, actual: any): boolean {
|
||||
}
|
||||
|
||||
if (expected instanceof SerializableKeyMap && actual instanceof SerializableKeyMap) {
|
||||
if (expected.size !== actual.size) {
|
||||
return false;
|
||||
}
|
||||
for (const [key, value] of expected.entries()) {
|
||||
if (!actual.has(key) || !isEqualWith(value, actual.get(key))) {
|
||||
if (!actual.has(key) || !isEqualWithEntityAware(value, actual.get(key))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,62 @@
|
||||
import type { EntityPrivacyPolicyRuleEvaluationContext } from '@expo/entity';
|
||||
import type { EntityPrivacyPolicyRuleEvaluationContext, RuleEvaluationOutcome } from '@expo/entity';
|
||||
import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
AlwaysDenyPrivacyPolicyRule,
|
||||
AlwaysSkipPrivacyPolicyRule,
|
||||
EntityQueryContext,
|
||||
PrivacyPolicyRule,
|
||||
ViewerContext,
|
||||
denyWithReasons,
|
||||
skipWithReasons,
|
||||
} from '@expo/entity';
|
||||
import { describe } from '@jest/globals';
|
||||
import { anything, instance, mock } from 'ts-mockito';
|
||||
|
||||
import { describePrivacyPolicyRuleWithAsyncTestCase } from '../PrivacyPolicyRuleTestUtils.ts';
|
||||
import {
|
||||
describePrivacyPolicyRule,
|
||||
describePrivacyPolicyRuleWithAsyncTestCase,
|
||||
} from '../PrivacyPolicyRuleTestUtils.ts';
|
||||
|
||||
class SkipWithReasonsRule extends PrivacyPolicyRule<any, any, any, any, any> {
|
||||
async evaluateAsync(): Promise<RuleEvaluationOutcome> {
|
||||
return skipWithReasons('NOT_OWNER', 'NOT_MEMBER');
|
||||
}
|
||||
}
|
||||
|
||||
class DenyWithReasonsRule extends PrivacyPolicyRule<any, any, any, any, any> {
|
||||
async evaluateAsync(): Promise<RuleEvaluationOutcome> {
|
||||
return denyWithReasons('BLOCKED');
|
||||
}
|
||||
}
|
||||
|
||||
const makeCase = (expectedReasons?: readonly string[]): any => ({
|
||||
viewerContext: instance(mock(ViewerContext)),
|
||||
queryContext: instance(mock(EntityQueryContext)),
|
||||
evaluationContext:
|
||||
instance(mock<EntityPrivacyPolicyRuleEvaluationContext<any, any, any, any, any>>()),
|
||||
entity: anything(),
|
||||
expectedReasons,
|
||||
});
|
||||
|
||||
describe(describePrivacyPolicyRule, () => {
|
||||
describe('expectedReasons', () => {
|
||||
describePrivacyPolicyRule(new SkipWithReasonsRule(), {
|
||||
skipCases: [makeCase(), makeCase(['NOT_OWNER', 'NOT_MEMBER'])],
|
||||
});
|
||||
|
||||
describePrivacyPolicyRule(new DenyWithReasonsRule(), {
|
||||
denyCases: [makeCase(), makeCase(['BLOCKED'])],
|
||||
});
|
||||
|
||||
describePrivacyPolicyRule(new AlwaysSkipPrivacyPolicyRule(), {
|
||||
skipCases: [makeCase([])],
|
||||
});
|
||||
|
||||
describePrivacyPolicyRule(new AlwaysDenyPrivacyPolicyRule(), {
|
||||
denyCases: [makeCase([])],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(describePrivacyPolicyRuleWithAsyncTestCase, () => {
|
||||
describe('default args do not execute', () => {
|
||||
|
||||
@@ -117,6 +117,55 @@ describe(StubDatabaseAdapter, () => {
|
||||
results2.get(new CompositeFieldValueHolder({ stringField: 'not-in-db', intField: 5 })),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not collapse distinct composite tuples that stringify with the same delimiter join', async () => {
|
||||
const queryContext = instance(mock(EntityQueryContext));
|
||||
const databaseAdapter = new StubDatabaseAdapter<TestFields, 'customIdField'>(
|
||||
testEntityConfiguration,
|
||||
StubDatabaseAdapter.convertFieldObjectsToDataStore(
|
||||
testEntityConfiguration,
|
||||
new Map([
|
||||
[
|
||||
testEntityConfiguration.tableName,
|
||||
[
|
||||
{
|
||||
customIdField: 'id1',
|
||||
testIndexedField: 'b',
|
||||
intField: 5,
|
||||
stringField: 'a:b',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
{
|
||||
customIdField: 'id2',
|
||||
testIndexedField: 'b:c',
|
||||
intField: 10,
|
||||
stringField: 'a',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
const results = await databaseAdapter.fetchManyWhereAsync(
|
||||
queryContext,
|
||||
new CompositeFieldHolder<TestFields, 'customIdField'>(['stringField', 'testIndexedField']),
|
||||
[
|
||||
new CompositeFieldValueHolder({ stringField: 'a:b', testIndexedField: 'c' }),
|
||||
new CompositeFieldValueHolder({ stringField: 'a', testIndexedField: 'b:c' }),
|
||||
],
|
||||
);
|
||||
|
||||
expect(
|
||||
results.get(new CompositeFieldValueHolder({ stringField: 'a:b', testIndexedField: 'c' })),
|
||||
).toHaveLength(0);
|
||||
expect(
|
||||
results.get(new CompositeFieldValueHolder({ stringField: 'a', testIndexedField: 'b:c' })),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchOneWhereAsync', () => {
|
||||
@@ -279,13 +328,9 @@ describe(StubDatabaseAdapter, () => {
|
||||
]),
|
||||
),
|
||||
);
|
||||
const result = await databaseAdapter.updateAsync(queryContext, 'customIdField', 'hello', {
|
||||
await databaseAdapter.updateAsync(queryContext, 'customIdField', 'hello', {
|
||||
stringField: 'b',
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
stringField: 'b',
|
||||
testIndexedField: 'h1',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws error when empty update to match common DBMS behavior', async () => {
|
||||
|
||||
@@ -60,7 +60,14 @@ describe(isEqualWithEntityAware, () => {
|
||||
const map3 = new SingleFieldValueHolderMap(
|
||||
new Map([[new SingleFieldValueHolder('foo2'), 'bar']]),
|
||||
);
|
||||
const map4 = new SingleFieldValueHolderMap(
|
||||
new Map([
|
||||
[new SingleFieldValueHolder('foo'), 'bar'],
|
||||
[new SingleFieldValueHolder('extra'), 'bar'],
|
||||
]),
|
||||
);
|
||||
expect(isEqualWithEntityAware(map1, map2)).toBe(true);
|
||||
expect(isEqualWithEntityAware(map1, map3)).toBe(false);
|
||||
expect(isEqualWithEntityAware(map1, map4)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,34 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.69.0](https://github.com/expo/entity/compare/v0.68.0...v0.69.0) (2026-09-29)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity
|
||||
|
||||
# [0.68.0](https://github.com/expo/entity/compare/v0.67.0...v0.68.0) (2026-09-25)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity
|
||||
|
||||
# [0.67.0](https://github.com/expo/entity/compare/v0.66.0...v0.67.0) (2026-09-18)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity
|
||||
|
||||
# [0.66.0](https://github.com/expo/entity/compare/v0.65.0...v0.66.0) (2026-08-03)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity
|
||||
|
||||
# [0.65.0](https://github.com/expo/entity/compare/v0.64.0...v0.65.0) (2026-07-10)
|
||||
|
||||
### Features
|
||||
|
||||
- accept array of parent entity classes in cascade deletion rule ([#650](https://github.com/expo/entity/issues/650)) ([df75910](https://github.com/expo/entity/commit/df75910cbdc89df60ed2f23dbedf8862ed5c9077))
|
||||
|
||||
# [0.62.0](https://github.com/expo/entity/compare/v0.61.0...v0.62.0) (2026-03-16)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- remove unused arg from EntityInvalidationUtils ([#536](https://github.com/expo/entity/issues/536)) ([0a1d1b5](https://github.com/expo/entity/commit/0a1d1b5972c15c932f5c31015f2519163f882f83))
|
||||
|
||||
# [0.61.0](https://github.com/expo/entity/compare/v0.60.0...v0.61.0) (2026-03-12)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity
|
||||
|
||||
@@ -10,4 +10,4 @@ Authorization of create, read, update, and delete operations for an entity are d
|
||||
|
||||
Entites are loaded through an EntityLoader, which is responsible for orchestrating fetching, caching, and authorization of entity loads.
|
||||
|
||||
Entities are mutated and deleted through an EntityMutator, which is responsible for orchestrating database writes, cache invalidation, and authorization of entity mutations.
|
||||
Entities are mutated and deleted through an EntityMutator, which is responsible for orchestrating database writes, cache invalidation, and authorization of entity mutations.
|
||||
@@ -1,45 +1,45 @@
|
||||
{
|
||||
"name": "@expo/entity",
|
||||
"version": "0.61.0",
|
||||
"version": "0.69.0",
|
||||
"description": "A privacy-first data model",
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"license": "MIT",
|
||||
"author": "Expo",
|
||||
"files": [
|
||||
"build",
|
||||
"!*.tsbuildinfo",
|
||||
"!__*",
|
||||
"src"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "build/src/index.js",
|
||||
"types": "build/src/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"prepack": "rm -rf build && yarn build",
|
||||
"clean": "yarn build --clean",
|
||||
"lint": "yarn run --top-level eslint src",
|
||||
"lint": "yarn run --top-level oxlint --type-aware src",
|
||||
"lint-fix": "yarn run lint --fix",
|
||||
"test": "yarn test:all --rootDir $(pwd)"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"keywords": [
|
||||
"entity"
|
||||
],
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@expo/results": "^1.0.0",
|
||||
"dataloader": "^2.2.3",
|
||||
"invariant": "^2.2.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jest/globals": "30.2.0",
|
||||
"@jest/globals": "30.5.1",
|
||||
"@types/invariant": "2.2.37",
|
||||
"@types/lodash-es": "4.17.12",
|
||||
"@types/node": "24.12.0",
|
||||
"lodash-es": "4.17.23",
|
||||
"@types/node": "24.19.1",
|
||||
"lodash-es": "4.18.1",
|
||||
"ts-mockito": "2.6.1",
|
||||
"typescript": "5.9.3",
|
||||
"uuid": "13.0.0"
|
||||
"typescript": "6.0.3",
|
||||
"uuid": "14.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ export class AuthorizationResultBasedEntityAssociationLoader<
|
||||
Result<null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity>
|
||||
> {
|
||||
const associatedEntityID = this.entity.getField(fieldIdentifyingAssociatedEntity);
|
||||
if (!associatedEntityID) {
|
||||
if (associatedEntityID === null || associatedEntityID === undefined) {
|
||||
return result(null) as Result<
|
||||
null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity
|
||||
>;
|
||||
@@ -75,9 +75,7 @@ export class AuthorizationResultBasedEntityAssociationLoader<
|
||||
.getViewerScopedEntityCompanionForClass(associatedEntityClass)
|
||||
.getLoaderFactory()
|
||||
.forLoad(this.queryContext, { previousValue: null, cascadingDeleteCause: null });
|
||||
return (await loader.loadByIDAsync(associatedEntityID)) as Result<
|
||||
null extends TFields[TIdentifyingField] ? TAssociatedEntity | null : TAssociatedEntity
|
||||
>;
|
||||
return await loader.loadByIDAsync(associatedEntityID);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -150,7 +150,7 @@ export class AuthorizationResultBasedEntityLoader<
|
||||
* @internal
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore -- this method is used in EntityPrivacyUtils, but is not intended to be part of the public API of this class, so it is marked as private.
|
||||
// @ts-expect-error -- this method is used in EntityPrivacyUtils, but is not intended to be part of the public API of this class, so it is marked as private.
|
||||
private async loadOneByFieldEqualingAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
fieldName: N,
|
||||
fieldValue: NonNullable<TFields[N]>,
|
||||
@@ -247,10 +247,7 @@ export class AuthorizationResultBasedEntityLoader<
|
||||
* @returns entity result for matching ID, or null if no entity exists for ID.
|
||||
*/
|
||||
async loadByIDNullableAsync(id: TFields[TIDField]): Promise<Result<TEntity> | null> {
|
||||
return await this.loadByFieldEqualingAsync(
|
||||
this.entityConfiguration.idField as TSelectedFields,
|
||||
id,
|
||||
);
|
||||
return await this.loadByFieldEqualingAsync(this.entityConfiguration.idField, id);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -261,7 +258,7 @@ export class AuthorizationResultBasedEntityLoader<
|
||||
ids: readonly TFields[TIDField][],
|
||||
): Promise<ReadonlyMap<TFields[TIDField], Result<TEntity>>> {
|
||||
const entityResults = (await this.loadManyByFieldEqualingManyAsync(
|
||||
this.entityConfiguration.idField as TSelectedFields,
|
||||
this.entityConfiguration.idField,
|
||||
ids,
|
||||
)) as ReadonlyMap<TFields[TIDField], readonly Result<TEntity>[]>;
|
||||
return mapMap(entityResults, (entityResultsForId, id) => {
|
||||
@@ -287,7 +284,7 @@ export class AuthorizationResultBasedEntityLoader<
|
||||
ids: readonly TFields[TIDField][],
|
||||
): Promise<ReadonlyMap<TFields[TIDField], Result<TEntity> | null>> {
|
||||
const entityResults = (await this.loadManyByFieldEqualingManyAsync(
|
||||
this.entityConfiguration.idField as TSelectedFields,
|
||||
this.entityConfiguration.idField,
|
||||
ids,
|
||||
)) as ReadonlyMap<TFields[TIDField], readonly Result<TEntity>[]>;
|
||||
return mapMap(entityResults, (entityResultsForId) => {
|
||||
|
||||
@@ -804,6 +804,14 @@ export class AuthorizationResultBasedDeleteMutator<
|
||||
processedEntityIdentifiersFromTransitiveDeletions: Set<string>,
|
||||
skipDatabaseDeletion: boolean,
|
||||
): Promise<Result<void>> {
|
||||
// prevent infinite reference cycles AND avoid re-running deletion side effects
|
||||
// (authorization, validators, triggers, DB delete, invalidation) for an entity that
|
||||
// is already being deleted higher up the cascade stack
|
||||
if (processedEntityIdentifiersFromTransitiveDeletions.has(this.entity.getUniqueIdentifier())) {
|
||||
return result();
|
||||
}
|
||||
processedEntityIdentifiersFromTransitiveDeletions.add(this.entity.getUniqueIdentifier());
|
||||
|
||||
const authorizeDeleteResult = await asyncResult(
|
||||
this.privacyPolicy.authorizeDeleteAsync(
|
||||
this.viewerContext,
|
||||
@@ -928,12 +936,6 @@ export class AuthorizationResultBasedDeleteMutator<
|
||||
queryContext: EntityTransactionalQueryContext,
|
||||
processedEntityIdentifiers: Set<string>,
|
||||
): Promise<void> {
|
||||
// prevent infinite reference cycles by keeping track of entities already processed
|
||||
if (processedEntityIdentifiers.has(entity.getUniqueIdentifier())) {
|
||||
return;
|
||||
}
|
||||
processedEntityIdentifiers.add(entity.getUniqueIdentifier());
|
||||
|
||||
const companionDefinition = this.companionProvider.getCompanionForEntity(
|
||||
entity.constructor as IEntityClass<
|
||||
TFields,
|
||||
@@ -1016,6 +1018,7 @@ export class AuthorizationResultBasedDeleteMutator<
|
||||
mutatorFactory
|
||||
.forUpdate(inboundReferenceEntity, queryContext, newCascadingDeleteCause)
|
||||
.setField(fieldName, null)
|
||||
// eslint-disable-next-line no-unexpected-multiline
|
||||
['updateInTransactionAsync'](/* skipDatabaseUpdate */ true),
|
||||
),
|
||||
),
|
||||
@@ -1029,6 +1032,7 @@ export class AuthorizationResultBasedDeleteMutator<
|
||||
mutatorFactory
|
||||
.forUpdate(inboundReferenceEntity, queryContext, newCascadingDeleteCause)
|
||||
.setField(fieldName, null)
|
||||
// eslint-disable-next-line no-unexpected-multiline
|
||||
['updateInTransactionAsync'](/* skipDatabaseUpdate */ false),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -127,11 +127,13 @@ export interface EntityCompanionDefinition<
|
||||
*/
|
||||
export class EntityCompanionProvider {
|
||||
private readonly companionDefinitionMap: Map<
|
||||
string,
|
||||
IEntityClass<any, any, any, any, any, any>,
|
||||
EntityCompanionDefinition<any, any, any, any, any, any>
|
||||
> = new Map();
|
||||
private readonly companionMap: Map<string, EntityCompanion<any, any, any, any, any, any>> =
|
||||
new Map();
|
||||
private readonly companionMap: Map<
|
||||
IEntityClass<any, any, any, any, any, any>,
|
||||
EntityCompanion<any, any, any, any, any, any>
|
||||
> = new Map();
|
||||
private readonly tableDataCoordinatorMap: Map<string, EntityTableDataCoordinator<any, any>> =
|
||||
new Map();
|
||||
|
||||
@@ -192,14 +194,14 @@ export class EntityCompanionProvider {
|
||||
): EntityCompanion<TFields, TIDField, TViewerContext, TEntity, TPrivacyPolicy, TSelectedFields> {
|
||||
const entityCompanionDefinition = computeIfAbsent(
|
||||
this.companionDefinitionMap,
|
||||
entityClass.name,
|
||||
entityClass,
|
||||
() => entityClass.defineCompanionDefinition(),
|
||||
);
|
||||
const tableDataCoordinator = this.getTableDataCoordinatorForEntity(
|
||||
entityCompanionDefinition.entityConfiguration,
|
||||
entityClass.name,
|
||||
);
|
||||
return computeIfAbsent(this.companionMap, entityClass.name, () => {
|
||||
return computeIfAbsent(this.companionMap, entityClass, () => {
|
||||
return new EntityCompanion(
|
||||
this,
|
||||
entityCompanionDefinition,
|
||||
@@ -228,7 +230,12 @@ export class EntityCompanionProvider {
|
||||
entityConfiguration: EntityConfiguration<TFields, TIDField>,
|
||||
entityClassName: string,
|
||||
): EntityTableDataCoordinator<TFields, TIDField> {
|
||||
return computeIfAbsent(this.tableDataCoordinatorMap, entityConfiguration.tableName, () => {
|
||||
const tableDataCoordinatorKey = [
|
||||
entityConfiguration.databaseAdapterFlavor,
|
||||
entityConfiguration.cacheAdapterFlavor,
|
||||
entityConfiguration.tableName,
|
||||
].join('\0');
|
||||
return computeIfAbsent(this.tableDataCoordinatorMap, tableDataCoordinatorKey, () => {
|
||||
const entityDatabaseAdapterFlavor = this.databaseAdapterFlavors.get(
|
||||
entityConfiguration.databaseAdapterFlavor,
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ import invariant from 'invariant';
|
||||
|
||||
import type { IEntityClass } from './Entity.ts';
|
||||
import type { CacheAdapterFlavor, DatabaseAdapterFlavor } from './EntityCompanionProvider.ts';
|
||||
import { RESERVED_ENTITY_COUNT_QUERY_ALIAS } from './EntityDatabaseAdapter.ts';
|
||||
import type { EntityFieldDefinition } from './EntityFieldDefinition.ts';
|
||||
import type { SerializedCompositeFieldHolder } from './internal/CompositeFieldHolder.ts';
|
||||
import { CompositeFieldHolder } from './internal/CompositeFieldHolder.ts';
|
||||
@@ -183,8 +184,7 @@ export class EntityConfiguration<
|
||||
|
||||
// external schema is a Record to typecheck that all fields have FieldDefinitions,
|
||||
// but internally the most useful representation is a map for lookups
|
||||
EntityConfiguration.validateSchema<TFields, TIDField>(schema);
|
||||
this.schema = new Map(Object.entries(schema));
|
||||
this.schema = this.validateSchemaMap(new Map(Object.entries(schema)));
|
||||
|
||||
this.cacheableKeys = EntityConfiguration.computeCacheableKeys(this.schema);
|
||||
this.compositeFieldInfo = new CompositeFieldInfo(compositeFieldDefinitions ?? []);
|
||||
@@ -194,21 +194,27 @@ export class EntityConfiguration<
|
||||
this.dbToEntityFieldsKeyMapping = invertMap(this.entityToDBFieldsKeyMapping);
|
||||
}
|
||||
|
||||
private static validateSchema<
|
||||
TFields extends Record<string, any>,
|
||||
TIDField extends keyof TFields,
|
||||
>(
|
||||
schema: Omit<Record<keyof TFields, EntityFieldDefinition<any, false>>, TIDField> &
|
||||
Record<TIDField, EntityFieldDefinition<any, true>>,
|
||||
): void {
|
||||
const disallowedFieldsKeys = Object.getOwnPropertyNames(Object.prototype);
|
||||
for (const disallowedFieldsKey of disallowedFieldsKeys) {
|
||||
if (Object.hasOwn(schema, disallowedFieldsKey)) {
|
||||
private validateSchemaMap(
|
||||
schemaMap: ReadonlyMap<keyof TFields, EntityFieldDefinition<any, any>>,
|
||||
): ReadonlyMap<keyof TFields, EntityFieldDefinition<any, any>> {
|
||||
for (const disallowedFieldName of Object.getOwnPropertyNames(Object.prototype)) {
|
||||
if (schemaMap.has(disallowedFieldName)) {
|
||||
throw new Error(
|
||||
`Entity field name not allowed to prevent conflicts with standard Object prototype fields: ${disallowedFieldsKey}`,
|
||||
`Entity field name not allowed to prevent conflicts with standard Object prototype fields: ${disallowedFieldName}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// check for column named RESERVED_ENTITY_COUNT_QUERY_ALIAS which is used for count queries and would cause issues if used as a column name for an entity field
|
||||
for (const [fieldName, fieldDefinition] of schemaMap) {
|
||||
if (fieldDefinition.columnName === RESERVED_ENTITY_COUNT_QUERY_ALIAS) {
|
||||
throw new Error(
|
||||
`Entity field "${String(fieldName)}" has disallowed column name "${RESERVED_ENTITY_COUNT_QUERY_ALIAS}" which is reserved for count queries. Choose a different column name.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return schemaMap;
|
||||
}
|
||||
|
||||
private static computeCacheableKeys<TFields extends Record<string, any>>(
|
||||
|
||||
@@ -73,7 +73,7 @@ export class EntityConstructionUtils<
|
||||
const selectedFields = pick(fieldsObject, entitySelectedFields);
|
||||
return new this.entityClass({
|
||||
viewerContext: this.viewerContext,
|
||||
id: id as TFields[TIDField],
|
||||
id,
|
||||
databaseFields: fieldsObject,
|
||||
selectedFields,
|
||||
});
|
||||
|
||||
@@ -68,6 +68,6 @@ export class EntityCreator<
|
||||
return this.viewerContext
|
||||
.getViewerScopedEntityCompanionForClass(this.entityClass)
|
||||
.getMutatorFactory()
|
||||
.forCreate(this.queryContext);
|
||||
.forCreate(this.viewerContext, this.queryContext);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user