forked from typeorm/typeorm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbQueryResultCache.ts
More file actions
182 lines (158 loc) · 7.06 KB
/
DbQueryResultCache.ts
File metadata and controls
182 lines (158 loc) · 7.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import {QueryResultCache} from "./QueryResultCache";
import {QueryResultCacheOptions} from "./QueryResultCacheOptions";
import {Table} from "../schema-builder/schema/Table";
import {TableColumn} from "../schema-builder/schema/TableColumn";
import {QueryRunner} from "../query-runner/QueryRunner";
import {Connection} from "../connection/Connection";
import {SqlServerDriver} from "../driver/sqlserver/SqlServerDriver";
import {MssqlParameter} from "../driver/sqlserver/MssqlParameter";
import {ObjectLiteral} from "../common/ObjectLiteral";
/**
* Caches query result into current database, into separate table called "query-result-cache".
*/
export class DbQueryResultCache implements QueryResultCache {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(protected connection: Connection) {
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Creates a connection with given cache provider.
*/
async connect(): Promise<void> {
}
/**
* Disconnects with given cache provider.
*/
async disconnect(): Promise<void> {
}
/**
* Creates table for storing cache if it does not exist yet.
*/
async synchronize(queryRunner?: QueryRunner): Promise<void> {
queryRunner = this.getQueryRunner(queryRunner);
const driver = this.connection.driver;
const tableExist = await queryRunner.hasTable("query-result-cache"); // todo: table name should be configurable
if (tableExist)
return;
await queryRunner.createTable(new Table("query-result-cache", [ // createTableIfNotExist
new TableColumn({
name: "id",
isNullable: true,
isPrimary: true,
type: driver.normalizeType({ type: driver.mappedDataTypes.cacheId }),
generationStrategy: "increment",
isGenerated: true
}),
new TableColumn({
name: "identifier",
type: driver.normalizeType({ type: driver.mappedDataTypes.cacheIdentifier }),
isNullable: true
}),
new TableColumn({
name: "time",
type: driver.normalizeType({ type: driver.mappedDataTypes.cacheTime }),
isPrimary: false,
isNullable: false
}),
new TableColumn({
name: "duration",
type: driver.normalizeType({ type: driver.mappedDataTypes.cacheDuration }),
isPrimary: false,
isNullable: false
}),
new TableColumn({
name: "query",
type: driver.normalizeType({ type: driver.mappedDataTypes.cacheQuery }),
isPrimary: false,
isNullable: false
}),
new TableColumn({
name: "result",
type: driver.normalizeType({ type: driver.mappedDataTypes.cacheResult }),
isNullable: false
}),
]));
}
/**
* Caches given query result.
* Returns cache result if found.
* Returns undefined if result is not cached.
*/
getFromCache(options: QueryResultCacheOptions, queryRunner?: QueryRunner): Promise<QueryResultCacheOptions|undefined> {
queryRunner = this.getQueryRunner(queryRunner);
const qb = this.connection
.createQueryBuilder(queryRunner)
.select()
.from("query-result-cache", "cache");
if (options.identifier) {
return qb
.where(`${qb.escape("cache")}.${qb.escape("identifier")} = :identifier`)
.setParameters({ identifier: this.connection.driver instanceof SqlServerDriver ? new MssqlParameter(options.identifier, "nvarchar") : options.identifier })
.getRawOne();
} else if (options.query) {
return qb
.where(`${qb.escape("cache")}.${qb.escape("query")} = :query`)
.setParameters({ query: this.connection.driver instanceof SqlServerDriver ? new MssqlParameter(options.query, "nvarchar") : options.query })
.getRawOne();
}
return Promise.resolve(undefined);
}
/**
* Checks if cache is expired or not.
*/
isExpired(savedCache: QueryResultCacheOptions): boolean {
return ((typeof savedCache.time === "string" ? parseInt(savedCache.time as any) : savedCache.time)! + savedCache.duration) < new Date().getTime();
}
/**
* Stores given query result in the cache.
*/
async storeInCache(options: QueryResultCacheOptions, savedCache: QueryResultCacheOptions|undefined, queryRunner?: QueryRunner): Promise<void> {
queryRunner = this.getQueryRunner(queryRunner);
let insertedValues: ObjectLiteral = options;
if (this.connection.driver instanceof SqlServerDriver) { // todo: bad abstraction, re-implement this part, probably better if we create an entity metadata for cache table
insertedValues = {
identifier: new MssqlParameter(options.identifier, "nvarchar"),
time: new MssqlParameter(options.time, "bigint"),
duration: new MssqlParameter(options.duration, "int"),
query: new MssqlParameter(options.query, "nvarchar"),
result: new MssqlParameter(options.result, "nvarchar"),
};
}
if (savedCache && savedCache.identifier) { // if exist then update
await queryRunner.update("query-result-cache", insertedValues, { identifier: insertedValues.identifier });
} else if (savedCache && savedCache.query) { // if exist then update
await queryRunner.update("query-result-cache", insertedValues, { query: insertedValues.query });
} else { // otherwise insert
await queryRunner.insert("query-result-cache", insertedValues);
}
}
/**
* Clears everything stored in the cache.
*/
async clear(queryRunner: QueryRunner): Promise<void> {
return this.getQueryRunner(queryRunner).truncate("query-result-cache");
}
/**
* Removes all cached results by given identifiers from cache.
*/
async remove(identifiers: string[], queryRunner?: QueryRunner): Promise<void> {
await Promise.all(identifiers.map(identifier => {
return this.getQueryRunner(queryRunner).delete("query-result-cache", { identifier });
}));
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
/**
* Gets a query runner to work with.
*/
protected getQueryRunner(queryRunner: QueryRunner|undefined): QueryRunner {
if (queryRunner)
return queryRunner;
return this.connection.createQueryRunner("master");
}
}