@@ -133,35 +133,55 @@ const appendEventsRaw = async (
133
133
134
134
globalPosition = BigInt ( returningId . global_position ) ;
135
135
136
- const positions = await db . querySingle < { stream_position : string } | null > (
137
- `INSERT INTO ${ streamsTable . name }
138
- (stream_id, stream_position, partition, stream_type, stream_metadata, is_archived)
139
- VALUES (
140
- ?,
141
- ?,
142
- ?,
143
- ?,
144
- '[]',
145
- false
146
- )
147
- ON CONFLICT(stream_id, partition, is_archived)
148
- DO UPDATE SET stream_position=stream_position + ?
149
- RETURNING stream_position;
150
- ` ,
151
- [
152
- streamId ,
153
- events . length ,
154
- options ?. partition ?? '0' ,
155
- streamType ,
156
- events . length ,
157
- ] ,
158
- ) ;
136
+ let position : { stream_position : string } | null ;
137
+
138
+ if ( expectedStreamVersion === 0n ) {
139
+ position = await db . querySingle < {
140
+ stream_position : string ;
141
+ } | null > (
142
+ `INSERT INTO ${ streamsTable . name }
143
+ (stream_id, stream_position, partition, stream_type, stream_metadata, is_archived)
144
+ VALUES (
145
+ ?,
146
+ ?,
147
+ ?,
148
+ ?,
149
+ '[]',
150
+ false
151
+ )
152
+ RETURNING stream_position;
153
+ ` ,
154
+ [
155
+ streamId ,
156
+ events . length ,
157
+ options ?. partition ?? streamsTable . columns . partition ,
158
+ streamType ,
159
+ ] ,
160
+ ) ;
161
+ } else {
162
+ position = await db . querySingle < {
163
+ stream_position : string ;
164
+ } | null > (
165
+ `UPDATE ${ streamsTable . name }
166
+ SET stream_position = stream_position + ?
167
+ WHERE stream_id = ?
168
+ AND partition = ?
169
+ AND is_archived = false
170
+ RETURNING stream_position;
171
+ ` ,
172
+ [
173
+ events . length ,
174
+ streamId ,
175
+ options ?. partition ?? streamsTable . columns . partition ,
176
+ ] ,
177
+ ) ;
178
+ }
159
179
160
- if ( positions == null ) {
161
- throw new Error ( 'Could not find stream positions ' ) ;
180
+ if ( position == null ) {
181
+ throw new Error ( 'Could not find stream position ' ) ;
162
182
}
163
183
164
- streamPosition = BigInt ( positions . stream_position ) ;
184
+ streamPosition = BigInt ( position . stream_position ) ;
165
185
166
186
if ( expectedStreamVersion != null ) {
167
187
const expectedStreamPositionAfterSave =
0 commit comments