|
| 1 | +/* |
| 2 | +Copyright 2022 The Matrix.org Foundation C.I.C. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import { PostgresStore, SchemaUpdateFunction } from "matrix-appservice-bridge"; |
| 18 | +import { DataStore, MjolnirRecord } from "../datastore"; |
| 19 | + |
| 20 | +function getSchema(): SchemaUpdateFunction[] { |
| 21 | + const nSchema = 1; |
| 22 | + const schema = []; |
| 23 | + for (let schemaID = 1; schemaID < nSchema + 1; schemaID++) { |
| 24 | + schema.push(require(`./schema/v${schemaID}`).runSchema); |
| 25 | + } |
| 26 | + return schema; |
| 27 | +} |
| 28 | + |
| 29 | +export class PgDataStore extends PostgresStore implements DataStore { |
| 30 | + |
| 31 | + constructor(connectionString: string) { |
| 32 | + super(getSchema(), { url: connectionString }) |
| 33 | + } |
| 34 | + |
| 35 | + public async init(): Promise<void> { |
| 36 | + await this.ensureSchema(); |
| 37 | + } |
| 38 | + |
| 39 | + public async close(): Promise<void> { |
| 40 | + await this.destroy(); |
| 41 | + } |
| 42 | + |
| 43 | + public async list(): Promise<MjolnirRecord[]> { |
| 44 | + const result = await this.sql`SELECT local_part, owner, management_room FROM mjolnir`; |
| 45 | + if (!result.count) { |
| 46 | + return []; |
| 47 | + } |
| 48 | + |
| 49 | + return result.flat() as MjolnirRecord[]; |
| 50 | + } |
| 51 | + |
| 52 | + public async store(mjolnirRecord: MjolnirRecord): Promise<void> { |
| 53 | + await this.sql`INSERT INTO mjolnir (local_part, owner, management_room) |
| 54 | + VALUES (${mjolnirRecord.local_part}, ${mjolnirRecord.owner}, ${mjolnirRecord.management_room})`; |
| 55 | + } |
| 56 | + |
| 57 | + public async lookupByOwner(owner: string): Promise<MjolnirRecord[]> { |
| 58 | + const result = await this.sql`SELECT local_part, owner, management_room FROM mjolnir |
| 59 | + WHERE owner = ${owner}`; |
| 60 | + return result.flat() as MjolnirRecord[]; |
| 61 | + } |
| 62 | + |
| 63 | + public async lookupByLocalPart(localPart: string): Promise<MjolnirRecord[]> { |
| 64 | + const result = await this.sql`SELECT local_part, owner, management_room FROM mjolnir |
| 65 | + WHERE local_part = ${localPart}`; |
| 66 | + return result.flat() as MjolnirRecord[]; |
| 67 | + } |
| 68 | +} |
0 commit comments