orange-orm 4.4.0-beta.1 → 4.5.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client/map.js CHANGED
@@ -48,6 +48,7 @@ function map(index, context, providers, fn) {
48
48
  context.sap = connect.bind(null, 'sap');
49
49
  context.oracle = connect.bind(null, 'oracle');
50
50
  context.sqlite = connect.bind(null, 'sqlite');
51
+ context.d1 = connect.bind(null, 'd1');
51
52
  context.http = function(url) {
52
53
  return index({ db: url, providers});
53
54
  };
@@ -0,0 +1,133 @@
1
+ let createDomain = require('../createDomain');
2
+ let newTransaction = require('./newTransaction');
3
+ let _begin = require('../table/begin');
4
+ let commit = require('../table/commit');
5
+ let rollback = require('../table/rollback');
6
+ let newPool = require('./newPool');
7
+ let useHook = require('../useHook');
8
+ let promise = require('promise/domains');
9
+ let versionArray = process.version.replace('v', '').split('.');
10
+ let major = parseInt(versionArray[0]);
11
+ let express = require('../hostExpress');
12
+ let hostLocal = require('../hostLocal');
13
+ let doQuery = require('../query');
14
+ let releaseDbClient = require('../table/releaseDbClient');
15
+ let setSessionSingleton = require('../table/setSessionSingleton');
16
+
17
+ function newDatabase(d1Database, poolOptions) {
18
+ if (!d1Database)
19
+ throw new Error('Missing d1Database');
20
+ var pool;
21
+ if (!poolOptions)
22
+ pool = newPool.bind(null,d1Database, poolOptions);
23
+ else
24
+ pool = newPool(d1Database, poolOptions);
25
+
26
+ let c = {poolFactory: pool, hostLocal, express};
27
+
28
+ c.transaction = function(options, fn) {
29
+ if ((arguments.length === 1) && (typeof options === 'function')) {
30
+ fn = options;
31
+ options = undefined;
32
+ }
33
+ let domain = createDomain();
34
+
35
+ if (fn)
36
+ return domain.run(runInTransaction);
37
+ else if ((major >= 12) && useHook()) {
38
+ domain.exitContext = true;
39
+ return domain.start().then(run);
40
+ }
41
+ else
42
+ return domain.run(run);
43
+
44
+ function begin() {
45
+ const transactionLess = true;
46
+ return _begin(transactionLess);
47
+ }
48
+
49
+ async function runInTransaction() {
50
+ let result;
51
+ let transaction = newTransaction(domain, pool, options);
52
+ await new Promise(transaction)
53
+ .then(begin)
54
+ .then(fn)
55
+ .then((res) => result = res)
56
+ .then(c.commit)
57
+ .then(null, c.rollback);
58
+ return result;
59
+ }
60
+
61
+ function run() {
62
+ let p;
63
+ let transaction = newTransaction(domain, pool, options);
64
+ if (useHook())
65
+ p = new Promise(transaction);
66
+ else
67
+ p = new promise(transaction);
68
+
69
+ return p.then(begin);
70
+ }
71
+
72
+ };
73
+
74
+ c.createTransaction = function() {
75
+ let domain = createDomain();
76
+ let transaction = newTransaction(domain, pool);
77
+ let p = domain.run(() => new Promise(transaction).then(_begin));
78
+
79
+ function run(fn) {
80
+ return p.then(domain.run.bind(domain, fn));
81
+ }
82
+ return run;
83
+ };
84
+
85
+ c.bindTransaction = function() {
86
+ // @ts-ignore
87
+ var domain = process.domain;
88
+ let p = domain.run(() => true);
89
+
90
+ function run(fn) {
91
+ return p.then(domain.run.bind(domain, fn));
92
+ }
93
+ return run;
94
+ };
95
+
96
+ c.query = function(query) {
97
+ let domain = createDomain();
98
+ let transaction = newTransaction(domain, pool);
99
+ let p = domain.run(() => new Promise(transaction)
100
+ .then(() => setSessionSingleton('changes', []))
101
+ .then(() => doQuery(query).then(onResult, onError)));
102
+ return p;
103
+
104
+ function onResult(result) {
105
+ releaseDbClient();
106
+ return result;
107
+ }
108
+
109
+ function onError(e) {
110
+ releaseDbClient();
111
+ throw e;
112
+ }
113
+ };
114
+
115
+
116
+ c.rollback = rollback;
117
+ c.commit = commit;
118
+
119
+ c.end = function() {
120
+ if (poolOptions)
121
+ return pool.end();
122
+ else
123
+ return Promise.resolve();
124
+ };
125
+
126
+ c.accept = function(caller) {
127
+ caller.visitSqlite();
128
+ };
129
+
130
+ return c;
131
+ }
132
+
133
+ module.exports = newDatabase;
@@ -0,0 +1,19 @@
1
+ var pools = require('../pools');
2
+ var promise = require('../table/promise');
3
+ var end = require('./pool/end');
4
+ var newGenericPool = require('./pool/newGenericPool');
5
+ var newId = require('../newId');
6
+
7
+ function newPool(d1Database, poolOptions) {
8
+ var pool = newGenericPool(d1Database, poolOptions);
9
+ var id = newId();
10
+ var boundEnd = end.bind(null, pool, id);
11
+ var c = {};
12
+
13
+ c.connect = pool.connect;
14
+ c.end = promise.denodeify(boundEnd);
15
+ pools[id] = c;
16
+ return c;
17
+ }
18
+
19
+ module.exports = newPool;
@@ -0,0 +1,82 @@
1
+ const wrapQuery = require('./wrapQuery');
2
+ const encodeBoolean = require('../sqlite/encodeBoolean');
3
+ const deleteFromSql = require('../sqlite/deleteFromSql');
4
+ const selectForUpdateSql = require('../sqlite/selectForUpdateSql');
5
+ const lastInsertedSql = require('../sqlite/lastInsertedSql');
6
+ const limitAndOffset = require('../sqlite/limitAndOffset');
7
+ const insertSql = require('../sqlite/insertSql');
8
+ const insert = require('../sqlite/insert');
9
+
10
+ function newResolveTransaction(domain, pool, { readonly = false } = {}) {
11
+ var rdb = {poolFactory: pool};
12
+ if (!pool.connect) {
13
+ pool = pool();
14
+ rdb.pool = pool;
15
+ }
16
+ rdb.engine = 'sqlite';
17
+ rdb.encodeBoolean = encodeBoolean;
18
+ rdb.decodeJSON = decodeJSON;
19
+ rdb.encodeJSON = JSON.stringify;
20
+ rdb.deleteFromSql = deleteFromSql;
21
+ rdb.selectForUpdateSql = selectForUpdateSql;
22
+ rdb.lastInsertedSql = lastInsertedSql;
23
+ rdb.insertSql = insertSql;
24
+ rdb.insert = insert;
25
+ rdb.lastInsertedIsSeparate = true;
26
+ rdb.multipleStatements = false;
27
+ rdb.limitAndOffset = limitAndOffset;
28
+ rdb.accept = function(caller) {
29
+ caller.visitSqlite();
30
+ };
31
+ rdb.aggregateCount = 0;
32
+ rdb.quote = (name) => `"${name}"`;
33
+
34
+ if (readonly) {
35
+ rdb.dbClient = {
36
+ executeQuery: function(query, callback) {
37
+ pool.connect((err, client, done) => {
38
+ if (err) {
39
+ return callback(err);
40
+ }
41
+ try {
42
+ wrapQuery(client)(query, (err, res) => {
43
+ done();
44
+ callback(err, res);
45
+ });
46
+ } catch (e) {
47
+ done();
48
+ callback(e);
49
+ }
50
+ });
51
+ }
52
+ };
53
+ domain.rdb = rdb;
54
+ return (onSuccess) => onSuccess();
55
+ }
56
+
57
+ return function(onSuccess, onError) {
58
+ pool.connect(onConnected);
59
+
60
+ function onConnected(err, client, done) {
61
+ try {
62
+ if (err) {
63
+ onError(err);
64
+ return;
65
+ }
66
+ client.executeQuery = wrapQuery(client);
67
+ rdb.dbClient = client;
68
+ rdb.dbClientDone = done;
69
+ domain.rdb = rdb;
70
+ onSuccess();
71
+ } catch (e) {
72
+ onError(e);
73
+ }
74
+ }
75
+ };
76
+ }
77
+
78
+ function decodeJSON(value) {
79
+ return JSON.parse(value);
80
+ }
81
+
82
+ module.exports = newResolveTransaction;
@@ -0,0 +1,45 @@
1
+ module.exports = {
2
+ // database host defaults to localhost
3
+ host: 'localhost',
4
+
5
+ //database user's name
6
+ user: process.platform === 'win32' ? process.env.USERNAME : process.env.USER,
7
+
8
+ //name of database to connect
9
+ database: process.platform === 'win32' ? process.env.USERNAME : process.env.USER,
10
+
11
+ //database user's password
12
+ password: null,
13
+
14
+ //database port
15
+ port: 5432,
16
+
17
+ //number of rows to return at a time from a prepared statement's
18
+ //portal. 0 will return all rows at once
19
+ rows: 0,
20
+
21
+ // binary result mode
22
+ binary: false,
23
+
24
+ //Connection pool options - see https://github.com/coopernurse/node-pool
25
+ //number of connections to use in connection pool
26
+ //0 will disable connection pooling
27
+ poolSize: 0,
28
+
29
+ //max milliseconds a client can go unused before it is removed
30
+ //from the pool and destroyed
31
+ poolIdleTimeout: 30000,
32
+
33
+ //frequeny to check for idle clients within the client pool
34
+ reapIntervalMillis: 1000,
35
+
36
+ //pool log function / boolean
37
+ poolLog: false,
38
+
39
+ client_encoding: '',
40
+
41
+ ssl: false,
42
+
43
+ application_name : undefined,
44
+ fallback_application_name: undefined
45
+ };
@@ -0,0 +1,13 @@
1
+ var pools = require('../../pools');
2
+
3
+ function endPool(genericPool, id, done) {
4
+ genericPool.drain(onDrained);
5
+
6
+ function onDrained() {
7
+ genericPool.destroyAllNow();
8
+ delete pools[id];
9
+ done();
10
+ }
11
+ }
12
+
13
+ module.exports = endPool;
@@ -0,0 +1,52 @@
1
+ /* eslint-disable no-prototype-builtins */
2
+ var EventEmitter = require('events').EventEmitter;
3
+
4
+ var defaults = require('./defaults');
5
+ var genericPool = require('../../generic-pool');
6
+
7
+ function newGenericPool(d1Database, poolOptions) {
8
+ poolOptions = poolOptions || {};
9
+ // @ts-ignore
10
+ var pool = genericPool.Pool({
11
+ max: 1,
12
+ idleTimeoutMillis: poolOptions.idleTimeout || defaults.poolIdleTimeout,
13
+ reapIntervalMillis: poolOptions.reapIntervalMillis || defaults.reapIntervalMillis,
14
+ log: poolOptions.log || defaults.poolLog,
15
+ create: function(cb) {
16
+ var client = {d1: d1Database, poolCount: 0};
17
+
18
+ return cb(null, client);
19
+ },
20
+
21
+ destroy: function() {
22
+ }
23
+ });
24
+ //mixin EventEmitter to pool
25
+ EventEmitter.call(pool);
26
+ for(var key in EventEmitter.prototype) {
27
+ if(EventEmitter.prototype.hasOwnProperty(key)) {
28
+ pool[key] = EventEmitter.prototype[key];
29
+ }
30
+ }
31
+ //monkey-patch with connect method
32
+ pool.connect = function(cb) {
33
+ var domain = process.domain;
34
+ pool.acquire(function(err, client) {
35
+ if(domain) {
36
+ cb = domain.bind(cb);
37
+ }
38
+ if(err) return cb(err, null, function() {/*NOOP*/});
39
+ client.poolCount++;
40
+ cb(null, client, function(err) {
41
+ if(err) {
42
+ pool.destroy(client);
43
+ } else {
44
+ pool.release(client);
45
+ }
46
+ });
47
+ });
48
+ };
49
+ return pool;
50
+ }
51
+
52
+ module.exports = newGenericPool;
@@ -0,0 +1,22 @@
1
+ var log = require('../table/log');
2
+
3
+ function wrapQuery(client) {
4
+
5
+ return runQuery;
6
+
7
+ function runQuery(query, onCompleted) {
8
+
9
+ var params = query.parameters;
10
+ var sql = query.sql();
11
+ log.emitQuery({sql, parameters: params});
12
+ client.d1.prepare(sql, params).bind(...params).all().then(onInnerCompleted, onCompleted);
13
+
14
+ function onInnerCompleted(response) {
15
+ onCompleted(null, response.results);
16
+ }
17
+
18
+ }
19
+
20
+ }
21
+
22
+ module.exports = wrapQuery;
package/src/d1test.js ADDED
@@ -0,0 +1,35 @@
1
+ import { connect } from '@cloudflare/d1';
2
+
3
+ const databaseId = process.env.D1_DATABASE_ID;
4
+ const accountId = process.env.D1_ACCOUNT_ID;
5
+ const apiToken = process.env.D1_API_TOKEN;
6
+
7
+ export class Database {
8
+ constructor() {
9
+ this.db = connect({
10
+ databaseId,
11
+ accountId,
12
+ apiToken,
13
+ });
14
+ }
15
+
16
+ async createUser(name, email) {
17
+ return await this.db
18
+ .prepare('INSERT INTO users (name, email) VALUES (?, ?)')
19
+ .bind(name, email)
20
+ .run();
21
+ }
22
+
23
+ async getUsers() {
24
+ return await this.db
25
+ .prepare('SELECT * FROM users')
26
+ .all();
27
+ }
28
+
29
+ async getUserById(id) {
30
+ return await this.db
31
+ .prepare('SELECT * FROM users WHERE id = ?')
32
+ .bind(id)
33
+ .first();
34
+ }
35
+ }
package/src/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Options } from './ajv';
2
2
  import type { RequestHandler } from 'express';
3
+ import type { D1Database } from '@cloudflare/workers-types';
3
4
  import type { ConnectionConfiguration } from 'tedious';
4
5
  import type { PoolAttributes } from 'oracledb';
5
6
  import type { AllowedDbMap, DbMapper, MappedDbDef } from './map';
@@ -10,6 +11,7 @@ declare namespace r {
10
11
 
11
12
  function table(name: string): Table;
12
13
  function end(): Promise<void>;
14
+ function d1(database: D1Database, options?: PoolOptions): Pool;
13
15
  function postgres(connectionString: string, options?: PoolOptions): Pool;
14
16
  function sqlite(connectionString: string, options?: PoolOptions): Pool;
15
17
  function sap(connectionString: string, options?: PoolOptions): Pool;
package/src/index.js CHANGED
@@ -2,6 +2,7 @@ var hostExpress = require('./hostExpress');
2
2
  var client = require('./client/index.js');
3
3
  var _mySql;
4
4
  var _pg;
5
+ var _d1;
5
6
  var _sqlite;
6
7
  var _mssqlNative;
7
8
  var _sap;
@@ -76,6 +77,14 @@ Object.defineProperty(connectViaPool, 'sqlite', {
76
77
  }
77
78
  });
78
79
 
80
+ Object.defineProperty(connectViaPool, 'd1', {
81
+ get: function() {
82
+ if (!_d1)
83
+ _d1 = require('./d1/newDatabase');
84
+ return _d1;
85
+ }
86
+ });
87
+
79
88
  Object.defineProperty(connectViaPool, 'mssqlNative', {
80
89
  get: function() {
81
90
  if (!_mssqlNative)
package/src/map.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Options } from './ajv';
2
2
  import type { ConnectionConfiguration } from 'tedious';
3
+ import type { D1Database } from '@cloudflare/workers-types';
3
4
  import type { PoolAttributes } from 'oracledb';
4
5
  import type { AxiosInterceptorManager, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
5
6
 
@@ -29,6 +30,7 @@ type MappedDb<T> = {
29
30
 
30
31
  type DbConnectable<T> = {
31
32
  http(url: string): MappedDbInstance<T>;
33
+ d1(database: D1Database): MappedDbInstance<T>;
32
34
  postgres(connectionString: string, options?: PoolOptions): MappedDbInstance<T>;
33
35
  sqlite(connectionString: string, options?: PoolOptions): MappedDbInstance<T>;
34
36
  sap(connectionString: string, options?: PoolOptions): MappedDbInstance<T>;
@@ -59,6 +61,7 @@ type DbOptions<T> = {
59
61
 
60
62
  interface Connectors {
61
63
  http(url: string): Pool;
64
+ d1(database: D1Database): Pool;
62
65
  postgres(connectionString: string, options?: PoolOptions): Pool;
63
66
  sqlite(connectionString: string, options?: PoolOptions): Pool;
64
67
  sap(connectionString: string, options?: PoolOptions): Pool;
@@ -8,7 +8,7 @@ const formatDateOut = require('../tedious/formatDateOut');
8
8
  const insertSql = require('../tedious/insertSql');
9
9
  const insert = require('../tedious/insert');
10
10
 
11
- function newResolveTransaction(domain, pool, { readonly } = {}) {
11
+ function newResolveTransaction(domain, pool, { readonly = false } = {}) {
12
12
  var rdb = {poolFactory: pool};
13
13
  if (!pool.connect) {
14
14
  pool = pool();
@@ -7,7 +7,7 @@ const limitAndOffset = require('./limitAndOffset');
7
7
  const insertSql = require('./insertSql');
8
8
  const insert = require('./insert');
9
9
 
10
- function newResolveTransaction(domain, pool, { readonly } = {}) {
10
+ function newResolveTransaction(domain, pool, { readonly = false } = {}) {
11
11
  var rdb = {poolFactory: pool};
12
12
  if (!pool.connect) {
13
13
  pool = pool();
@@ -9,7 +9,7 @@ const insert = require('./insert');
9
9
  const formatDateOut = require('./formatDateOut');
10
10
  const formatDateIn = require('./formatDateIn');
11
11
 
12
- function newResolveTransaction(domain, pool, { readonly } = {}) {
12
+ function newResolveTransaction(domain, pool, { readonly = false } = {}) {
13
13
  var rdb = {poolFactory: pool};
14
14
  if (!pool.connect) {
15
15
  pool = pool();
@@ -9,7 +9,7 @@ var encodeJSON = require('./encodeJSON');
9
9
  var insertSql = require('./insertSql');
10
10
  var insert = require('./insert');
11
11
 
12
- function newResolveTransaction(domain, pool, { readonly } = {}) {
12
+ function newResolveTransaction(domain, pool, { readonly = false } = {}) {
13
13
  var rdb = { poolFactory: pool };
14
14
  if (!pool.connect) {
15
15
  pool = pool();
@@ -8,7 +8,7 @@ const insertSql = require('./insertSql');
8
8
  const insert = require('./insert');
9
9
  const limitAndOffset = require('./limitAndOffset');
10
10
 
11
- function newResolveTransaction(domain, pool, { readonly } = {}) {
11
+ function newResolveTransaction(domain, pool, { readonly = false } = {}) {
12
12
  var rdb = {poolFactory: pool};
13
13
  if (!pool.connect) {
14
14
  pool = pool();
@@ -7,7 +7,7 @@ const limitAndOffset = require('./limitAndOffset');
7
7
  const insertSql = require('./insertSql');
8
8
  const insert = require('./insert');
9
9
 
10
- function newResolveTransaction(domain, pool, { readonly } = {}) {
10
+ function newResolveTransaction(domain, pool, { readonly = false } = {}) {
11
11
  var rdb = {poolFactory: pool};
12
12
  if (!pool.connect) {
13
13
  pool = pool();
@@ -5,7 +5,7 @@ let setSessionSingleton = require('./setSessionSingleton');
5
5
  function begin(readonly) {
6
6
  setSessionSingleton('changes', []);
7
7
  if (readonly) {
8
- setSessionSingleton('readonly', true);
8
+ setSessionSingleton('transactionLess', true);
9
9
  return Promise.resolve();
10
10
  }
11
11
  return executeQuery(beginCommand());
@@ -20,7 +20,7 @@ function commit(result) {
20
20
  await executeChanges(changes);
21
21
  changes = popChanges();
22
22
  }
23
- if (!getSessionSingleton('readonly'))
23
+ if (!getSessionSingleton('transactionLess'))
24
24
  pushCommand(commitCommand);
25
25
  return executeChanges(popChanges());
26
26
  }
@@ -10,7 +10,7 @@ const formatJSONOut = require('./formatJSONOut');
10
10
  const insertSql = require('./insertSql');
11
11
  const insert = require('./insert');
12
12
 
13
- function newResolveTransaction(domain, pool, { readonly } = {}) {
13
+ function newResolveTransaction(domain, pool, { readonly = false } = {}) {
14
14
  var rdb = {poolFactory: pool};
15
15
  if (!pool.connect) {
16
16
  pool = pool();