Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

types.ts

249 lines7.2 KB

1/**
2 * Default types for SQL but can be extended with additional types when using a custom parser.
3 * @typeParam Extensions - Additional value types.
4 */
5export type Value<Extensions = never> =
6 | string
7 | number
8 | boolean
9 | bigint
10 | null
11 | Extensions
12 | Value<Extensions>[]
13 | { [key: string]: Value<Extensions> }
14​
15export type Row<Extensions = never> = Record<string, Value<Extensions>>
16​
17// Check if `T` extends the base Row type without extensions
18// if yes, it has no extensions so we return `never`
19// otherwise, we infer the extensions from the Row type
20export type GetExtensions<T> = [T] extends [Row<never>]
21 ? never
22 : [T] extends [Row<infer E>]
23 ? E
24 : never
25​
26export type Offset =
27 | `-1`
28 | `now`
29 | `${number}_${number}`
30 | `${bigint}_${number}`
31​
32/** Information about transaction visibility for a snapshot. All fields are encoded as strings, but should be treated as uint64. */
33export type PostgresSnapshot = {
34 xmin: `${bigint}`
35 xmax: `${bigint}`
36 xip_list: `${bigint}`[]
38​
39export type NormalizedPgSnapshot = {
40 xmin: bigint
41 xmax: bigint
42 xip_list: bigint[]
44​
45interface Header {
46 [key: Exclude<string, `operation` | `control` | `event`>]: Value
48​
49export type Operation = `insert` | `update` | `delete`
50/**
51 * A tag is a string identifying a reason for this row to be part of the shape.
52 *
53 * Tags can be composite, but they are always sent as a single string. Compound tags
54 * are separated by `|`. It's up to the client to split the tag into its components
55 * in order to react to move-outs correctly. Tag parts are guaranteed to not contain an
56 * unescaped `|` character (escaped as `\\|`) or be a literal `*`.
57 *
58 * Composite tag width is guaranteed to be fixed for a given shape.
59 */
60export type MoveTag = string
61​
62/**
63 * A move pattern is a position and a value. The position is the index of the column
64 * involved in the move. The value is the value of that column.
65 *
66 * Tag width and value order is fixed for a given shape, so the client can determine
67 * which tags match this pattern.
68 */
69export type MovePattern = { pos: number; value: string }
70​
71/** @deprecated Use {@link MovePattern} instead */
72export type MoveOutPattern = MovePattern
73​
74/**
75 * Serialized expression types for structured subset queries.
76 * These allow Electric to properly apply columnMapper transformations
77 * before generating the final SQL.
78 */
79export type SerializedExpression =
80 | { type: `ref`; column: string } // Column reference
81 | { type: `val`; paramIndex: number } // Parameter placeholder ($1, $2, etc.)
82 | { type: `func`; name: string; args: SerializedExpression[] } // Operator/function
83​
84/**
85 * Serialized ORDER BY clause for structured subset queries.
86 */
87export type SerializedOrderByClause = {
88 column: string
89 direction?: `asc` | `desc` // omitted means 'asc'
90 nulls?: `first` | `last`
92​
93export type SubsetParams = {
94 /** Legacy string format WHERE clause */
95 where?: string
96 /** Positional parameter values for WHERE clause */
97 params?: Record<string, string | bigint | number>
98 /** Maximum number of rows to return */
99 limit?: number
100 /** Number of rows to skip */
101 offset?: number
102 /** Legacy string format ORDER BY clause */
103 orderBy?: string
104 /** Structured WHERE expression (preferred when available) */
105 whereExpr?: SerializedExpression
106 /** Structured ORDER BY clauses (preferred when available) */
107 orderByExpr?: SerializedOrderByClause[]
108 /**
109 * HTTP method to use for the request. Overrides `subsetMethod` from ShapeStreamOptions.
110 * - `GET` (default): Sends subset params as query parameters. May fail with 414 errors
111 * for large queries.
112 * - `POST`: Sends subset params in request body as JSON. Recommended to avoid URL
113 * length limits with large WHERE clauses or many parameters.
114 *
115 * In Electric 2.0, GET will be deprecated and only POST will be supported.
116 */
117 method?: `GET` | `POST`
119​
120export type ControlMessage = {
121 headers:
122 | (Header & {
123 control: `up-to-date` | `must-refetch`
124 global_last_seen_lsn?: string
125 })
126 | (Header & { control: `snapshot-end` } & PostgresSnapshot)
127 | (Header & { control: `subset-end` } & SubsetParams)
129​
130export type EventMessage = {
131 headers: Header & { event: `move-out` | `move-in`; patterns: MovePattern[] }
133​
134export type ChangeMessage<T extends Row<unknown> = Row> = {
135 key: string
136 value: T
137 old_value?: Partial<T> // Only provided for updates if `replica` is `full`
138 headers: Header & {
139 operation: Operation
140 txids?: number[]
141 /** Tags will always be present for changes if the shape has a subquery in its where clause, and are omitted otherwise.*/
142 tags?: MoveTag[]
143 removed_tags?: MoveTag[]
144 active_conditions?: boolean[]
145 }
147​
148// Define the type for a record
149export type Message<T extends Row<unknown> = Row> =
150 | ControlMessage
151 | EventMessage
152 | ChangeMessage<T>
153​
154/**
155 * Common properties for all columns.
156 * `dims` is the number of dimensions of the column. Only provided if the column is an array.
157 * `not_null` is true if the column has a `NOT NULL` constraint and is omitted otherwise.
158 */
159export type CommonColumnProps = {
160 dims?: number
161 not_null?: boolean
163​
164export type RegularColumn = {
165 type: string
166} & CommonColumnProps
167​
168export type VarcharColumn = {
169 type: `varchar`
170 max_length?: number
171} & CommonColumnProps
172​
173export type BpcharColumn = {
174 type: `bpchar`
175 length?: number
176} & CommonColumnProps
177​
178export type TimeColumn = {
179 type: `time` | `timetz` | `timestamp` | `timestamptz`
180 precision?: number
181} & CommonColumnProps
182​
183export type IntervalColumn = {
184 type: `interval`
185 fields?:
186 | `YEAR`
187 | `MONTH`
188 | `DAY`
189 | `HOUR`
190 | `MINUTE`
191 | `YEAR TO MONTH`
192 | `DAY TO HOUR`
193 | `DAY TO MINUTE`
194 | `DAY TO SECOND`
195 | `HOUR TO MINUTE`
196 | `HOUR TO SECOND`
197 | `MINUTE TO SECOND`
198} & CommonColumnProps
199​
200export type IntervalColumnWithPrecision = {
201 type: `interval`
202 precision?: 0 | 1 | 2 | 3 | 4 | 5 | 6
203 fields?: `SECOND`
204} & CommonColumnProps
205​
206export type BitColumn = {
207 type: `bit`
208 length: number
209} & CommonColumnProps
210​
211export type NumericColumn = {
212 type: `numeric`
213 precision?: number
214 scale?: number
215} & CommonColumnProps
216​
217export type ColumnInfo =
218 | RegularColumn
219 | VarcharColumn
220 | BpcharColumn
221 | TimeColumn
222 | IntervalColumn
223 | IntervalColumnWithPrecision
224 | BitColumn
225 | NumericColumn
226​
227export type Schema = { [key: string]: ColumnInfo }
228​
229export type TypedMessages<T extends Row<unknown> = Row> = {
230 messages: Array<Message<T>>
231 schema: ColumnInfo
233​
234export type MaybePromise<T> = T | Promise<T>
235​
236/**
237 * Metadata that allows the consumer to know which changes have been incorporated into this snapshot.
238 *
239 * For any data that has a known transaction ID `xid` (and e.g. a key that's part of the snapshot):
240 * - if `xid` < `xmin` - included, change can be skipped
241 * - if `xid` < `xmax` AND `xid` not in `xip` - included, change can be skipped
242 * - if `xid` < `xmax` AND `xid` in `xip` - parallel, not included, change must be processed
243 * - if `xid` >= `xmax` - not included, change must be processed, and we can stop filtering after we see this
244 */
245export type SnapshotMetadata = {
246 /** Random number that's reflected in the `snapshot_mark` header on the snapshot items. */
247 snapshot_mark: number
248 database_lsn: string
249} & PostgresSnapshot