-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
sequence-fns.ts
83 lines (80 loc) · 2.48 KB
/
sequence-fns.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
import { executionCtx } from '../utils';
import { Types } from '../datatypes';
import { FunctionDefinition, QueryError } from '../interfaces';
import { asSeq, RegClass, _ISequence } from '../interfaces-private';
// https://www.postgresql.org/docs/8.1/functions-sequence.html
function getSeq(id: RegClass) {
const { transaction, schema } = executionCtx();
if (!transaction) {
throw new QueryError('cannot query sequence value in this context');
}
return {
t: transaction,
seq: asSeq(schema.getObjectByRegOrName(id)),
};
}
const lastVal = Symbol();
export const sequenceFunctions: FunctionDefinition[] = [
{
name: 'nextval',
args: [Types.regclass],
returns: Types.integer,
implementation: (seqId: RegClass) => {
const { seq, t } = getSeq(seqId);
const ret = seq.nextValue(t);
t.set(lastVal, ret);
return ret;
},
impure: true,
},
{
name: 'currval',
args: [Types.regclass],
returns: Types.integer,
implementation: (seqId: RegClass) => {
const { seq, t } = getSeq(seqId);
return seq.currentValue(t);
},
impure: true,
},
{
name: 'lastval',
returns: Types.integer,
implementation: (seqId: RegClass) => {
const { transaction } = executionCtx();
if (!transaction) {
throw new QueryError('cannot query lastval in this context');
}
return transaction.get<number>(lastVal);
},
impure: true,
},
{
name: 'setval',
args: [Types.regclass, Types.integer],
returns: Types.integer,
implementation: (seqId: RegClass, val: number) => {
const { seq, t } = getSeq(seqId);
if (typeof val !== 'number') {
throw new QueryError('Invalid setval() value');
}
seq.setValue(t, val);
return val;
},
impure: true,
},
{
name: 'setval',
args: [Types.regclass, Types.integer, Types.bool],
returns: Types.integer,
implementation: (seqId: RegClass, val: number, increase: boolean) => {
const { seq, t } = getSeq(seqId);
if (typeof val !== 'number') {
throw new QueryError('Invalid setval() value');
}
seq.setValue(t, val, increase);
return val;
},
impure: true,
},
]