mirror of
https://github.com/expo/entity.git
synced 2026-11-15 17:32:07 -10:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47d0eac78e | ||
|
|
2069a0d9fd | ||
|
|
83fe9cdea5 | ||
|
|
1934216b70 | ||
|
|
92f5529eba | ||
|
|
67732d6847 | ||
|
|
bb0cd51eb5 | ||
|
|
abd86b91d3 | ||
|
|
b5f734b1e1 | ||
|
|
b11bd24351 | ||
|
|
684f91b1f2 | ||
|
|
e381f5b2ac | ||
|
|
69692c3b64 | ||
|
|
dbf1e03039 | ||
|
|
0fb74137f2 | ||
|
|
a77b914ad6 | ||
|
|
acbad826a3 | ||
|
|
8bdd9f7ac2 | ||
|
|
bc6a0d4310 |
No files matched your search
+47
-1
@@ -3,6 +3,52 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
|
||||
# [0.31.1](https://github.com/expo/entity/compare/v0.31.0...v0.31.1) (2023-03-06)
|
||||
|
||||
### Features
|
||||
* add loadFirstByFieldEqualityConjunction, a convenience method ([#206](https://github.com/expo/entity/pull/206)) ([1934216](https://github.com/expo/entity/commit/1934216b70572cf2b9693e0f14939f49b90427dd))
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package root
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add example of redis mget batching using @expo/batcher ([#199](https://github.com/expo/entity/issues/199)) ([684f91b](https://github.com/expo/entity/commit/684f91b1f270851dbe331df2e2620664eea17266))
|
||||
* change redis cache adapter to use redis-like interface ([#200](https://github.com/expo/entity/issues/200)) ([e381f5b](https://github.com/expo/entity/commit/e381f5b2acfc17dcade2cf6e8506fa1c1c255e73))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add BigIntField ([#193](https://github.com/expo/entity/issues/193)) ([acbad82](https://github.com/expo/entity/commit/acbad826a37bb5a054b4dcf9be91d11aa5f7f29a))
|
||||
* nested transactions ([#194](https://github.com/expo/entity/issues/194)) ([a77b914](https://github.com/expo/entity/commit/a77b914ad6dc018d1e309c9caf4971088a553ecf))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
|
||||
@@ -96,7 +142,7 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline
|
||||
|
||||
### Chores
|
||||
|
||||
* Refactor cachers to use an abstract class and interface ([#157](https://github.com/expo/entity/pull/157))
|
||||
* Refactor cachers to use an abstract class and interface ([#157](https://github.com/expo/entity/pull/157))
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -80,18 +80,10 @@ Note: The entity framework instance should not be shared across multiple request
|
||||
|
||||
## Releasing
|
||||
|
||||
To release a new version, let's say `v1.0.0` for example:
|
||||
1. `git checkout -b bump-v1.0.0`
|
||||
1. `yarn lerna version [patch|minor|major] -- --no-push --conventional-commits`
|
||||
1. `git push -u origin bump-v1.0.0`
|
||||
1. Create a PR from the `bump-v1.0.0` branch, wait for tests, and commit the PR using GitHub interface.
|
||||
1. `git checkout main && git pull`
|
||||
1. `git tag -d v1.0.0`
|
||||
1. `git tag v1.0.0`
|
||||
1. `git push origin v1.0.0`
|
||||
To release a new version:
|
||||
1. `git checkout main`
|
||||
1. `yarn lerna publish [patch|minor|major] -- --conventional-commits`
|
||||
1. In GitHub release interface, create a new release from the tag, copy changelog changes to release description.
|
||||
1. `yarn clean && yarn tsc`
|
||||
1. In each public subpackage, run `npm publish` and enter 2FA token.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+1
-1
@@ -4,5 +4,5 @@
|
||||
],
|
||||
"npmClient": "yarn",
|
||||
"useWorkspaces": true,
|
||||
"version": "0.27.0"
|
||||
"version": "0.31.1"
|
||||
}
|
||||
+2
-1
@@ -16,6 +16,7 @@
|
||||
"barrelsby": "lerna run barrelsby"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/batcher": "^1.0.0",
|
||||
"@expo/entity": "file:packages/entity",
|
||||
"@expo/results": "^1.0.0",
|
||||
"@types/invariant": "^2.2.33",
|
||||
@@ -30,7 +31,7 @@
|
||||
"eslint": "^7.7.0",
|
||||
"eslint-config-universe": "^7.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.2.16",
|
||||
"ioredis": "^5.0.4",
|
||||
"ioredis": "^5.2.5",
|
||||
"jest": "^26.6.3",
|
||||
"lerna": "^5.4.0",
|
||||
"lru-cache": "^6.0.0",
|
||||
|
||||
@@ -3,6 +3,38 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-local-memory
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-cache-adapter-local-memory",
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "Cross-request local memory cache adapter for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -33,6 +33,6 @@
|
||||
"lru-cache": "^6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.27.0"
|
||||
"@expo/entity": "^0.31.1"
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,42 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add example of redis mget batching using @expo/batcher ([#199](https://github.com/expo/entity/issues/199)) ([684f91b](https://github.com/expo/entity/commit/684f91b1f270851dbe331df2e2620664eea17266))
|
||||
* change redis cache adapter to use redis-like interface ([#200](https://github.com/expo/entity/issues/200)) ([e381f5b](https://github.com/expo/entity/commit/e381f5b2acfc17dcade2cf6e8506fa1c1c255e73))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-cache-adapter-redis
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-cache-adapter-redis",
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "Redis cache adapter for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -31,7 +31,7 @@
|
||||
"ioredis": ">=5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.27.0",
|
||||
"ioredis": "^5.0.4"
|
||||
"@expo/entity": "^0.31.1",
|
||||
"ioredis": "^5.2.5"
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
transformFieldsToCacheObject,
|
||||
IEntityGenericCacher,
|
||||
} from '@expo/entity';
|
||||
import { Redis } from 'ioredis';
|
||||
|
||||
import { redisTransformerMap } from './RedisCommon';
|
||||
import wrapNativeRedisCallAsync from './errors/wrapNativeRedisCallAsync';
|
||||
@@ -15,11 +14,22 @@ import wrapNativeRedisCallAsync from './errors/wrapNativeRedisCallAsync';
|
||||
// The sentinel value is distinct from any (positively) cached value.
|
||||
const DOES_NOT_EXIST_REDIS = '';
|
||||
|
||||
export interface IRedisTransaction {
|
||||
set(key: string, value: string, secondsToken: 'EX', seconds: number): this;
|
||||
exec(): Promise<any>;
|
||||
}
|
||||
|
||||
export interface IRedis {
|
||||
mget(...args: [...keys: string[]]): Promise<(string | null)[]>;
|
||||
multi(): IRedisTransaction;
|
||||
del(...args: [...keys: string[]]): Promise<any>;
|
||||
}
|
||||
|
||||
export interface GenericRedisCacheContext {
|
||||
/**
|
||||
* Instance of ioredis.Redis
|
||||
*/
|
||||
redisClient: Redis;
|
||||
redisClient: IRedis;
|
||||
|
||||
/**
|
||||
* TTL for caching database hits. Successive entity loads within this TTL
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { EntityCacheAdapter, EntityConfiguration, CacheLoadResult, mapKeys } from '@expo/entity';
|
||||
import invariant from 'invariant';
|
||||
import type { Redis } from 'ioredis';
|
||||
|
||||
import GenericRedisCacher from './GenericRedisCacher';
|
||||
import GenericRedisCacher, { IRedis } from './GenericRedisCacher';
|
||||
|
||||
export interface RedisCacheAdapterContext {
|
||||
/**
|
||||
* Instance of ioredis.Redis
|
||||
*/
|
||||
redisClient: Redis;
|
||||
redisClient: IRedis;
|
||||
|
||||
/**
|
||||
* Create a key string for key parts (cache key prefix, versions, entity name, etc).
|
||||
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
import { Batcher } from '@expo/batcher';
|
||||
import { ViewerContext, zipToMap } from '@expo/entity';
|
||||
import invariant from 'invariant';
|
||||
import Redis from 'ioredis';
|
||||
import nullthrows from 'nullthrows';
|
||||
import { URL } from 'url';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { IRedis, IRedisTransaction } from '../GenericRedisCacher';
|
||||
import RedisCacheAdapter, { RedisCacheAdapterContext } from '../RedisCacheAdapter';
|
||||
import RedisTestEntity from '../testfixtures/RedisTestEntity';
|
||||
import { createRedisIntegrationTestEntityCompanionProvider } from '../testfixtures/createRedisIntegrationTestEntityCompanionProvider';
|
||||
|
||||
class BatchedRedis implements IRedis {
|
||||
private readonly mgetBatcher = new Batcher<string[], (string | null)[]>(
|
||||
this.batchMgetAsync.bind(this),
|
||||
{
|
||||
maxBatchInterval: 0,
|
||||
}
|
||||
);
|
||||
|
||||
constructor(private readonly redis: Redis) {}
|
||||
|
||||
private async batchMgetAsync(keySets: string[][]): Promise<(string | null)[][]> {
|
||||
// ordered distinct keys to fetch
|
||||
const allKeysToFetch = [...new Set(keySets.flat())];
|
||||
|
||||
// fetch the distinct keys
|
||||
const allResults = await this.redis.mget(...allKeysToFetch);
|
||||
|
||||
// put them into a map for fast lookup
|
||||
const keysToResults = zipToMap(allKeysToFetch, allResults);
|
||||
|
||||
// re-associate them with original key sets
|
||||
return keySets.map((keySet) =>
|
||||
keySet.map((key) => {
|
||||
const result = keysToResults.get(key);
|
||||
invariant(result !== undefined, 'result should not be undefined');
|
||||
return result;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async mget(...args: string[]): Promise<(string | null)[]> {
|
||||
return await this.mgetBatcher.batchAsync(args);
|
||||
}
|
||||
|
||||
multi(): IRedisTransaction {
|
||||
return this.redis.multi();
|
||||
}
|
||||
|
||||
async del(...args: string[]): Promise<void> {
|
||||
await this.redis.del(...args);
|
||||
}
|
||||
}
|
||||
|
||||
describe(RedisCacheAdapter, () => {
|
||||
const redis = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
const redisClient = new BatchedRedis(redis);
|
||||
|
||||
let redisCacheAdapterContext: RedisCacheAdapterContext;
|
||||
|
||||
beforeAll(() => {
|
||||
redisCacheAdapterContext = {
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
part.replace('\\', '\\\\').replace(delimiter, `\\${delimiter}`)
|
||||
);
|
||||
return escapedParts.join(delimiter);
|
||||
},
|
||||
cacheKeyPrefix: 'test-',
|
||||
cacheKeyVersion: 1,
|
||||
ttlSecondsPositive: 86400, // 1 day
|
||||
ttlSecondsNegative: 600, // 10 minutes
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await redis.flushdb();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
redis.disconnect();
|
||||
});
|
||||
|
||||
it('has correct caching behavior', async () => {
|
||||
// simulate two requests
|
||||
const viewerContext = new ViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(redisCacheAdapterContext)
|
||||
);
|
||||
|
||||
const mgetSpy = jest.spyOn(redis, 'mget');
|
||||
|
||||
const cacheAdapter = viewerContext.entityCompanionProvider.getCompanionForEntity(
|
||||
RedisTestEntity,
|
||||
RedisTestEntity.getCompanionDefinition()
|
||||
)['tableDataCoordinator']['cacheAdapter'];
|
||||
const cacheKeyMaker = cacheAdapter['makeCacheKey'].bind(cacheAdapter);
|
||||
|
||||
const entity1Created = await RedisTestEntity.creator(viewerContext)
|
||||
.setField('name', 'blah')
|
||||
.enforceCreateAsync();
|
||||
|
||||
// loading an entity should put it in cache. load by multiple requests and multiple fields in same tick to ensure batch works
|
||||
mgetSpy.mockClear();
|
||||
const viewerContext1 = new ViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(redisCacheAdapterContext)
|
||||
);
|
||||
const viewerContext2 = new ViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(redisCacheAdapterContext)
|
||||
);
|
||||
const viewerContext3 = new ViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(redisCacheAdapterContext)
|
||||
);
|
||||
const [entity1, entity2, entity3] = await Promise.all([
|
||||
RedisTestEntity.loader(viewerContext1).enforcing().loadByIDAsync(entity1Created.getID()),
|
||||
RedisTestEntity.loader(viewerContext2).enforcing().loadByIDAsync(entity1Created.getID()),
|
||||
RedisTestEntity.loader(viewerContext3)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', entity1Created.getField('name')),
|
||||
]);
|
||||
|
||||
expect(mgetSpy).toHaveBeenCalledTimes(1);
|
||||
expect(mgetSpy.mock.calls[0]).toHaveLength(2); // should dedupe the first two loads
|
||||
expect(entity1.getID()).toEqual(entity2.getID());
|
||||
expect(entity2.getID()).toEqual(nullthrows(entity3).getID());
|
||||
|
||||
const cacheKeyEntity1 = cacheKeyMaker('id', entity1Created.getID());
|
||||
const cachedJSON = await redis.get(cacheKeyEntity1);
|
||||
const cachedValue = JSON.parse(cachedJSON!);
|
||||
expect(cachedValue).toMatchObject({
|
||||
id: entity1.getID(),
|
||||
name: 'blah',
|
||||
});
|
||||
|
||||
const cacheKeyEntity1NameField = cacheKeyMaker('name', entity1Created.getField('name'));
|
||||
await RedisTestEntity.loader(viewerContext)
|
||||
.enforcing()
|
||||
.loadByFieldEqualingAsync('name', entity1Created.getField('name'));
|
||||
await expect(redis.get(cacheKeyEntity1NameField)).resolves.toEqual(cachedJSON);
|
||||
|
||||
// simulate non existent db fetch, should write negative result ('') to cache
|
||||
const nonExistentId = uuidv4();
|
||||
const entityNonExistentResult = await RedisTestEntity.loader(viewerContext).loadByIDAsync(
|
||||
nonExistentId
|
||||
);
|
||||
expect(entityNonExistentResult.ok).toBe(false);
|
||||
const cacheKeyNonExistent = cacheKeyMaker('id', nonExistentId);
|
||||
const nonExistentCachedValue = await redis.get(cacheKeyNonExistent);
|
||||
expect(nonExistentCachedValue).toEqual('');
|
||||
// load again through entities framework to ensure it reads negative result
|
||||
const entityNonExistentResult2 = await RedisTestEntity.loader(viewerContext).loadByIDAsync(
|
||||
nonExistentId
|
||||
);
|
||||
expect(entityNonExistentResult2.ok).toBe(false);
|
||||
|
||||
// invalidate from cache to ensure it invalidates correctly in both caches
|
||||
await RedisTestEntity.loader(viewerContext).invalidateFieldsAsync(entity1.getAllFields());
|
||||
await expect(redis.get(cacheKeyEntity1)).resolves.toBeNull();
|
||||
await expect(redis.get(cacheKeyEntity1NameField)).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
+5
-4
@@ -13,11 +13,12 @@ import { createRedisIntegrationTestEntityCompanionProvider } from '../testfixtur
|
||||
class TestViewerContext extends ViewerContext {}
|
||||
|
||||
describe(GenericRedisCacher, () => {
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let redisCacheAdapterContext: RedisCacheAdapterContext;
|
||||
|
||||
beforeAll(() => {
|
||||
redisCacheAdapterContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
@@ -33,10 +34,10 @@ describe(GenericRedisCacher, () => {
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await redisCacheAdapterContext.redisClient.flushdb();
|
||||
await redisClient.flushdb();
|
||||
});
|
||||
afterAll(async () => {
|
||||
redisCacheAdapterContext.redisClient.disconnect();
|
||||
redisClient.disconnect();
|
||||
});
|
||||
|
||||
it('has correct caching and loading behavior', async () => {
|
||||
@@ -62,7 +63,7 @@ describe(GenericRedisCacher, () => {
|
||||
]);
|
||||
await genericRedisCacher.cacheManyAsync(objectMap);
|
||||
|
||||
const cachedJSON = await redisCacheAdapterContext.redisClient.get(testKey);
|
||||
const cachedJSON = await redisClient.get(testKey);
|
||||
const cachedValue = JSON.parse(cachedJSON!);
|
||||
expect(cachedValue).toMatchObject({
|
||||
id: entity1Created.getID(),
|
||||
|
||||
+7
-12
@@ -11,11 +11,12 @@ import { createRedisIntegrationTestEntityCompanionProvider } from '../testfixtur
|
||||
class TestViewerContext extends ViewerContext {}
|
||||
|
||||
describe(RedisCacheAdapter, () => {
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let redisCacheAdapterContext: RedisCacheAdapterContext;
|
||||
|
||||
beforeAll(() => {
|
||||
redisCacheAdapterContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
@@ -31,10 +32,10 @@ describe(RedisCacheAdapter, () => {
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await redisCacheAdapterContext.redisClient.flushdb();
|
||||
await redisClient.flushdb();
|
||||
});
|
||||
afterAll(async () => {
|
||||
redisCacheAdapterContext.redisClient.disconnect();
|
||||
redisClient.disconnect();
|
||||
});
|
||||
|
||||
it('has correct caching behavior', async () => {
|
||||
@@ -56,9 +57,7 @@ describe(RedisCacheAdapter, () => {
|
||||
.enforcing()
|
||||
.loadByIDAsync(entity1Created.getID());
|
||||
|
||||
const cachedJSON = await redisCacheAdapterContext.redisClient.get(
|
||||
cacheKeyMaker('id', entity1.getID())
|
||||
);
|
||||
const cachedJSON = await redisClient.get(cacheKeyMaker('id', entity1.getID()));
|
||||
const cachedValue = JSON.parse(cachedJSON!);
|
||||
expect(cachedValue).toMatchObject({
|
||||
id: entity1.getID(),
|
||||
@@ -73,9 +72,7 @@ describe(RedisCacheAdapter, () => {
|
||||
);
|
||||
expect(entityNonExistentResult.ok).toBe(false);
|
||||
|
||||
const nonExistentCachedValue = await redisCacheAdapterContext.redisClient.get(
|
||||
cacheKeyMaker('id', nonExistentId)
|
||||
);
|
||||
const nonExistentCachedValue = await redisClient.get(cacheKeyMaker('id', nonExistentId));
|
||||
expect(nonExistentCachedValue).toEqual('');
|
||||
|
||||
// load again through entities framework to ensure it reads negative result
|
||||
@@ -86,9 +83,7 @@ describe(RedisCacheAdapter, () => {
|
||||
|
||||
// invalidate from cache to ensure it invalidates correctly
|
||||
await RedisTestEntity.loader(viewerContext).invalidateFieldsAsync(entity1.getAllFields());
|
||||
const cachedValueNull = await redisCacheAdapterContext.redisClient.get(
|
||||
cacheKeyMaker('id', entity1.getID())
|
||||
);
|
||||
const cachedValueNull = await redisClient.get(cacheKeyMaker('id', entity1.getID()));
|
||||
expect(cachedValueNull).toBe(null);
|
||||
});
|
||||
|
||||
|
||||
@@ -9,11 +9,12 @@ import { createRedisIntegrationTestEntityCompanionProvider } from '../testfixtur
|
||||
class TestViewerContext extends ViewerContext {}
|
||||
|
||||
describe(RedisCacheAdapter, () => {
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let redisCacheAdapterContext: RedisCacheAdapterContext;
|
||||
|
||||
beforeAll(() => {
|
||||
redisCacheAdapterContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
@@ -29,11 +30,11 @@ describe(RedisCacheAdapter, () => {
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await redisCacheAdapterContext.redisClient.flushdb();
|
||||
await redisClient.flushdb();
|
||||
});
|
||||
|
||||
it('throws when redis is disconnected', async () => {
|
||||
redisCacheAdapterContext.redisClient.disconnect();
|
||||
redisClient.disconnect();
|
||||
|
||||
const vc1 = new TestViewerContext(
|
||||
createRedisIntegrationTestEntityCompanionProvider(redisCacheAdapterContext)
|
||||
|
||||
+4
-1
@@ -9,6 +9,9 @@ import {
|
||||
import { RedisCacheAdapterContext } from '../RedisCacheAdapter';
|
||||
import RedisCacheAdapterProvider from '../RedisCacheAdapterProvider';
|
||||
|
||||
// share across all in calls in test to simulate postgres
|
||||
const adapterProvider = new StubDatabaseAdapterProvider();
|
||||
|
||||
export const createRedisIntegrationTestEntityCompanionProvider = (
|
||||
redisCacheAdapterContext: RedisCacheAdapterContext,
|
||||
metricsAdapter: IEntityMetricsAdapter = new NoOpEntityMetricsAdapter()
|
||||
@@ -19,7 +22,7 @@ export const createRedisIntegrationTestEntityCompanionProvider = (
|
||||
[
|
||||
'postgres',
|
||||
{
|
||||
adapterProvider: new StubDatabaseAdapterProvider(),
|
||||
adapterProvider,
|
||||
queryContextProvider: StubQueryContextProvider,
|
||||
},
|
||||
],
|
||||
|
||||
@@ -3,6 +3,42 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-database-adapter-knex
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add BigIntField ([#193](https://github.com/expo/entity/issues/193)) ([acbad82](https://github.com/expo/entity/commit/acbad826a37bb5a054b4dcf9be91d11aa5f7f29a))
|
||||
* nested transactions ([#194](https://github.com/expo/entity/issues/194)) ([a77b914](https://github.com/expo/entity/commit/a77b914ad6dc018d1e309c9caf4971088a553ecf))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-database-adapter-knex",
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "Knex database adapter for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -30,10 +30,10 @@
|
||||
"@expo/entity": "*"
|
||||
},
|
||||
"dependencies": {
|
||||
"knex": "^1.0.2"
|
||||
"knex": "^2.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.27.0",
|
||||
"@expo/entity": "^0.31.1",
|
||||
"pg": "^8.7.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { EntityFieldDefinition } from '@expo/entity';
|
||||
|
||||
/**
|
||||
* EntityFieldDefinition for a Postres column with a JS JSON array type.
|
||||
*/
|
||||
export class JSONArrayField extends EntityFieldDefinition<any[]> {
|
||||
protected validateInputValueInternal(value: any[]): boolean {
|
||||
return Array.isArray(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* EntityFieldDefinition for a Postgres column that may be a JS JSON array type.
|
||||
* Does not do any validation.
|
||||
*/
|
||||
export class MaybeJSONArrayField extends EntityFieldDefinition<any | any[]> {
|
||||
protected validateInputValueInternal(_value: any): boolean {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* EntityFieldDefinition for a Postgres BIGINT column.
|
||||
*/
|
||||
export class BigIntField extends EntityFieldDefinition<string> {
|
||||
protected validateInputValueInternal(value: string): boolean {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,6 @@ import {
|
||||
EntityDatabaseAdapter,
|
||||
FieldTransformerMap,
|
||||
FieldTransformer,
|
||||
JSONArrayField,
|
||||
MaybeJSONArrayField,
|
||||
TableQuerySelectionModifiers,
|
||||
TableFieldSingleValueEqualityCondition,
|
||||
TableFieldMultiValueEqualityCondition,
|
||||
@@ -11,6 +9,7 @@ import {
|
||||
} from '@expo/entity';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
import { JSONArrayField, MaybeJSONArrayField } from './EntityFields';
|
||||
import wrapNativePostgresCallAsync from './errors/wrapNativePostgresCallAsync';
|
||||
|
||||
export default class PostgresEntityDatabaseAdapter<TFields> extends EntityDatabaseAdapter<TFields> {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { EntityQueryContextProvider } from '@expo/entity';
|
||||
import {
|
||||
EntityQueryContextProvider,
|
||||
TransactionConfig,
|
||||
TransactionIsolationLevel,
|
||||
} from '@expo/entity';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
/**
|
||||
@@ -13,9 +17,44 @@ export default class PostgresEntityQueryContextProvider extends EntityQueryConte
|
||||
return this.knexInstance;
|
||||
}
|
||||
|
||||
protected createTransactionRunner<T>(): (
|
||||
transactionScope: (trx: any) => Promise<T>
|
||||
) => Promise<T> {
|
||||
return (transactionScope) => this.knexInstance.transaction(transactionScope);
|
||||
protected createTransactionRunner<T>(
|
||||
transactionConfig?: TransactionConfig
|
||||
): (transactionScope: (trx: any) => Promise<T>) => Promise<T> {
|
||||
return (transactionScope) =>
|
||||
this.knexInstance.transaction(
|
||||
transactionScope,
|
||||
transactionConfig
|
||||
? PostgresEntityQueryContextProvider.convertTransactionConfig(transactionConfig)
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
|
||||
protected createNestedTransactionRunner<T>(
|
||||
outerQueryInterface: any
|
||||
): (transactionScope: (queryInterface: any) => Promise<T>) => Promise<T> {
|
||||
return (transactionScope) => (outerQueryInterface as Knex).transaction(transactionScope);
|
||||
}
|
||||
|
||||
private static convertTransactionConfig(
|
||||
transactionConfig: TransactionConfig
|
||||
): Knex.TransactionConfig {
|
||||
const convertIsolationLevel = (
|
||||
isolationLevel: TransactionIsolationLevel
|
||||
): Knex.IsolationLevels => {
|
||||
switch (isolationLevel) {
|
||||
case TransactionIsolationLevel.READ_COMMITTED:
|
||||
return 'read committed';
|
||||
case TransactionIsolationLevel.REPEATABLE_READ:
|
||||
return 'repeatable read';
|
||||
case TransactionIsolationLevel.SERIALIZABLE:
|
||||
return 'serializable';
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
...(transactionConfig.isolationLevel
|
||||
? { isolationLevel: convertIsolationLevel(transactionConfig.isolationLevel) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
+85
-1
@@ -3,6 +3,7 @@ import {
|
||||
createUnitTestEntityCompanionProvider,
|
||||
enforceResultsAsync,
|
||||
ViewerContext,
|
||||
TransactionIsolationLevel,
|
||||
} from '@expo/entity';
|
||||
import { enforceAsyncResult } from '@expo/results';
|
||||
import { knex, Knex } from 'knex';
|
||||
@@ -111,6 +112,44 @@ describe('postgres entity integration', () => {
|
||||
expect(entities).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('passes transaction config into transactions', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
const firstEntity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1).setField('name', 'hello').createAsync()
|
||||
);
|
||||
|
||||
const loadAndUpdateAsync = async (newName: string): Promise<{ error?: Error }> => {
|
||||
try {
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync(
|
||||
'postgres',
|
||||
async (queryContext) => {
|
||||
const entity = await PostgresTestEntity.loader(vc1, queryContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(firstEntity.getID());
|
||||
await PostgresTestEntity.updater(entity, queryContext)
|
||||
.setField('name', newName)
|
||||
.enforceUpdateAsync();
|
||||
},
|
||||
{ isolationLevel: TransactionIsolationLevel.SERIALIZABLE }
|
||||
);
|
||||
return {};
|
||||
} catch (e) {
|
||||
return { error: e as Error };
|
||||
}
|
||||
};
|
||||
|
||||
// do some parallel updates to trigger serializable error in at least some of them
|
||||
const results = await Promise.all([
|
||||
loadAndUpdateAsync('hello2'),
|
||||
loadAndUpdateAsync('hello3'),
|
||||
loadAndUpdateAsync('hello4'),
|
||||
loadAndUpdateAsync('hello5'),
|
||||
]);
|
||||
|
||||
expect(results.filter((r) => (r.error as any)?.cause?.code === '40001').length > 0).toBe(true);
|
||||
});
|
||||
|
||||
describe('JSON fields', () => {
|
||||
it('supports both types of array fields', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
@@ -157,6 +196,27 @@ describe('postgres entity integration', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('BIGINT fields', () => {
|
||||
it('supports BIGINT fields', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
let entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.creator(vc1).setField('bigintField', '72057594037928038').createAsync()
|
||||
);
|
||||
expect(entity.getField('bigintField')).toEqual('72057594037928038');
|
||||
|
||||
entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.updater(entity).setField('bigintField', '10').updateAsync()
|
||||
);
|
||||
expect(entity.getField('bigintField')).toEqual('10');
|
||||
|
||||
entity = await enforceAsyncResult(
|
||||
PostgresTestEntity.updater(entity).setField('bigintField', '-10').updateAsync()
|
||||
);
|
||||
expect(entity.getField('bigintField')).toEqual('-10');
|
||||
});
|
||||
});
|
||||
|
||||
describe('conjunction field equality loading', () => {
|
||||
it('supports single fieldValue and multiple fieldValues', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
@@ -615,6 +675,7 @@ describe('postgres entity integration', () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
let preCommitCallCount = 0;
|
||||
let preCommitInnerCallCount = 0;
|
||||
let postCommitCallCount = 0;
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync('postgres', async (queryContext) => {
|
||||
@@ -624,6 +685,28 @@ describe('postgres entity integration', () => {
|
||||
queryContext.appendPreCommitCallback(async () => {
|
||||
preCommitCallCount++;
|
||||
}, 0);
|
||||
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
innerQueryContext.appendPostCommitCallback(async () => {
|
||||
postCommitCallCount++;
|
||||
});
|
||||
innerQueryContext.appendPreCommitCallback(async () => {
|
||||
preCommitInnerCallCount++;
|
||||
}, 0);
|
||||
});
|
||||
|
||||
// this one throws so its post commit shouldn't execute
|
||||
try {
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
innerQueryContext.appendPostCommitCallback(async () => {
|
||||
postCommitCallCount++;
|
||||
});
|
||||
innerQueryContext.appendPreCommitCallback(async () => {
|
||||
preCommitInnerCallCount++;
|
||||
throw Error('wat');
|
||||
}, 0);
|
||||
});
|
||||
} catch {}
|
||||
});
|
||||
|
||||
await expect(
|
||||
@@ -639,7 +722,8 @@ describe('postgres entity integration', () => {
|
||||
).rejects.toThrowError('wat');
|
||||
|
||||
expect(preCommitCallCount).toBe(2);
|
||||
expect(postCommitCallCount).toBe(1);
|
||||
expect(preCommitInnerCallCount).toBe(2);
|
||||
expect(postCommitCallCount).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import { ViewerContext } from '@expo/entity';
|
||||
import { knex, Knex } from 'knex';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
import PostgresEntityQueryContextProvider from '../PostgresEntityQueryContextProvider';
|
||||
import PostgresUniqueTestEntity from '../testfixtures/PostgresUniqueTestEntity';
|
||||
import { createKnexIntegrationTestEntityCompanionProvider } from '../testfixtures/createKnexIntegrationTestEntityCompanionProvider';
|
||||
|
||||
describe(PostgresEntityQueryContextProvider, () => {
|
||||
let knexInstance: Knex;
|
||||
|
||||
beforeAll(() => {
|
||||
knexInstance = knex({
|
||||
client: 'pg',
|
||||
connection: {
|
||||
user: nullthrows(process.env['PGUSER']),
|
||||
password: nullthrows(process.env['PGPASSWORD']),
|
||||
host: 'localhost',
|
||||
port: parseInt(nullthrows(process.env['PGPORT']), 10),
|
||||
database: nullthrows(process.env['PGDATABASE']),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await PostgresUniqueTestEntity.createOrTruncatePostgresTable(knexInstance);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await PostgresUniqueTestEntity.dropPostgresTable(knexInstance);
|
||||
await knexInstance.destroy();
|
||||
});
|
||||
|
||||
it('supports nested transactions', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
await PostgresUniqueTestEntity.creator(vc1).setField('name', 'unique').enforceCreateAsync();
|
||||
|
||||
const id = (
|
||||
await PostgresUniqueTestEntity.creator(vc1).setField('name', 'wat').enforceCreateAsync()
|
||||
).getID();
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync('postgres', async (queryContext) => {
|
||||
const entity = await PostgresUniqueTestEntity.loader(vc1, queryContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(id);
|
||||
await PostgresUniqueTestEntity.updater(entity, queryContext)
|
||||
.setField('name', 'wat2')
|
||||
.enforceUpdateAsync();
|
||||
|
||||
// ensure the outer transaction is not aborted due to postgres error in inner transaction,
|
||||
// in this case the error triggered is a unique constraint violation
|
||||
try {
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
const entity = await PostgresUniqueTestEntity.loader(vc1, innerQueryContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(id);
|
||||
await PostgresUniqueTestEntity.updater(entity, innerQueryContext)
|
||||
.setField('name', 'unique')
|
||||
.enforceUpdateAsync();
|
||||
});
|
||||
} catch {}
|
||||
|
||||
const entity2 = await PostgresUniqueTestEntity.loader(vc1, queryContext)
|
||||
.enforcing()
|
||||
.loadByIDAsync(id);
|
||||
await PostgresUniqueTestEntity.updater(entity2, queryContext)
|
||||
.setField('name', 'wat3')
|
||||
.enforceUpdateAsync();
|
||||
});
|
||||
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).enforcing().loadByIDAsync(id);
|
||||
expect(entityLoaded.getField('name')).toEqual('wat3');
|
||||
});
|
||||
|
||||
it('supports multi-nested transactions', async () => {
|
||||
const vc1 = new ViewerContext(createKnexIntegrationTestEntityCompanionProvider(knexInstance));
|
||||
|
||||
const id = (
|
||||
await PostgresUniqueTestEntity.creator(vc1).setField('name', 'wat').enforceCreateAsync()
|
||||
).getID();
|
||||
|
||||
await vc1.runInTransactionForDatabaseAdaptorFlavorAsync('postgres', async (queryContext) => {
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
await innerQueryContext.runInNestedTransactionAsync(async (innerQueryContex2) => {
|
||||
await innerQueryContex2.runInNestedTransactionAsync(async (innerQueryContex3) => {
|
||||
const entity = await PostgresUniqueTestEntity.loader(vc1, innerQueryContex3)
|
||||
.enforcing()
|
||||
.loadByIDAsync(id);
|
||||
await PostgresUniqueTestEntity.updater(entity, innerQueryContex3)
|
||||
.setField('name', 'wat3')
|
||||
.enforceUpdateAsync();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const entityLoaded = await PostgresUniqueTestEntity.loader(vc1).enforcing().loadByIDAsync(id);
|
||||
expect(entityLoaded.getField('name')).toEqual('wat3');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describeFieldTestCase } from '@expo/entity';
|
||||
|
||||
import { BigIntField, JSONArrayField, MaybeJSONArrayField } from '../EntityFields';
|
||||
|
||||
describeFieldTestCase(
|
||||
new JSONArrayField({ columnName: 'wat' }),
|
||||
[[[1, 2]] as any, [['hello']] as any],
|
||||
[1, 'hello']
|
||||
);
|
||||
describeFieldTestCase(
|
||||
new MaybeJSONArrayField({ columnName: 'wat' }),
|
||||
[1, 'hello', [['hello']]],
|
||||
[]
|
||||
);
|
||||
describeFieldTestCase(
|
||||
new BigIntField({ columnName: 'wat' }),
|
||||
['123457682149816498126412896', '123', '-1', '-124147812641876482716841'],
|
||||
[1, false, -1, 1e6, {}]
|
||||
);
|
||||
@@ -7,3 +7,4 @@
|
||||
export { default as PostgresEntityDatabaseAdapter } from './PostgresEntityDatabaseAdapter';
|
||||
export { default as PostgresEntityDatabaseAdapterProvider } from './PostgresEntityDatabaseAdapterProvider';
|
||||
export { default as PostgresEntityQueryContextProvider } from './PostgresEntityQueryContextProvider';
|
||||
export * from './EntityFields';
|
||||
@@ -6,16 +6,16 @@ import {
|
||||
StringField,
|
||||
BooleanField,
|
||||
StringArrayField,
|
||||
JSONArrayField,
|
||||
JSONObjectField,
|
||||
DateField,
|
||||
MaybeJSONArrayField,
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
} from '@expo/entity';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
import { BigIntField, JSONArrayField, MaybeJSONArrayField } from '../EntityFields';
|
||||
|
||||
type PostgresTestEntityFields = {
|
||||
id: string;
|
||||
name: string | null;
|
||||
@@ -28,6 +28,7 @@ type PostgresTestEntityFields = {
|
||||
} | null;
|
||||
dateField: Date | null;
|
||||
maybeJsonArrayField: string[] | { hello: string } | null;
|
||||
bigintField: string | null;
|
||||
};
|
||||
|
||||
export default class PostgresTestEntity extends Entity<
|
||||
@@ -46,13 +47,11 @@ export default class PostgresTestEntity extends Entity<
|
||||
}
|
||||
|
||||
public static async createOrTruncatePostgresTable(knex: Knex): Promise<void> {
|
||||
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
|
||||
|
||||
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
|
||||
const hasTable = await knex.schema.hasTable(tableName);
|
||||
if (!hasTable) {
|
||||
await knex.schema.createTable(tableName, (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
table.string('name');
|
||||
table.boolean('has_a_dog');
|
||||
table.boolean('has_a_cat');
|
||||
@@ -61,6 +60,7 @@ export default class PostgresTestEntity extends Entity<
|
||||
table.jsonb('json_object_field');
|
||||
table.dateTime('date_field', { useTz: true });
|
||||
table.jsonb('maybe_json_array_field');
|
||||
table.bigint('bigint_field');
|
||||
});
|
||||
}
|
||||
await knex.into(tableName).truncate();
|
||||
@@ -147,6 +147,9 @@ export const postgresTestEntityConfiguration = new EntityConfiguration<PostgresT
|
||||
maybeJsonArrayField: new MaybeJSONArrayField({
|
||||
columnName: 'maybe_json_array_field',
|
||||
}),
|
||||
bigintField: new BigIntField({
|
||||
columnName: 'bigint_field',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
|
||||
@@ -35,13 +35,11 @@ export default class PostgresTriggerTestEntity extends Entity<
|
||||
}
|
||||
|
||||
public static async createOrTruncatePostgresTable(knex: Knex): Promise<void> {
|
||||
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
|
||||
|
||||
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
|
||||
const hasTable = await knex.schema.hasTable(tableName);
|
||||
if (!hasTable) {
|
||||
await knex.schema.createTable(tableName, (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
table.string('name');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import {
|
||||
AlwaysAllowPrivacyPolicyRule,
|
||||
EntityPrivacyPolicy,
|
||||
ViewerContext,
|
||||
UUIDField,
|
||||
StringField,
|
||||
EntityConfiguration,
|
||||
EntityCompanionDefinition,
|
||||
Entity,
|
||||
} from '@expo/entity';
|
||||
import { Knex } from 'knex';
|
||||
|
||||
type PostgresUniqueTestEntityFields = {
|
||||
id: string;
|
||||
name: string | null;
|
||||
};
|
||||
|
||||
export default class PostgresUniqueTestEntity extends Entity<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
ViewerContext
|
||||
> {
|
||||
static getCompanionDefinition(): EntityCompanionDefinition<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity,
|
||||
PostgresUniqueTestEntityPrivacyPolicy
|
||||
> {
|
||||
return postgresTestEntityCompanionDefinition;
|
||||
}
|
||||
|
||||
public static async createOrTruncatePostgresTable(knex: Knex): Promise<void> {
|
||||
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
|
||||
const hasTable = await knex.schema.hasTable(tableName);
|
||||
if (!hasTable) {
|
||||
await knex.schema.createTable(tableName, (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
table.string('name').unique();
|
||||
});
|
||||
}
|
||||
await knex.into(tableName).truncate();
|
||||
}
|
||||
|
||||
public static async dropPostgresTable(knex: Knex): Promise<void> {
|
||||
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
|
||||
const hasTable = await knex.schema.hasTable(tableName);
|
||||
if (hasTable) {
|
||||
await knex.schema.dropTable(tableName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class PostgresUniqueTestEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
> {
|
||||
protected override readonly createRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
>(),
|
||||
];
|
||||
protected override readonly readRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
>(),
|
||||
];
|
||||
protected override readonly updateRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
>(),
|
||||
];
|
||||
protected override readonly deleteRules = [
|
||||
new AlwaysAllowPrivacyPolicyRule<
|
||||
PostgresUniqueTestEntityFields,
|
||||
string,
|
||||
ViewerContext,
|
||||
PostgresUniqueTestEntity
|
||||
>(),
|
||||
];
|
||||
}
|
||||
|
||||
export const postgresTestEntityConfiguration =
|
||||
new EntityConfiguration<PostgresUniqueTestEntityFields>({
|
||||
idField: 'id',
|
||||
tableName: 'postgres_test_entities',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
name: new StringField({
|
||||
columnName: 'name',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
|
||||
const postgresTestEntityCompanionDefinition = new EntityCompanionDefinition({
|
||||
entityClass: PostgresUniqueTestEntity,
|
||||
entityConfiguration: postgresTestEntityConfiguration,
|
||||
privacyPolicyClass: PostgresUniqueTestEntityPrivacyPolicy,
|
||||
});
|
||||
+1
-3
@@ -34,13 +34,11 @@ export default class PostgresValidatorTestEntity extends Entity<
|
||||
}
|
||||
|
||||
public static async createOrTruncatePostgresTable(knex: Knex): Promise<void> {
|
||||
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
|
||||
|
||||
const tableName = this.getCompanionDefinition().entityConfiguration.tableName;
|
||||
const hasTable = await knex.schema.hasTable(tableName);
|
||||
if (!hasTable) {
|
||||
await knex.schema.createTable(tableName, (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
table.string('name');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,6 +3,41 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* nested transactions ([#194](https://github.com/expo/entity/issues/194)) ([a77b914](https://github.com/expo/entity/commit/a77b914ad6dc018d1e309c9caf4971088a553ecf))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-example
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@expo/entity-example",
|
||||
"private": true,
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "An example integration of the @expo/entity framework",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
@@ -23,7 +23,7 @@
|
||||
"author": "Expo",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/entity": "^0.27.0",
|
||||
"@expo/entity": "^0.31.1",
|
||||
"apollo-server-koa": "^2.16.1",
|
||||
"graphql": "^15.3.0",
|
||||
"koa": "^2.13.0",
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { EntityQueryContextProvider } from '@expo/entity';
|
||||
import { EntityQueryContextProvider, TransactionConfig } from '@expo/entity';
|
||||
|
||||
export default class InMemoryQueryContextProvider extends EntityQueryContextProvider {
|
||||
protected getQueryInterface(): any {
|
||||
return {};
|
||||
}
|
||||
|
||||
protected createTransactionRunner<T>(): (
|
||||
transactionScope: (queryInterface: any) => Promise<T>
|
||||
) => Promise<T> {
|
||||
protected createTransactionRunner<T>(
|
||||
_transactionConfig?: TransactionConfig
|
||||
): (transactionScope: (queryInterface: any) => Promise<T>) => Promise<T> {
|
||||
return (transactionScope) => Promise.resolve(transactionScope({}));
|
||||
}
|
||||
|
||||
protected createNestedTransactionRunner<T>(
|
||||
_outerQueryInterface: any
|
||||
): (transactionScope: (queryInterface: any) => Promise<T>) => Promise<T> {
|
||||
return (transactionScope) => Promise.resolve(transactionScope({}));
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,27 @@ export default class NoteEntity extends Entity<NoteFields, string, ExampleViewer
|
||||
}
|
||||
}
|
||||
|
||||
const noteEntityConfiguration = new EntityConfiguration<NoteFields>({
|
||||
idField: 'id',
|
||||
tableName: 'notes',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
}),
|
||||
userID: new UUIDField({
|
||||
columnName: 'user_id',
|
||||
}),
|
||||
title: new StringField({
|
||||
columnName: 'title',
|
||||
}),
|
||||
body: new StringField({
|
||||
columnName: 'body',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
|
||||
/**
|
||||
* The companion provides configuration instructions to the Entity framework for this type
|
||||
* of entity. In some languages, this would be representable as "abstract" static members
|
||||
@@ -38,25 +59,6 @@ export default class NoteEntity extends Entity<NoteFields, string, ExampleViewer
|
||||
*/
|
||||
export const noteEntityCompanion = new EntityCompanionDefinition({
|
||||
entityClass: NoteEntity,
|
||||
entityConfiguration: new EntityConfiguration<NoteFields>({
|
||||
idField: 'id',
|
||||
tableName: 'notes',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
}),
|
||||
userID: new UUIDField({
|
||||
columnName: 'user_id',
|
||||
}),
|
||||
title: new StringField({
|
||||
columnName: 'title',
|
||||
}),
|
||||
body: new StringField({
|
||||
columnName: 'body',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
}),
|
||||
entityConfiguration: noteEntityConfiguration,
|
||||
privacyPolicyClass: NotePrivacyPolicy,
|
||||
});
|
||||
@@ -3,6 +3,41 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* change redis cache adapter to use redis-like interface ([#200](https://github.com/expo/entity/issues/200)) ([e381f5b](https://github.com/expo/entity/commit/e381f5b2acfc17dcade2cf6e8506fa1c1c255e73))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-full-integration-tests
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@expo/entity-full-integration-tests",
|
||||
"private": true,
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "Full redis and knex integration tests for the entity framework",
|
||||
"scripts": {
|
||||
"tsc": "tsc",
|
||||
@@ -27,8 +27,8 @@
|
||||
"@expo/entity-database-adapter-knex": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.27.0",
|
||||
"@expo/entity-cache-adapter-redis": "^0.27.0",
|
||||
"@expo/entity-database-adapter-knex": "^0.27.0"
|
||||
"@expo/entity": "^0.31.1",
|
||||
"@expo/entity-cache-adapter-redis": "^0.31.1",
|
||||
"@expo/entity-database-adapter-knex": "^0.31.1"
|
||||
}
|
||||
}
|
||||
+5
-6
@@ -81,10 +81,8 @@ const testEntityCompanion = new EntityCompanionDefinition({
|
||||
});
|
||||
|
||||
async function createOrTruncatePostgresTables(knex: Knex): Promise<void> {
|
||||
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
|
||||
|
||||
await knex.schema.createTable('testentities', (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
table.string('other_string').notNullable();
|
||||
table.string('third_string').notNullable();
|
||||
});
|
||||
@@ -99,6 +97,7 @@ async function dropPostgresTable(knex: Knex): Promise<void> {
|
||||
|
||||
describe('Entity cache inconsistency', () => {
|
||||
let knexInstance: Knex;
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let redisCacheAdapterContext: RedisCacheAdapterContext;
|
||||
|
||||
beforeAll(() => {
|
||||
@@ -113,7 +112,7 @@ describe('Entity cache inconsistency', () => {
|
||||
},
|
||||
});
|
||||
redisCacheAdapterContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
@@ -130,13 +129,13 @@ describe('Entity cache inconsistency', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
await createOrTruncatePostgresTables(knexInstance);
|
||||
await redisCacheAdapterContext.redisClient.flushdb();
|
||||
await redisClient.flushdb();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await dropPostgresTable(knexInstance);
|
||||
await knexInstance.destroy();
|
||||
redisCacheAdapterContext.redisClient.disconnect();
|
||||
redisClient.disconnect();
|
||||
});
|
||||
|
||||
test('lots of updates in long-ish running transactions', async () => {
|
||||
|
||||
+6
-7
@@ -10,15 +10,13 @@ import ChildEntity from './entities/ChildEntity';
|
||||
import ParentEntity from './entities/ParentEntity';
|
||||
|
||||
async function createOrTruncatePostgresTables(knex: Knex): Promise<void> {
|
||||
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
|
||||
|
||||
await knex.schema.createTable('parents', (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
});
|
||||
await knex.into('parents').truncate();
|
||||
|
||||
await knex.schema.createTable('children', (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
table.uuid('parent_id').references('id').inTable('parents').onDelete('cascade').unique();
|
||||
});
|
||||
await knex.into('children').truncate();
|
||||
@@ -35,6 +33,7 @@ async function dropPostgresTable(knex: Knex): Promise<void> {
|
||||
|
||||
describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
let knexInstance: Knex;
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let redisCacheAdapterContext: RedisCacheAdapterContext;
|
||||
|
||||
beforeAll(() => {
|
||||
@@ -49,7 +48,7 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
},
|
||||
});
|
||||
redisCacheAdapterContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
@@ -66,13 +65,13 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
await createOrTruncatePostgresTables(knexInstance);
|
||||
await redisCacheAdapterContext.redisClient.flushdb();
|
||||
await redisClient.flushdb();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await dropPostgresTable(knexInstance);
|
||||
await knexInstance.destroy();
|
||||
redisCacheAdapterContext.redisClient.disconnect();
|
||||
redisClient.disconnect();
|
||||
});
|
||||
|
||||
describe('EntityEdgeDeletionBehavior.INVALIDATE_CACHE', () => {
|
||||
|
||||
+9
-10
@@ -74,7 +74,7 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
const categoryEntityConfiguration = new EntityConfiguration<CategoryFields>({
|
||||
idField: 'id',
|
||||
tableName: categoriesTableName,
|
||||
getInboundEdges: () => [OtherEntity],
|
||||
getInboundEdges: async () => [OtherEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
@@ -84,7 +84,7 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
columnName: 'parent_other_id',
|
||||
cache: true,
|
||||
association: {
|
||||
getAssociatedEntityClass: () => OtherEntity,
|
||||
getAssociatedEntityClass: async () => OtherEntity,
|
||||
edgeDeletionBehavior,
|
||||
},
|
||||
}),
|
||||
@@ -102,7 +102,7 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
const otherEntityConfiguration = new EntityConfiguration<OtherFields>({
|
||||
idField: 'id',
|
||||
tableName: othersTableName,
|
||||
getInboundEdges: () => [CategoryEntity],
|
||||
getInboundEdges: async () => [CategoryEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
@@ -112,7 +112,7 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
columnName: 'parent_category_id',
|
||||
cache: true,
|
||||
association: {
|
||||
getAssociatedEntityClass: () => CategoryEntity,
|
||||
getAssociatedEntityClass: async () => CategoryEntity,
|
||||
edgeDeletionBehavior,
|
||||
},
|
||||
}),
|
||||
@@ -127,14 +127,12 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
privacyPolicyClass: PrivacyPolicy,
|
||||
});
|
||||
|
||||
await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); // for uuid_generate_v4()
|
||||
|
||||
await knex.schema.createTable(categoriesTableName, (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
});
|
||||
|
||||
await knex.schema.createTable(othersTableName, (table) => {
|
||||
table.uuid('id').defaultTo(knex.raw('uuid_generate_v4()')).primary();
|
||||
table.uuid('id').defaultTo(knex.raw('gen_random_uuid()')).primary();
|
||||
if (edgeDeletionBehavior === EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE_ONLY) {
|
||||
table
|
||||
.uuid('parent_category_id')
|
||||
@@ -178,6 +176,7 @@ const makeEntityClasses = async (knex: Knex, edgeDeletionBehavior: EntityEdgeDel
|
||||
};
|
||||
describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
let knexInstance: Knex;
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let redisCacheAdapterContext: RedisCacheAdapterContext;
|
||||
|
||||
beforeAll(() => {
|
||||
@@ -192,7 +191,7 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
},
|
||||
});
|
||||
redisCacheAdapterContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
redisClient,
|
||||
makeKeyFn(...parts: string[]): string {
|
||||
const delimiter = ':';
|
||||
const escapedParts = parts.map((part) =>
|
||||
@@ -209,7 +208,7 @@ describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => {
|
||||
|
||||
afterAll(async () => {
|
||||
await knexInstance.destroy();
|
||||
redisCacheAdapterContext.redisClient.disconnect();
|
||||
redisClient.disconnect();
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ const childEntityConfiguration = new EntityConfiguration<ChildFields>({
|
||||
columnName: 'parent_id',
|
||||
cache: true,
|
||||
association: {
|
||||
getAssociatedEntityClass: () => ParentEntity,
|
||||
getAssociatedEntityClass: async () => ParentEntity,
|
||||
edgeDeletionBehavior: EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE_ONLY,
|
||||
},
|
||||
}),
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ export default class ParentEntity extends Entity<ParentFields, string, ViewerCon
|
||||
const parentEntityConfiguration = new EntityConfiguration<ParentFields>({
|
||||
idField: 'id',
|
||||
tableName: 'parents',
|
||||
getInboundEdges: () => [ChildEntity],
|
||||
getInboundEdges: async () => [ChildEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
|
||||
@@ -3,6 +3,38 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-ip-address-field
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-ip-address-field",
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "IP address EntityField definitions for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -28,7 +28,7 @@
|
||||
"ip-address": "^8.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.27.0",
|
||||
"@expo/entity": "^0.31.1",
|
||||
"@types/jsbn": "^1.2.29"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -3,6 +3,38 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-local-memory
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-secondary-cache-local-memory",
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "Local memory secondary cache for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -31,8 +31,8 @@
|
||||
"@expo/entity-cache-adapter-local-memory": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.27.0",
|
||||
"@expo/entity-cache-adapter-local-memory": "^0.27.0",
|
||||
"@expo/entity": "^0.31.1",
|
||||
"@expo/entity-cache-adapter-local-memory": "^0.31.1",
|
||||
"nullthrows": "^1.1.1"
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,41 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* change redis cache adapter to use redis-like interface ([#200](https://github.com/expo/entity/issues/200)) ([e381f5b](https://github.com/expo/entity/commit/e381f5b2acfc17dcade2cf6e8506fa1c1c255e73))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity-secondary-cache-redis
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity-secondary-cache-redis",
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "Redis secondary cache for @expo/entity",
|
||||
"files": [
|
||||
"build",
|
||||
@@ -31,9 +31,9 @@
|
||||
"@expo/entity-cache-adapter-redis": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/entity": "^0.27.0",
|
||||
"@expo/entity-cache-adapter-redis": "^0.27.0",
|
||||
"ioredis": "^5.0.4",
|
||||
"@expo/entity": "^0.31.1",
|
||||
"@expo/entity-cache-adapter-redis": "^0.31.1",
|
||||
"ioredis": "^5.2.5",
|
||||
"nullthrows": "^1.1.1"
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -52,11 +52,12 @@ class TestSecondaryRedisCacheLoader extends EntitySecondaryCacheLoader<
|
||||
}
|
||||
|
||||
describe(RedisSecondaryEntityCache, () => {
|
||||
const redisClient = new Redis(new URL(process.env['REDIS_URL']!).toString());
|
||||
let redisCacheAdapterContext: RedisCacheAdapterContext;
|
||||
|
||||
beforeAll(() => {
|
||||
redisCacheAdapterContext = {
|
||||
redisClient: new Redis(new URL(process.env['REDIS_URL']!).toString()),
|
||||
redisClient,
|
||||
makeKeyFn(..._parts: string[]): string {
|
||||
throw new Error('should not be used by this test');
|
||||
},
|
||||
@@ -68,10 +69,10 @@ describe(RedisSecondaryEntityCache, () => {
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await redisCacheAdapterContext.redisClient.flushdb();
|
||||
await redisClient.flushdb();
|
||||
});
|
||||
afterAll(async () => {
|
||||
redisCacheAdapterContext.redisClient.disconnect();
|
||||
redisClient.disconnect();
|
||||
});
|
||||
|
||||
it('Loads through secondary loader, caches, and invalidates', async () => {
|
||||
|
||||
@@ -3,6 +3,42 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
# [0.31.0](https://github.com/expo/entity/compare/v0.30.0...v0.31.0) (2023-01-19)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.30.0](https://github.com/expo/entity/compare/v0.29.0...v0.30.0) (2022-12-23)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.29.0](https://github.com/expo/entity/compare/v0.28.0...v0.29.0) (2022-10-06)
|
||||
|
||||
**Note:** Version bump only for package @expo/entity
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.28.0](https://github.com/expo/entity/compare/v0.27.0...v0.28.0) (2022-09-13)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add BigIntField ([#193](https://github.com/expo/entity/issues/193)) ([acbad82](https://github.com/expo/entity/commit/acbad826a37bb5a054b4dcf9be91d11aa5f7f29a))
|
||||
* nested transactions ([#194](https://github.com/expo/entity/issues/194)) ([a77b914](https://github.com/expo/entity/commit/a77b914ad6dc018d1e309c9caf4971088a553ecf))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [0.27.0](https://github.com/expo/entity/compare/v0.26.1...v0.27.0) (2022-08-09)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/entity",
|
||||
"version": "0.27.0",
|
||||
"version": "0.31.1",
|
||||
"description": "A privacy-first data model",
|
||||
"files": [
|
||||
"build",
|
||||
|
||||
@@ -114,6 +114,22 @@ export default class EnforcingEntityLoader<
|
||||
return mapMap(entityResults, (result) => result.enforceValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforcing version of entity loader method by the same name.
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view one or more of the returned entities
|
||||
*/
|
||||
async loadFirstByFieldEqualityConjunctionAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
fieldEqualityOperands: FieldEqualityCondition<TFields, N>[],
|
||||
querySelectionModifiers: Omit<QuerySelectionModifiers<TFields>, 'limit'> &
|
||||
Required<Pick<QuerySelectionModifiers<TFields>, 'orderBy'>>
|
||||
): Promise<TEntity | null> {
|
||||
const entityResult = await this.entityLoader.loadFirstByFieldEqualityConjunctionAsync(
|
||||
fieldEqualityOperands,
|
||||
querySelectionModifiers
|
||||
);
|
||||
return entityResult ? entityResult.enforceValue() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforcing version of entity loader method by the same name.
|
||||
* @throws EntityNotAuthorizedError when viewer is not authorized to view one or more of the returned entities
|
||||
|
||||
@@ -13,7 +13,7 @@ export default class EntityConfiguration<TFields> {
|
||||
readonly cacheableKeys: ReadonlySet<keyof TFields>;
|
||||
readonly cacheKeyVersion: number;
|
||||
|
||||
readonly getInboundEdges: () => IEntityClass<any, any, any, any, any, any>[];
|
||||
readonly getInboundEdges: () => Promise<IEntityClass<any, any, any, any, any, any>[]>;
|
||||
readonly schema: ReadonlyMap<keyof TFields, EntityFieldDefinition<any>>;
|
||||
readonly entityToDBFieldsKeyMapping: ReadonlyMap<keyof TFields, string>;
|
||||
readonly dbToEntityFieldsKeyMapping: ReadonlyMap<string, keyof TFields>;
|
||||
@@ -25,7 +25,7 @@ export default class EntityConfiguration<TFields> {
|
||||
idField,
|
||||
tableName,
|
||||
schema,
|
||||
getInboundEdges = () => [],
|
||||
getInboundEdges = async () => [],
|
||||
cacheKeyVersion = 0,
|
||||
databaseAdapterFlavor,
|
||||
cacheAdapterFlavor,
|
||||
@@ -48,7 +48,7 @@ export default class EntityConfiguration<TFields> {
|
||||
/**
|
||||
* List of other entity types that reference this type in EntityFieldDefinition associations.
|
||||
*/
|
||||
getInboundEdges?: () => IEntityClass<any, any, any, any, any, any>[];
|
||||
getInboundEdges?: () => Promise<IEntityClass<any, any, any, any, any, any>[]>;
|
||||
|
||||
/**
|
||||
* Cache key version for this entity type. Should be bumped when a field is added to, removed from, or changed
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
FieldTransformerMap,
|
||||
} from './internal/EntityFieldTransformationUtils';
|
||||
|
||||
/**
|
||||
* Equality operand that is used for selecting entities with a field with a single value.
|
||||
*/
|
||||
export interface SingleValueFieldEqualityCondition<
|
||||
TFields,
|
||||
N extends keyof TFields = keyof TFields
|
||||
@@ -15,6 +18,9 @@ export interface SingleValueFieldEqualityCondition<
|
||||
fieldValue: TFields[N];
|
||||
}
|
||||
|
||||
/**
|
||||
* Equality operand that is used for selecting entities with a field matching one of multiple values.
|
||||
*/
|
||||
export interface MultiValueFieldEqualityCondition<
|
||||
TFields,
|
||||
N extends keyof TFields = keyof TFields
|
||||
@@ -23,6 +29,10 @@ export interface MultiValueFieldEqualityCondition<
|
||||
fieldValues: readonly TFields[N][];
|
||||
}
|
||||
|
||||
/**
|
||||
* A single equality operand for use in a selection clause.
|
||||
* See EntityLoader.loadManyByFieldEqualityConjunctionAsync documentation for examples.
|
||||
*/
|
||||
export type FieldEqualityCondition<TFields, N extends keyof TFields = keyof TFields> =
|
||||
| SingleValueFieldEqualityCondition<TFields, N>
|
||||
| MultiValueFieldEqualityCondition<TFields, N>;
|
||||
|
||||
@@ -61,13 +61,15 @@ export interface EntityAssociationDefinition<
|
||||
/**
|
||||
* Class of entity on the other end of this edge.
|
||||
*/
|
||||
getAssociatedEntityClass: () => IEntityClass<
|
||||
TAssociatedFields,
|
||||
TAssociatedID,
|
||||
TViewerContext,
|
||||
TAssociatedEntity,
|
||||
TAssociatedPrivacyPolicy,
|
||||
TAssociatedSelectedFields
|
||||
getAssociatedEntityClass: () => Promise<
|
||||
IEntityClass<
|
||||
TAssociatedFields,
|
||||
TAssociatedID,
|
||||
TViewerContext,
|
||||
TAssociatedEntity,
|
||||
TAssociatedPrivacyPolicy,
|
||||
TAssociatedSelectedFields
|
||||
>
|
||||
>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -86,22 +86,3 @@ export class EnumField extends EntityFieldDefinition<string | number> {
|
||||
return typeof value === 'number' || typeof value === 'string';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* EntityFieldDefinition for a column with a JS JSON array type.
|
||||
*/
|
||||
export class JSONArrayField extends EntityFieldDefinition<any[]> {
|
||||
protected validateInputValueInternal(value: any[]): boolean {
|
||||
return Array.isArray(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* EntityFieldDefinition for a column that may be a JS JSON array type.
|
||||
* Does not do any validation.
|
||||
*/
|
||||
export class MaybeJSONArrayField extends EntityFieldDefinition<any | any[]> {
|
||||
protected validateInputValueInternal(_value: any): boolean {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -183,16 +183,42 @@ export default class EntityLoader<
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads many entities matching the conjunction of WHERE clauses constructed from specified operands.
|
||||
* Loads the first entity matching the selection constructed from the conjunction of specified
|
||||
* operands, or null if no matching entity exists. Entities loaded using this method are not
|
||||
* batched or cached.
|
||||
*
|
||||
* This is a convenience method for {@link loadManyByFieldEqualityConjunctionAsync}. However, the
|
||||
* `orderBy` option must be specified to define what "first" means. If ordering doesn't matter,
|
||||
* explicitly pass in an empty array.
|
||||
*
|
||||
* @param fieldEqualityOperands - list of field equality selection operand specifications
|
||||
* @param querySelectionModifiers - orderBy and optional offset for the query
|
||||
* @returns the first entity results that matches the query, where result error can be
|
||||
* UnauthorizedError
|
||||
*/
|
||||
async loadFirstByFieldEqualityConjunctionAsync<N extends keyof Pick<TFields, TSelectedFields>>(
|
||||
fieldEqualityOperands: FieldEqualityCondition<TFields, N>[],
|
||||
querySelectionModifiers: Omit<QuerySelectionModifiers<TFields>, 'limit'> &
|
||||
Required<Pick<QuerySelectionModifiers<TFields>, 'orderBy'>>
|
||||
): Promise<Result<TEntity> | null> {
|
||||
const results = await this.loadManyByFieldEqualityConjunctionAsync(fieldEqualityOperands, {
|
||||
...querySelectionModifiers,
|
||||
limit: 1,
|
||||
});
|
||||
return results[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads many entities matching the selection constructed from the conjunction of specified operands.
|
||||
* Entities loaded using this method are not batched or cached.
|
||||
*
|
||||
* @example
|
||||
* fieldEqualityOperands:
|
||||
* `[{fieldName: 'hello', fieldValue: 1}, {fieldName: 'world', fieldValues: [2, 3]}]`
|
||||
* Entities returned:
|
||||
* Entities returned with a SQL EntityDatabaseAdapter:
|
||||
* `WHERE hello = 1 AND world = ANY({2, 3})`
|
||||
*
|
||||
* @param fieldEqualityOperands - list of field equality WHERE clause operand specifications
|
||||
* @param fieldEqualityOperands - list of field equality selection operand specifications
|
||||
* @param querySelectionModifiers - limit, offset, and orderBy for the query
|
||||
* @returns array of entity results that match the query, where result error can be UnauthorizedError
|
||||
*/
|
||||
|
||||
@@ -45,7 +45,7 @@ export default interface EntityMutationTriggerConfiguration<
|
||||
*/
|
||||
beforeAll?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
|
||||
/**
|
||||
* Trigger set that runs within the transaction but before the entity is created in, updated in, or deleted from
|
||||
* Trigger set that runs within the transaction but after the entity is created in, updated in, or deleted from
|
||||
* the database and the cache is invalidated.
|
||||
*/
|
||||
afterAll?: EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[];
|
||||
|
||||
@@ -734,7 +734,7 @@ export class DeleteMutator<
|
||||
TSelectedFields
|
||||
>;
|
||||
const entityConfiguration = companionDefinition.entityConfiguration;
|
||||
const inboundEdges = entityConfiguration.getInboundEdges();
|
||||
const inboundEdges = await entityConfiguration.getInboundEdges();
|
||||
await Promise.all(
|
||||
inboundEdges.map(async (entityClass) => {
|
||||
return await mapMapAsync(
|
||||
@@ -745,9 +745,9 @@ export class DeleteMutator<
|
||||
return;
|
||||
}
|
||||
|
||||
const associatedConfiguration = association
|
||||
.getAssociatedEntityClass()
|
||||
.getCompanionDefinition().entityConfiguration;
|
||||
const associatedConfiguration = (
|
||||
await association.getAssociatedEntityClass()
|
||||
).getCompanionDefinition().entityConfiguration;
|
||||
if (associatedConfiguration !== entityConfiguration) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,16 @@ export type PreCommitCallback = (
|
||||
...args: any
|
||||
) => Promise<any>;
|
||||
|
||||
export enum TransactionIsolationLevel {
|
||||
READ_COMMITTED = 'READ_COMMITTED',
|
||||
REPEATABLE_READ = 'REPEATABLE_READ',
|
||||
SERIALIZABLE = 'SERIALIZABLE',
|
||||
}
|
||||
|
||||
export type TransactionConfig = {
|
||||
isolationLevel?: TransactionIsolationLevel;
|
||||
};
|
||||
|
||||
/**
|
||||
* Entity framework representation of transactional and non-transactional database
|
||||
* query execution units.
|
||||
@@ -25,7 +35,8 @@ export abstract class EntityQueryContext {
|
||||
}
|
||||
|
||||
abstract runInTransactionIfNotInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>,
|
||||
transactionConfig?: TransactionConfig
|
||||
): Promise<T>;
|
||||
}
|
||||
|
||||
@@ -48,9 +59,13 @@ export class EntityNonTransactionalQueryContext extends EntityQueryContext {
|
||||
}
|
||||
|
||||
async runInTransactionIfNotInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>,
|
||||
transactionConfig?: TransactionConfig
|
||||
): Promise<T> {
|
||||
return await this.entityQueryContextProvider.runInTransactionAsync(transactionScope);
|
||||
return await this.entityQueryContextProvider.runInTransactionAsync(
|
||||
transactionScope,
|
||||
transactionConfig
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +80,13 @@ export class EntityTransactionalQueryContext extends EntityQueryContext {
|
||||
|
||||
private readonly preCommitCallbacks: { callback: PreCommitCallback; order: number }[] = [];
|
||||
|
||||
constructor(
|
||||
queryInterface: any,
|
||||
private readonly entityQueryContextProvider: EntityQueryContextProvider
|
||||
) {
|
||||
super(queryInterface);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a pre-commit callback. These will be run within the transaction right before it is
|
||||
* committed, and will be run in the order specified. Ordering of callbacks scheduled with the
|
||||
@@ -125,8 +147,66 @@ export class EntityTransactionalQueryContext extends EntityQueryContext {
|
||||
}
|
||||
|
||||
async runInTransactionIfNotInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>,
|
||||
transactionConfig?: TransactionConfig
|
||||
): Promise<T> {
|
||||
assert(
|
||||
transactionConfig === undefined,
|
||||
'Should not pass transactionConfig to a nested transaction'
|
||||
);
|
||||
return await transactionScope(this);
|
||||
}
|
||||
|
||||
async runInNestedTransactionAsync<T>(
|
||||
transactionScope: (innerQueryContext: EntityTransactionalQueryContext) => Promise<T>
|
||||
): Promise<T> {
|
||||
return await this.entityQueryContextProvider.runInNestedTransactionAsync(
|
||||
this,
|
||||
transactionScope
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity framework representation of a nested transactional query execution unit. When supplied
|
||||
* to EntityMutator and EntityLoader methods, those methods and their
|
||||
* dependent triggers and validators will run within the nested transaction.
|
||||
*
|
||||
* This exists to forward post-commit callbacks to the parent query context.
|
||||
*/
|
||||
export class EntityNestedTransactionalQueryContext extends EntityTransactionalQueryContext {
|
||||
private readonly postCommitInvalidationCallbacksToTransfer: PostCommitCallback[] = [];
|
||||
private readonly postCommitCallbacksToTransfer: PostCommitCallback[] = [];
|
||||
|
||||
constructor(
|
||||
queryInterface: any,
|
||||
private readonly parentQueryContext: EntityTransactionalQueryContext,
|
||||
entityQueryContextProvider: EntityQueryContextProvider
|
||||
) {
|
||||
super(queryInterface, entityQueryContextProvider);
|
||||
}
|
||||
|
||||
public override appendPostCommitCallback(callback: PostCommitCallback): void {
|
||||
this.postCommitInvalidationCallbacksToTransfer.push(callback);
|
||||
}
|
||||
|
||||
public override appendPostCommitInvalidationCallback(callback: PostCommitCallback): void {
|
||||
this.postCommitCallbacksToTransfer.push(callback);
|
||||
}
|
||||
|
||||
public override runPostCommitCallbacksAsync(): Promise<void> {
|
||||
throw new Error(
|
||||
'Must not call runPostCommitCallbacksAsync on EntityNestedTransactionalQueryContext'
|
||||
);
|
||||
}
|
||||
|
||||
public transferPostCommitCallbacksToParent(): void {
|
||||
for (const callback of this.postCommitInvalidationCallbacksToTransfer) {
|
||||
this.parentQueryContext.appendPostCommitInvalidationCallback(callback);
|
||||
}
|
||||
|
||||
for (const callback of this.postCommitCallbacksToTransfer) {
|
||||
this.parentQueryContext.appendPostCommitCallback(callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import {
|
||||
EntityTransactionalQueryContext,
|
||||
EntityNonTransactionalQueryContext,
|
||||
EntityNestedTransactionalQueryContext,
|
||||
TransactionConfig,
|
||||
} from './EntityQueryContext';
|
||||
|
||||
/**
|
||||
@@ -22,21 +24,26 @@ export default abstract class EntityQueryContextProvider {
|
||||
/**
|
||||
* Vend a transaction runner for use in runInTransactionAsync.
|
||||
*/
|
||||
protected abstract createTransactionRunner<T>(): (
|
||||
transactionScope: (queryInterface: any) => Promise<T>
|
||||
) => Promise<T>;
|
||||
protected abstract createTransactionRunner<T>(
|
||||
transactionConfig?: TransactionConfig
|
||||
): (transactionScope: (queryInterface: any) => Promise<T>) => Promise<T>;
|
||||
|
||||
protected abstract createNestedTransactionRunner<T>(
|
||||
outerQueryInterface: any
|
||||
): (transactionScope: (queryInterface: any) => Promise<T>) => Promise<T>;
|
||||
|
||||
/**
|
||||
* Start a transaction and execute the provided transaction-scoped closure within the transaction.
|
||||
* @param transactionScope - async callback to execute within the transaction
|
||||
*/
|
||||
async runInTransactionAsync<T>(
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<T>,
|
||||
transactionConfig?: TransactionConfig
|
||||
): Promise<T> {
|
||||
const [returnedValue, queryContext] = await this.createTransactionRunner<
|
||||
[T, EntityTransactionalQueryContext]
|
||||
>()(async (queryInterface) => {
|
||||
const queryContext = new EntityTransactionalQueryContext(queryInterface);
|
||||
>(transactionConfig)(async (queryInterface) => {
|
||||
const queryContext = new EntityTransactionalQueryContext(queryInterface, this);
|
||||
const result = await transactionScope(queryContext);
|
||||
await queryContext.runPreCommitCallbacksAsync();
|
||||
return [result, queryContext];
|
||||
@@ -44,4 +51,31 @@ export default abstract class EntityQueryContextProvider {
|
||||
await queryContext.runPostCommitCallbacksAsync();
|
||||
return returnedValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a nested transaction from the specified parent transaction and execure the
|
||||
* provided nested-transaction-scoped closure within the nested transaction.
|
||||
* @param outerQueryContext - the query context of the parent transaction
|
||||
* @param transactionScope - async callback to execute within the nested transaction
|
||||
*/
|
||||
async runInNestedTransactionAsync<T>(
|
||||
outerQueryContext: EntityTransactionalQueryContext,
|
||||
transactionScope: (innerQueryContext: EntityNestedTransactionalQueryContext) => Promise<T>
|
||||
): Promise<T> {
|
||||
const [returnedValue, innerQueryContext] = await this.createNestedTransactionRunner<
|
||||
[T, EntityNestedTransactionalQueryContext]
|
||||
>(outerQueryContext.getQueryInterface())(async (innerQueryInterface) => {
|
||||
const innerQueryContext = new EntityNestedTransactionalQueryContext(
|
||||
innerQueryInterface,
|
||||
outerQueryContext,
|
||||
this
|
||||
);
|
||||
const result = await transactionScope(innerQueryContext);
|
||||
await innerQueryContext.runPreCommitCallbacksAsync();
|
||||
return [result, innerQueryContext];
|
||||
});
|
||||
// post-commit callbacks are appended to parent transaction instead of run, but only after the transaction has succeeded
|
||||
innerQueryContext.transferPostCommitCallbacksToParent();
|
||||
return returnedValue;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import { IEntityClass } from './Entity';
|
||||
import EntityCompanionProvider, { DatabaseAdapterFlavor } from './EntityCompanionProvider';
|
||||
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
|
||||
import { EntityQueryContext, EntityTransactionalQueryContext } from './EntityQueryContext';
|
||||
import {
|
||||
EntityQueryContext,
|
||||
EntityTransactionalQueryContext,
|
||||
TransactionConfig,
|
||||
} from './EntityQueryContext';
|
||||
import ReadonlyEntity from './ReadonlyEntity';
|
||||
import ViewerScopedEntityCompanion from './ViewerScopedEntityCompanion';
|
||||
import ViewerScopedEntityCompanionProvider from './ViewerScopedEntityCompanionProvider';
|
||||
@@ -82,11 +86,12 @@ export default class ViewerContext {
|
||||
*/
|
||||
async runInTransactionForDatabaseAdaptorFlavorAsync<TResult>(
|
||||
databaseAdaptorFlavor: DatabaseAdapterFlavor,
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<TResult>
|
||||
transactionScope: (queryContext: EntityTransactionalQueryContext) => Promise<TResult>,
|
||||
transactionConfig?: TransactionConfig
|
||||
): Promise<TResult> {
|
||||
return await this.entityCompanionProvider
|
||||
.getQueryContextProviderForDatabaseAdaptorFlavor(databaseAdaptorFlavor)
|
||||
.getQueryContext()
|
||||
.runInTransactionIfNotInTransactionAsync(transactionScope);
|
||||
.runInTransactionIfNotInTransactionAsync(transactionScope, transactionConfig);
|
||||
}
|
||||
}
|
||||
@@ -222,6 +222,46 @@ describe(EnforcingEntityLoader, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadFirstByFieldEqualityConjunction', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const entityLoaderMock = mock<EntityLoader<any, any, any, any, any, any>>(EntityLoader);
|
||||
const rejection = new Error();
|
||||
when(
|
||||
entityLoaderMock.loadFirstByFieldEqualityConjunctionAsync(anything(), anything())
|
||||
).thenResolve(result(rejection));
|
||||
const entityLoader = instance(entityLoaderMock);
|
||||
const enforcingEntityLoader = new EnforcingEntityLoader(entityLoader);
|
||||
await expect(
|
||||
enforcingEntityLoader.loadFirstByFieldEqualityConjunctionAsync(anything(), anything())
|
||||
).rejects.toThrow(rejection);
|
||||
});
|
||||
|
||||
it('returns value when result is successful', async () => {
|
||||
const entityLoaderMock = mock<EntityLoader<any, any, any, any, any, any>>(EntityLoader);
|
||||
const resolved = {};
|
||||
when(
|
||||
entityLoaderMock.loadFirstByFieldEqualityConjunctionAsync(anything(), anything())
|
||||
).thenResolve(result(resolved));
|
||||
const entityLoader = instance(entityLoaderMock);
|
||||
const enforcingEntityLoader = new EnforcingEntityLoader(entityLoader);
|
||||
await expect(
|
||||
enforcingEntityLoader.loadFirstByFieldEqualityConjunctionAsync(anything(), anything())
|
||||
).resolves.toEqual(resolved);
|
||||
});
|
||||
|
||||
it('returns null when the query is successful but no rows match', async () => {
|
||||
const entityLoaderMock = mock<EntityLoader<any, any, any, any, any, any>>(EntityLoader);
|
||||
when(
|
||||
entityLoaderMock.loadFirstByFieldEqualityConjunctionAsync(anything(), anything())
|
||||
).thenResolve(null);
|
||||
const entityLoader = instance(entityLoaderMock);
|
||||
const enforcingEntityLoader = new EnforcingEntityLoader(entityLoader);
|
||||
await expect(
|
||||
enforcingEntityLoader.loadFirstByFieldEqualityConjunctionAsync(anything(), anything())
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadManyByFieldEqualityConjunction', () => {
|
||||
it('throws when result is unsuccessful', async () => {
|
||||
const entityLoaderMock = mock<EntityLoader<any, any, any, any, any, any>>(EntityLoader);
|
||||
|
||||
@@ -84,23 +84,25 @@ class BlahEntityPrivacyPolicy extends EntityPrivacyPolicy<
|
||||
];
|
||||
}
|
||||
|
||||
const blahConfiguration = new EntityConfiguration<BlahFields>({
|
||||
idField: 'id',
|
||||
tableName: 'blah_table',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
ownerID: new UUIDField({
|
||||
columnName: 'owner_id',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
|
||||
const blahCompanion = new EntityCompanionDefinition({
|
||||
entityClass: BlahEntity,
|
||||
entityConfiguration: new EntityConfiguration<BlahFields>({
|
||||
idField: 'id',
|
||||
tableName: 'blah_table',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
ownerID: new UUIDField({
|
||||
columnName: 'owner_id',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
}),
|
||||
entityConfiguration: blahConfiguration,
|
||||
privacyPolicyClass: BlahEntityPrivacyPolicy,
|
||||
});
|
||||
|
||||
|
||||
@@ -360,7 +360,7 @@ const makeEntityClasses = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) =>
|
||||
const parentEntityConfiguration = new EntityConfiguration<ParentFields>({
|
||||
idField: 'id',
|
||||
tableName: 'parents',
|
||||
getInboundEdges: () => [ChildEntity],
|
||||
getInboundEdges: async () => [ChildEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
@@ -374,7 +374,7 @@ const makeEntityClasses = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) =>
|
||||
const childEntityConfiguration = new EntityConfiguration<ChildFields>({
|
||||
idField: 'id',
|
||||
tableName: 'children',
|
||||
getInboundEdges: () => [GrandChildEntity],
|
||||
getInboundEdges: async () => [GrandChildEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
@@ -384,7 +384,7 @@ const makeEntityClasses = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) =>
|
||||
columnName: 'parent_id',
|
||||
cache: true,
|
||||
association: {
|
||||
getAssociatedEntityClass: () => ParentEntity,
|
||||
getAssociatedEntityClass: async () => ParentEntity,
|
||||
edgeDeletionBehavior,
|
||||
},
|
||||
}),
|
||||
@@ -405,7 +405,7 @@ const makeEntityClasses = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) =>
|
||||
columnName: 'parent_id',
|
||||
cache: true,
|
||||
association: {
|
||||
getAssociatedEntityClass: () => ChildEntity,
|
||||
getAssociatedEntityClass: async () => ChildEntity,
|
||||
edgeDeletionBehavior,
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
StringArrayField,
|
||||
JSONObjectField,
|
||||
EnumField,
|
||||
JSONArrayField,
|
||||
MaybeJSONArrayField,
|
||||
} from '../EntityFields';
|
||||
import describeFieldTestCase from '../utils/testing/describeFieldTestCase';
|
||||
|
||||
@@ -71,13 +69,3 @@ describeFieldTestCase(
|
||||
);
|
||||
describeFieldTestCase(new JSONObjectField({ columnName: 'wat' }), [{}], [true, 'hello']);
|
||||
describeFieldTestCase(new EnumField({ columnName: 'wat' }), ['hello', 1], [true]);
|
||||
describeFieldTestCase(
|
||||
new JSONArrayField({ columnName: 'wat' }),
|
||||
[[[1, 2]] as any, [['hello']] as any], // jest test cases need extra wrapping array
|
||||
[1, 'hello']
|
||||
);
|
||||
describeFieldTestCase(
|
||||
new MaybeJSONArrayField({ columnName: 'wat' }),
|
||||
[1, 'hello', [['hello']]], // jest test cases need extra wrapping array
|
||||
[]
|
||||
);
|
||||
@@ -2,6 +2,7 @@ import { enforceAsyncResult } from '@expo/results';
|
||||
import { mock, instance, verify, spy, deepEqual, anyOfClass, anything, when } from 'ts-mockito';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { OrderByOrdering } from '../EntityDatabaseAdapter';
|
||||
import EntityLoader from '../EntityLoader';
|
||||
import { EntityPrivacyPolicyEvaluationContext } from '../EntityPrivacyPolicy';
|
||||
import ViewerContext from '../ViewerContext';
|
||||
@@ -210,6 +211,101 @@ describe(EntityLoader, () => {
|
||||
).rejects.toThrowError('Entity field not valid: TestEntity (customIdField = not-a-uuid)');
|
||||
});
|
||||
|
||||
it('loads entities with loadFirstByFieldEqualityConjunction', async () => {
|
||||
const privacyPolicy = new TestEntityPrivacyPolicy();
|
||||
const spiedPrivacyPolicy = spy(privacyPolicy);
|
||||
const viewerContext = instance(mock(ViewerContext));
|
||||
const privacyPolicyEvaluationContext = instance(mock<EntityPrivacyPolicyEvaluationContext>());
|
||||
const metricsAdapter = instance(mock<IEntityMetricsAdapter>());
|
||||
const queryContext = StubQueryContextProvider.getQueryContext();
|
||||
|
||||
const id1 = uuidv4();
|
||||
const id2 = uuidv4();
|
||||
const id3 = uuidv4();
|
||||
const databaseAdapter = new StubDatabaseAdapter<TestFields>(
|
||||
testEntityConfiguration,
|
||||
StubDatabaseAdapter.convertFieldObjectsToDataStore(
|
||||
testEntityConfiguration,
|
||||
new Map([
|
||||
[
|
||||
testEntityConfiguration.tableName,
|
||||
[
|
||||
{
|
||||
customIdField: id1,
|
||||
stringField: 'huh',
|
||||
intField: 4,
|
||||
testIndexedField: '4',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
{
|
||||
customIdField: id2,
|
||||
stringField: 'huh',
|
||||
intField: 4,
|
||||
testIndexedField: '5',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
{
|
||||
customIdField: id3,
|
||||
stringField: 'huh2',
|
||||
intField: 4,
|
||||
testIndexedField: '6',
|
||||
dateField: new Date(),
|
||||
nullableField: null,
|
||||
},
|
||||
],
|
||||
],
|
||||
])
|
||||
)
|
||||
);
|
||||
const cacheAdapterProvider = new NoCacheStubCacheAdapterProvider();
|
||||
const cacheAdapter = cacheAdapterProvider.getCacheAdapter(testEntityConfiguration);
|
||||
const entityCache = new ReadThroughEntityCache(testEntityConfiguration, cacheAdapter);
|
||||
const dataManager = new EntityDataManager(
|
||||
databaseAdapter,
|
||||
entityCache,
|
||||
StubQueryContextProvider,
|
||||
instance(mock<IEntityMetricsAdapter>()),
|
||||
TestEntity.name
|
||||
);
|
||||
const entityLoader = new EntityLoader(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
privacyPolicyEvaluationContext,
|
||||
testEntityConfiguration,
|
||||
TestEntity,
|
||||
privacyPolicy,
|
||||
dataManager,
|
||||
metricsAdapter
|
||||
);
|
||||
const result = await entityLoader.loadFirstByFieldEqualityConjunctionAsync(
|
||||
[
|
||||
{
|
||||
fieldName: 'stringField',
|
||||
fieldValue: 'huh',
|
||||
},
|
||||
{
|
||||
fieldName: 'intField',
|
||||
fieldValue: 4,
|
||||
},
|
||||
],
|
||||
{ orderBy: [{ fieldName: 'testIndexedField', order: OrderByOrdering.DESCENDING }] }
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.ok).toBe(true);
|
||||
expect(result!.enforceValue().getField('testIndexedField')).toEqual('5');
|
||||
verify(
|
||||
spiedPrivacyPolicy.authorizeReadAsync(
|
||||
viewerContext,
|
||||
queryContext,
|
||||
privacyPolicyEvaluationContext,
|
||||
anyOfClass(TestEntity),
|
||||
anything()
|
||||
)
|
||||
).once();
|
||||
});
|
||||
|
||||
it('authorizes loaded entities', async () => {
|
||||
const privacyPolicy = new TestEntityPrivacyPolicy();
|
||||
const spiedPrivacyPolicy = spy(privacyPolicy);
|
||||
|
||||
@@ -45,20 +45,22 @@ class BlahEntity extends Entity<BlahFields, string, ViewerContext> {
|
||||
}
|
||||
}
|
||||
|
||||
const blahConfiguration = new EntityConfiguration<BlahFields>({
|
||||
idField: 'id',
|
||||
tableName: 'blah_table',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
|
||||
const blahCompanion = new EntityCompanionDefinition({
|
||||
entityClass: BlahEntity,
|
||||
entityConfiguration: new EntityConfiguration<BlahFields>({
|
||||
idField: 'id',
|
||||
tableName: 'blah_table',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
cache: true,
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
}),
|
||||
entityConfiguration: blahConfiguration,
|
||||
privacyPolicyClass: BlahEntityPrivacyPolicy,
|
||||
mutationTriggers: () => ({
|
||||
afterCommit: [new TestNonTransactionalMutationTrigger()],
|
||||
|
||||
@@ -226,19 +226,21 @@ class EmptyPolicy extends EntityPrivacyPolicy<BlahFields, string, ViewerContext,
|
||||
protected override readonly deleteRules = [];
|
||||
}
|
||||
|
||||
const blahConfiguration = new EntityConfiguration<BlahFields>({
|
||||
idField: 'id',
|
||||
tableName: 'blah_table',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
});
|
||||
|
||||
const blahEntityCompanionDefinition = new EntityCompanionDefinition({
|
||||
entityClass: BlahEntity,
|
||||
entityConfiguration: new EntityConfiguration<BlahFields>({
|
||||
idField: 'id',
|
||||
tableName: 'blah_table',
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
}),
|
||||
},
|
||||
databaseAdapterFlavor: 'postgres',
|
||||
cacheAdapterFlavor: 'redis',
|
||||
}),
|
||||
entityConfiguration: blahConfiguration,
|
||||
privacyPolicyClass: AlwaysDenyPolicy,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import invariant from 'invariant';
|
||||
|
||||
import { EntityQueryContext } from '../EntityQueryContext';
|
||||
import { EntityQueryContext, TransactionIsolationLevel } from '../EntityQueryContext';
|
||||
import ViewerContext from '../ViewerContext';
|
||||
import { createUnitTestEntityCompanionProvider } from '../utils/testing/createUnitTestEntityCompanionProvider';
|
||||
|
||||
@@ -78,5 +78,77 @@ describe(EntityQueryContext, () => {
|
||||
expect(postCommitCallback).toHaveBeenCalledTimes(0);
|
||||
expect(postCommitInvalidationCallback).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it('calls callbacks correctly for nested transactions', async () => {
|
||||
const companionProvider = createUnitTestEntityCompanionProvider();
|
||||
const viewerContext = new ViewerContext(companionProvider);
|
||||
|
||||
const preCommitCallback = jest.fn(async (): Promise<void> => {});
|
||||
const preCommitNestedCallback = jest.fn(async (): Promise<void> => {});
|
||||
const preCommitNestedCallbackThrow = jest.fn(async (): Promise<void> => {
|
||||
throw new Error('wat');
|
||||
});
|
||||
const postCommitInvalidationCallback = jest.fn(async (): Promise<void> => {});
|
||||
const postCommitCallback = jest.fn(async (): Promise<void> => {});
|
||||
|
||||
await viewerContext.runInTransactionForDatabaseAdaptorFlavorAsync(
|
||||
'postgres',
|
||||
async (queryContext) => {
|
||||
queryContext.appendPostCommitCallback(postCommitCallback);
|
||||
queryContext.appendPostCommitInvalidationCallback(postCommitInvalidationCallback);
|
||||
queryContext.appendPreCommitCallback(preCommitCallback, 0);
|
||||
|
||||
await Promise.all([
|
||||
queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
innerQueryContext.appendPostCommitCallback(postCommitCallback);
|
||||
innerQueryContext.appendPostCommitInvalidationCallback(
|
||||
postCommitInvalidationCallback
|
||||
);
|
||||
innerQueryContext.appendPreCommitCallback(preCommitNestedCallback, 0);
|
||||
}),
|
||||
(async () => {
|
||||
try {
|
||||
await queryContext.runInNestedTransactionAsync(async (innerQueryContext) => {
|
||||
// these two shouldn't be called
|
||||
innerQueryContext.appendPostCommitCallback(postCommitCallback);
|
||||
innerQueryContext.appendPostCommitInvalidationCallback(
|
||||
postCommitInvalidationCallback
|
||||
);
|
||||
innerQueryContext.appendPreCommitCallback(preCommitNestedCallbackThrow, 0);
|
||||
});
|
||||
} catch {}
|
||||
})(),
|
||||
]);
|
||||
}
|
||||
);
|
||||
|
||||
expect(preCommitCallback).toHaveBeenCalledTimes(1);
|
||||
expect(preCommitNestedCallback).toHaveBeenCalledTimes(1);
|
||||
expect(preCommitNestedCallbackThrow).toHaveBeenCalledTimes(1);
|
||||
expect(postCommitCallback).toHaveBeenCalledTimes(2);
|
||||
expect(postCommitInvalidationCallback).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('transaction config', () => {
|
||||
it('passes it into the provider', async () => {
|
||||
const companionProvider = createUnitTestEntityCompanionProvider();
|
||||
const viewerContext = new ViewerContext(companionProvider);
|
||||
|
||||
const queryContextProvider =
|
||||
companionProvider.getQueryContextProviderForDatabaseAdaptorFlavor('postgres');
|
||||
const queryContextProviderSpy = jest.spyOn(queryContextProvider, 'runInTransactionAsync');
|
||||
|
||||
const transactionScopeFn = async (): Promise<any> => {};
|
||||
const transactionConfig = { isolationLevel: TransactionIsolationLevel.SERIALIZABLE };
|
||||
|
||||
await viewerContext.runInTransactionForDatabaseAdaptorFlavorAsync(
|
||||
'postgres',
|
||||
transactionScopeFn,
|
||||
transactionConfig
|
||||
);
|
||||
|
||||
expect(queryContextProviderSpy).toHaveBeenCalledWith(transactionScopeFn, transactionConfig);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -53,7 +53,7 @@ const makeEntityClass = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) => {
|
||||
const categoryEntityConfiguration = new EntityConfiguration<CategoryFields>({
|
||||
idField: 'id',
|
||||
tableName: 'categories',
|
||||
getInboundEdges: () => [CategoryEntity],
|
||||
getInboundEdges: async () => [CategoryEntity],
|
||||
schema: {
|
||||
id: new UUIDField({
|
||||
columnName: 'id',
|
||||
@@ -63,7 +63,7 @@ const makeEntityClass = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) => {
|
||||
columnName: 'parent_category_id',
|
||||
cache: true,
|
||||
association: {
|
||||
getAssociatedEntityClass: () => CategoryEntity,
|
||||
getAssociatedEntityClass: async () => CategoryEntity,
|
||||
edgeDeletionBehavior,
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -385,7 +385,8 @@ describe(EntityDataManager, () => {
|
||||
return await entityDataManager.loadManyByFieldEqualingAsync(queryContext, 'customIdField', [
|
||||
'1',
|
||||
]);
|
||||
}
|
||||
},
|
||||
{}
|
||||
);
|
||||
|
||||
expect(entityDatas.get('1')).toHaveLength(1);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { TransactionConfig } from '../../EntityQueryContext';
|
||||
import EntityQueryContextProvider from '../../EntityQueryContextProvider';
|
||||
|
||||
export class StubQueryContextProvider extends EntityQueryContextProvider {
|
||||
@@ -5,9 +6,15 @@ export class StubQueryContextProvider extends EntityQueryContextProvider {
|
||||
return {};
|
||||
}
|
||||
|
||||
protected createTransactionRunner<T>(): (
|
||||
transactionScope: (queryInterface: any) => Promise<T>
|
||||
) => Promise<T> {
|
||||
protected createTransactionRunner<T>(
|
||||
_transactionConfig?: TransactionConfig
|
||||
): (transactionScope: (queryInterface: any) => Promise<T>) => Promise<T> {
|
||||
return (transactionScope) => Promise.resolve(transactionScope({}));
|
||||
}
|
||||
|
||||
protected createNestedTransactionRunner<T>(
|
||||
_outerQueryInterface: any
|
||||
): (transactionScope: (queryInterface: any) => Promise<T>) => Promise<T> {
|
||||
return (transactionScope) => Promise.resolve(transactionScope({}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ services:
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
postgres:
|
||||
image: postgres:9.6
|
||||
image: postgres:14
|
||||
ports:
|
||||
- "${PGPORT}:5432"
|
||||
volumes:
|
||||
|
||||
@@ -367,32 +367,37 @@
|
||||
minimatch "^3.0.4"
|
||||
strip-json-comments "^3.1.1"
|
||||
|
||||
"@expo/batcher@^1.0.0":
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/@expo/batcher/-/batcher-1.0.0.tgz#325f4d36e2c846de6e72cdc024dbb45136508646"
|
||||
integrity sha512-reebgVwjf8VfZxSXU7e+UjpXGwcUTIMpWR9FY54Oh70ulhXrQiZei62B4D9bH3SVYMwnDGzifHJ8INRrJ+0L1g==
|
||||
|
||||
"@expo/entity-cache-adapter-local-memory@file:packages/entity-cache-adapter-local-memory":
|
||||
version "0.26.1"
|
||||
version "0.30.0"
|
||||
dependencies:
|
||||
lru-cache "^6.0.0"
|
||||
|
||||
"@expo/entity-cache-adapter-redis@file:packages/entity-cache-adapter-redis":
|
||||
version "0.26.1"
|
||||
version "0.30.0"
|
||||
|
||||
"@expo/entity-database-adapter-knex@file:packages/entity-database-adapter-knex":
|
||||
version "0.26.1"
|
||||
version "0.30.0"
|
||||
dependencies:
|
||||
knex "^1.0.2"
|
||||
knex "^2.4.1"
|
||||
|
||||
"@expo/entity-ip-address-field@file:packages/entity-ip-address-field":
|
||||
version "0.26.1"
|
||||
version "0.30.0"
|
||||
dependencies:
|
||||
ip-address "^8.1.0"
|
||||
|
||||
"@expo/entity-secondary-cache-local-memory@file:packages/entity-secondary-cache-local-memory":
|
||||
version "0.26.1"
|
||||
version "0.30.0"
|
||||
|
||||
"@expo/entity-secondary-cache-redis@file:packages/entity-secondary-cache-redis":
|
||||
version "0.26.1"
|
||||
version "0.30.0"
|
||||
|
||||
"@expo/entity@file:packages/entity":
|
||||
version "0.26.1"
|
||||
version "0.30.0"
|
||||
dependencies:
|
||||
"@expo/results" "^1.0.0"
|
||||
dataloader "^2.0.0"
|
||||
@@ -3184,10 +3189,10 @@ color-support@^1.1.3:
|
||||
resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2"
|
||||
integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==
|
||||
|
||||
[email protected]6:
|
||||
version "2.0.16"
|
||||
resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.16.tgz#713b9af84fdb000139f04546bd4a93f62a5085da"
|
||||
integrity sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==
|
||||
[email protected]9:
|
||||
version "2.0.19"
|
||||
resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.19.tgz#cdf044f47ad41a0f4b56b3a0d5b4e6e1a2d5a798"
|
||||
integrity sha512-3tlv/dIP7FWvj3BsbHrGLJ6l/oKh1O3TcgBqMn+yyCagOxc23fyzDS6HypQbgxWbkpDnf52p1LuR4eWDQ/K9WQ==
|
||||
|
||||
columnify@^1.6.0:
|
||||
version "1.6.0"
|
||||
@@ -5111,10 +5116,10 @@ invariant@^2.2.4:
|
||||
dependencies:
|
||||
loose-envify "^1.0.0"
|
||||
|
||||
ioredis@^5.0.4:
|
||||
version "5.0.6"
|
||||
resolved "https://registry.yarnpkg.com/ioredis/-/ioredis-5.0.6.tgz#e50b8cc945f1f3ac932b0b8aab4bd8073d1402a9"
|
||||
integrity sha512-KUm7wPzIet9QrFMoMm09/4bkfVKBUD9KXwBitP3hrNkZ+A6NBndweXGwYIB/7szHcTZgfo7Kvx88SxljJV4D9A==
|
||||
ioredis@^5.2.5:
|
||||
version "5.2.5"
|
||||
resolved "https://registry.yarnpkg.com/ioredis/-/ioredis-5.2.5.tgz#c62dc3945ad2a8f0323fbb2765b934a84a68cde0"
|
||||
integrity sha512-7HKo/ClM2DGLRXdFq8ruS3Uuadensz4A76wPOU0adqlOqd1qkhoLPDaBhmVhUhNGpB+J65/bhLmNB8DDY99HJQ==
|
||||
dependencies:
|
||||
"@ioredis/commands" "^1.1.1"
|
||||
cluster-key-slot "^1.1.0"
|
||||
@@ -6077,12 +6082,12 @@ kleur@^3.0.3:
|
||||
resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e"
|
||||
integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==
|
||||
|
||||
knex@^1.0.2:
|
||||
version "1.0.7"
|
||||
resolved "https://registry.yarnpkg.com/knex/-/knex-1.0.7.tgz#965f4490efc451b140aac4c5c6efa39fd877597b"
|
||||
integrity sha512-89jxuRATt4qJMb9ZyyaKBy0pQ4d5h7eOFRqiNFnUvsgU+9WZ2eIaZKrAPG1+F3mgu5UloPUnkVE5Yo2sKZUs6Q==
|
||||
knex@^2.4.1:
|
||||
version "2.4.1"
|
||||
resolved "https://registry.yarnpkg.com/knex/-/knex-2.4.1.tgz#eff21a905e102a306a9c43ea11d984b0f54c4583"
|
||||
integrity sha512-5wylehvnTOE8EdypPFakccA1zgo6Lp+TNultncvBUCUD0PasY+PLVa9qPrTFCioxPSPVha1u9ye2niAVVbLM0Q==
|
||||
dependencies:
|
||||
colorette "2.0.16"
|
||||
colorette "2.0.19"
|
||||
commander "^9.1.0"
|
||||
debug "4.3.4"
|
||||
escalade "^3.1.1"
|
||||
|
||||
Reference in new issue
Block a user