forked from typeorm/typeorm
/
ExpoDriver.ts
91 lines (77 loc) · 3.14 KB
/
ExpoDriver.ts
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
import {AbstractSqliteDriver} from "../sqlite-abstract/AbstractSqliteDriver";
import {ExpoConnectionOptions} from "./ExpoConnectionOptions";
import {ExpoQueryRunner} from "./ExpoQueryRunner";
import {QueryRunner} from "../../query-runner/QueryRunner";
import {Connection} from "../../connection/Connection";
import {DriverOptionNotSetError} from "../../error/DriverOptionNotSetError";
export class ExpoDriver extends AbstractSqliteDriver {
options: ExpoConnectionOptions;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(connection: Connection) {
super(connection);
this.database = this.options.database;
// validate options to make sure everything is set
if (!this.options.database)
throw new DriverOptionNotSetError("database");
if (!this.options.driver)
throw new DriverOptionNotSetError("driver");
// load sqlite package
this.sqlite = this.options.driver;
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Closes connection with database.
*/
async disconnect(): Promise<void> {
return new Promise<void>((ok, fail) => {
try {
this.queryRunner = undefined;
this.databaseConnection._db.close();
this.databaseConnection = undefined;
ok();
} catch (error) {
fail(error);
}
});
}
/**
* Creates a query runner used to execute database queries.
*/
createQueryRunner(mode: "master"|"slave" = "master"): QueryRunner {
if (!this.queryRunner)
this.queryRunner = new ExpoQueryRunner(this);
return this.queryRunner;
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
/**
* Creates connection with the database.
*/
protected createDatabaseConnection() {
return new Promise<void>((ok, fail) => {
try {
const databaseConnection = this.sqlite.openDatabase(this.options.database);
/*
// we need to enable foreign keys in sqlite to make sure all foreign key related features
// working properly. this also makes onDelete work with sqlite.
*/
databaseConnection.transaction((tsx: any) => {
tsx.executeSql(`PRAGMA foreign_keys = ON;`, [], (t: any, result: any) => {
ok(databaseConnection);
}, (t: any, err: any) => {
fail({transaction: t, error: err});
});
}, (err: any) => {
fail(err);
});
} catch (error) {
fail(error);
}
});
}
}