• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Permify / permify / 10478460802

20 Aug 2024 08:07PM UTC coverage: 80.155% (+0.05%) from 80.108%
10478460802

Pull #1470

github

tolgaOzen
test: cursor pagination
Pull Request #1470: feat(bulkchecker): add pagination limit and improve synchronization

464 of 554 new or added lines in 16 files covered. (83.75%)

4 existing lines in 2 files now uncovered.

7957 of 9927 relevant lines covered (80.16%)

116.05 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.32
/internal/storage/postgres/dataReader.go
1
package postgres
2

3
import (
4
        "context"
5
        "errors"
6
        "fmt"
7
        "log/slog"
8
        "strconv"
9
        "strings"
10

11
        "github.com/jackc/pgx/v5"
12

13
        "github.com/Masterminds/squirrel"
14
        "github.com/golang/protobuf/jsonpb"
15
        "google.golang.org/protobuf/types/known/anypb"
16

17
        "github.com/Permify/permify/internal/storage"
18
        "github.com/Permify/permify/internal/storage/postgres/snapshot"
19
        "github.com/Permify/permify/internal/storage/postgres/types"
20
        "github.com/Permify/permify/internal/storage/postgres/utils"
21
        "github.com/Permify/permify/pkg/database"
22
        db "github.com/Permify/permify/pkg/database/postgres"
23
        base "github.com/Permify/permify/pkg/pb/base/v1"
24
        "github.com/Permify/permify/pkg/token"
25
)
26

27
// DataReader is a struct which holds a reference to the database, transaction options and a logger.
28
// It is responsible for reading data from the database.
29
type DataReader struct {
30
        database  *db.Postgres  // database is an instance of the PostgreSQL database
31
        txOptions pgx.TxOptions // txOptions specifies the isolation level for database transaction and sets it as read only
32
}
33

34
// NewDataReader is a constructor function for DataReader.
35
// It initializes a new DataReader with a given database, a logger, and sets transaction options to be read-only with Repeatable Read isolation level.
36
func NewDataReader(database *db.Postgres) *DataReader {
14✔
37
        return &DataReader{
14✔
38
                database:  database,                                                             // Set the database to the passed in PostgreSQL instance
14✔
39
                txOptions: pgx.TxOptions{IsoLevel: pgx.ReadCommitted, AccessMode: pgx.ReadOnly}, // Set the transaction options
14✔
40
        }
14✔
41
}
14✔
42

43
// QueryRelationships reads relation tuples from the storage based on the given filter.
44
func (r *DataReader) QueryRelationships(ctx context.Context, tenantID string, filter *base.TupleFilter, snap string, pagination database.CursorPagination) (it *database.TupleIterator, err error) {
2✔
45
        // Start a new trace span and end it when the function exits.
2✔
46
        ctx, span := tracer.Start(ctx, "data-reader.query-relationships")
2✔
47
        defer span.End()
2✔
48

2✔
49
        slog.DebugContext(ctx, "querying relationships for tenant_id", slog.String("tenant_id", tenantID))
2✔
50

2✔
51
        // Decode the snapshot value.
2✔
52
        var st token.SnapToken
2✔
53
        st, err = snapshot.EncodedToken{Value: snap}.Decode()
2✔
54
        if err != nil {
2✔
55
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
56
        }
×
57

58
        // Build the relationships query based on the provided filter and snapshot value.
59
        var args []interface{}
2✔
60
        builder := r.database.Builder.Select("entity_type, entity_id, relation, subject_type, subject_id, subject_relation").From(RelationTuplesTable).Where(squirrel.Eq{"tenant_id": tenantID})
2✔
61
        builder = utils.TuplesFilterQueryForSelectBuilder(builder, filter)
2✔
62
        builder = utils.SnapshotQuery(builder, st.(snapshot.Token).Value.Uint)
2✔
63

2✔
64
        if pagination.Cursor() != "" {
2✔
NEW
65
                var t database.ContinuousToken
×
NEW
66
                t, err = utils.EncodedContinuousToken{Value: pagination.Cursor()}.Decode()
×
NEW
67
                if err != nil {
×
NEW
68
                        return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INVALID_CONTINUOUS_TOKEN)
×
NEW
69
                }
×
NEW
70
                builder = builder.Where(squirrel.GtOrEq{pagination.Sort(): t.(utils.ContinuousToken).Value})
×
71
        }
72

73
        if pagination.Sort() != "" {
2✔
NEW
74
                builder = builder.OrderBy(pagination.Sort())
×
NEW
75
        }
×
76

77
        // Generate the SQL query and arguments.
78
        var query string
2✔
79
        query, args, err = builder.ToSql()
2✔
80
        if err != nil {
2✔
81
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SQL_BUILDER)
×
82
        }
×
83

84
        slog.DebugContext(ctx, "generated sql query", slog.String("query", query), "with args", slog.Any("arguments", args))
2✔
85

2✔
86
        // Execute the SQL query and retrieve the result rows.
2✔
87
        var rows pgx.Rows
2✔
88
        rows, err = r.database.ReadPool.Query(ctx, query, args...)
2✔
89
        if err != nil {
2✔
90
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
×
91
        }
×
92
        defer rows.Close()
2✔
93

2✔
94
        // Process the result rows and store the relationships in a TupleCollection.
2✔
95
        collection := database.NewTupleCollection()
2✔
96
        for rows.Next() {
5✔
97
                rt := storage.RelationTuple{}
3✔
98
                err = rows.Scan(&rt.EntityType, &rt.EntityID, &rt.Relation, &rt.SubjectType, &rt.SubjectID, &rt.SubjectRelation)
3✔
99
                if err != nil {
3✔
100
                        return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
101
                }
×
102
                collection.Add(rt.ToTuple())
3✔
103
        }
104
        if err = rows.Err(); err != nil {
2✔
105
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
106
        }
×
107

108
        slog.DebugContext(ctx, "successfully retrieved relation tuples from the database")
2✔
109

2✔
110
        // Return a TupleIterator created from the TupleCollection.
2✔
111
        return collection.CreateTupleIterator(), nil
2✔
112
}
113

114
// ReadRelationships reads relation tuples from the storage based on the given filter and pagination.
115
func (r *DataReader) ReadRelationships(ctx context.Context, tenantID string, filter *base.TupleFilter, snap string, pagination database.Pagination) (collection *database.TupleCollection, ct database.EncodedContinuousToken, err error) {
10✔
116
        // Start a new trace span and end it when the function exits.
10✔
117
        ctx, span := tracer.Start(ctx, "data-reader.read-relationships")
10✔
118
        defer span.End()
10✔
119

10✔
120
        slog.DebugContext(ctx, "reading relationships for tenant_id", slog.String("tenant_id", tenantID))
10✔
121

10✔
122
        // Decode the snapshot value.
10✔
123
        var st token.SnapToken
10✔
124
        st, err = snapshot.EncodedToken{Value: snap}.Decode()
10✔
125
        if err != nil {
10✔
126
                return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
127
        }
×
128

129
        // Build the relationships query based on the provided filter, snapshot value, and pagination settings.
130
        builder := r.database.Builder.Select("id, entity_type, entity_id, relation, subject_type, subject_id, subject_relation").From(RelationTuplesTable).Where(squirrel.Eq{"tenant_id": tenantID})
10✔
131
        builder = utils.TuplesFilterQueryForSelectBuilder(builder, filter)
10✔
132
        builder = utils.SnapshotQuery(builder, st.(snapshot.Token).Value.Uint)
10✔
133

10✔
134
        // Apply the pagination token and limit to the query.
10✔
135
        if pagination.Token() != "" {
11✔
136
                var t database.ContinuousToken
1✔
137
                t, err = utils.EncodedContinuousToken{Value: pagination.Token()}.Decode()
1✔
138
                if err != nil {
1✔
139
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INVALID_CONTINUOUS_TOKEN)
×
140
                }
×
141
                var v uint64
1✔
142
                v, err = strconv.ParseUint(t.(utils.ContinuousToken).Value, 10, 64)
1✔
143
                if err != nil {
1✔
144
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INVALID_CONTINUOUS_TOKEN)
×
145
                }
×
146
                builder = builder.Where(squirrel.GtOrEq{"id": v})
1✔
147
        }
148

149
        builder = builder.OrderBy("id")
10✔
150

10✔
151
        if pagination.PageSize() != 0 {
20✔
152
                builder = builder.Limit(uint64(pagination.PageSize() + 1))
10✔
153
        }
10✔
154

155
        // Generate the SQL query and arguments.
156
        var query string
10✔
157
        var args []interface{}
10✔
158
        query, args, err = builder.ToSql()
10✔
159
        if err != nil {
10✔
160
                return nil, database.NewNoopContinuousToken().Encode(), utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SQL_BUILDER)
×
161
        }
×
162

163
        slog.DebugContext(ctx, "generated sql query", slog.String("query", query), "with args", slog.Any("arguments", args))
10✔
164

10✔
165
        // Execute the query and retrieve the rows.
10✔
166
        var rows pgx.Rows
10✔
167
        rows, err = r.database.ReadPool.Query(ctx, query, args...)
10✔
168
        if err != nil {
10✔
169
                return nil, database.NewNoopContinuousToken().Encode(), utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
×
170
        }
×
171
        defer rows.Close()
10✔
172

10✔
173
        var lastID uint64
10✔
174

10✔
175
        // Iterate through the rows and scan the result into a RelationTuple struct.
10✔
176
        tuples := make([]*base.Tuple, 0, pagination.PageSize()+1)
10✔
177
        for rows.Next() {
38✔
178
                rt := storage.RelationTuple{}
28✔
179
                err = rows.Scan(&rt.ID, &rt.EntityType, &rt.EntityID, &rt.Relation, &rt.SubjectType, &rt.SubjectID, &rt.SubjectRelation)
28✔
180
                if err != nil {
28✔
181
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
182
                }
×
183
                lastID = rt.ID
28✔
184
                tuples = append(tuples, rt.ToTuple())
28✔
185
        }
186
        // Check for any errors during iteration.
187
        if err = rows.Err(); err != nil {
10✔
188
                return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
189
        }
×
190

191
        slog.DebugContext(ctx, "successfully read relation tuples from database")
10✔
192

10✔
193
        // Return the results and encoded continuous token for pagination.
10✔
194
        if pagination.PageSize() != 0 && len(tuples) > int(pagination.PageSize()) {
11✔
195
                return database.NewTupleCollection(tuples[:pagination.PageSize()]...), utils.NewContinuousToken(strconv.FormatUint(lastID, 10)).Encode(), nil
1✔
196
        }
1✔
197

198
        return database.NewTupleCollection(tuples...), database.NewNoopContinuousToken().Encode(), nil
9✔
199
}
200

201
// QuerySingleAttribute retrieves a single attribute from the storage based on the given filter.
202
func (r *DataReader) QuerySingleAttribute(ctx context.Context, tenantID string, filter *base.AttributeFilter, snap string) (attribute *base.Attribute, err error) {
4✔
203
        // Start a new trace span and end it when the function exits.
4✔
204
        ctx, span := tracer.Start(ctx, "data-reader.query-single-attribute")
4✔
205
        defer span.End()
4✔
206

4✔
207
        slog.DebugContext(ctx, "querying single attribute for tenant_id", slog.String("tenant_id", tenantID))
4✔
208

4✔
209
        // Decode the snapshot value.
4✔
210
        var st token.SnapToken
4✔
211
        st, err = snapshot.EncodedToken{Value: snap}.Decode()
4✔
212
        if err != nil {
4✔
213
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
214
        }
×
215

216
        // Build the relationships query based on the provided filter and snapshot value.
217
        var args []interface{}
4✔
218
        builder := r.database.Builder.Select("entity_type, entity_id, attribute, value").From(AttributesTable).Where(squirrel.Eq{"tenant_id": tenantID})
4✔
219
        builder = utils.AttributesFilterQueryForSelectBuilder(builder, filter)
4✔
220
        builder = utils.SnapshotQuery(builder, st.(snapshot.Token).Value.Uint)
4✔
221

4✔
222
        // Generate the SQL query and arguments.
4✔
223
        var query string
4✔
224
        query, args, err = builder.ToSql()
4✔
225
        if err != nil {
4✔
226
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SQL_BUILDER)
×
227
        }
×
228

229
        slog.DebugContext(ctx, "generated sql query", slog.String("query", query), "with args", slog.Any("arguments", args))
4✔
230

4✔
231
        row := r.database.ReadPool.QueryRow(ctx, query, args...)
4✔
232

4✔
233
        rt := storage.Attribute{}
4✔
234

4✔
235
        // Suppose you have a struct `rt` with a field `Value` of type `*anypb.Any`.
4✔
236
        var valueStr string
4✔
237

4✔
238
        // Scan the row from the database into the fields of `rt` and `valueStr`.
4✔
239
        err = row.Scan(&rt.EntityType, &rt.EntityID, &rt.Attribute, &valueStr)
4✔
240
        if err != nil {
5✔
241
                if errors.Is(err, pgx.ErrNoRows) {
2✔
242
                        return nil, nil
1✔
243
                } else {
1✔
244
                        return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
245
                }
×
246
        }
247

248
        // Unmarshal the JSON data from `valueStr` into `rt.Value`.
249
        rt.Value = &anypb.Any{}
3✔
250
        unmarshaler := &jsonpb.Unmarshaler{}
3✔
251
        err = unmarshaler.Unmarshal(strings.NewReader(valueStr), rt.Value)
3✔
252
        if err != nil {
3✔
253
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
254
        }
×
255

256
        slog.DebugContext(ctx, "successfully retrieved Single attribute from the database")
3✔
257

3✔
258
        return rt.ToAttribute(), nil
3✔
259
}
260

261
// QueryAttributes reads multiple attributes from the storage based on the given filter.
262
func (r *DataReader) QueryAttributes(ctx context.Context, tenantID string, filter *base.AttributeFilter, snap string) (it *database.AttributeIterator, err error) {
2✔
263
        // Start a new trace span and end it when the function exits.
2✔
264
        ctx, span := tracer.Start(ctx, "data-reader.query-attributes")
2✔
265
        defer span.End()
2✔
266

2✔
267
        slog.DebugContext(ctx, "querying Attributes for tenant_id", slog.String("tenant_id", tenantID))
2✔
268

2✔
269
        // Decode the snapshot value.
2✔
270
        var st token.SnapToken
2✔
271
        st, err = snapshot.EncodedToken{Value: snap}.Decode()
2✔
272
        if err != nil {
2✔
273
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
274
        }
×
275

276
        // Build the relationships query based on the provided filter and snapshot value.
277
        var args []interface{}
2✔
278
        builder := r.database.Builder.Select("entity_type, entity_id, attribute, value").From(AttributesTable).Where(squirrel.Eq{"tenant_id": tenantID})
2✔
279
        builder = utils.AttributesFilterQueryForSelectBuilder(builder, filter)
2✔
280
        builder = utils.SnapshotQuery(builder, st.(snapshot.Token).Value.Uint)
2✔
281

2✔
282
        // Generate the SQL query and arguments.
2✔
283
        var query string
2✔
284
        query, args, err = builder.ToSql()
2✔
285
        if err != nil {
2✔
286
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SQL_BUILDER)
×
287
        }
×
288

289
        slog.DebugContext(ctx, "generated sql query", slog.String("query", query), "with args", slog.Any("arguments", args))
2✔
290

2✔
291
        // Execute the SQL query and retrieve the result rows.
2✔
292
        var rows pgx.Rows
2✔
293
        rows, err = r.database.ReadPool.Query(ctx, query, args...)
2✔
294
        if err != nil {
2✔
295
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
×
296
        }
×
297
        defer rows.Close()
2✔
298

2✔
299
        // Process the result rows and store the relationships in a TupleCollection.
2✔
300
        collection := database.NewAttributeCollection()
2✔
301
        for rows.Next() {
5✔
302
                rt := storage.Attribute{}
3✔
303

3✔
304
                // Suppose you have a struct `rt` with a field `Value` of type `*anypb.Any`.
3✔
305
                var valueStr string
3✔
306

3✔
307
                // Scan the row from the database into the fields of `rt` and `valueStr`.
3✔
308
                err := rows.Scan(&rt.EntityType, &rt.EntityID, &rt.Attribute, &valueStr)
3✔
309
                if err != nil {
3✔
310
                        return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
311
                }
×
312

313
                // Unmarshal the JSON data from `valueStr` into `rt.Value`.
314
                rt.Value = &anypb.Any{}
3✔
315
                unmarshaler := &jsonpb.Unmarshaler{}
3✔
316
                err = unmarshaler.Unmarshal(strings.NewReader(valueStr), rt.Value)
3✔
317
                if err != nil {
3✔
318
                        return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
319
                }
×
320

321
                collection.Add(rt.ToAttribute())
3✔
322
        }
323
        if err = rows.Err(); err != nil {
2✔
324
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
325
        }
×
326

327
        slog.DebugContext(ctx, "successfully retrieved attributes tuples from the database")
2✔
328

2✔
329
        // Return a TupleIterator created from the TupleCollection.
2✔
330
        return collection.CreateAttributeIterator(), nil
2✔
331
}
332

333
// ReadAttributes reads multiple attributes from the storage based on the given filter and pagination.
334
func (r *DataReader) ReadAttributes(ctx context.Context, tenantID string, filter *base.AttributeFilter, snap string, pagination database.Pagination) (collection *database.AttributeCollection, ct database.EncodedContinuousToken, err error) {
10✔
335
        // Start a new trace span and end it when the function exits.
10✔
336
        ctx, span := tracer.Start(ctx, "data-reader.read-attributes")
10✔
337
        defer span.End()
10✔
338

10✔
339
        slog.DebugContext(ctx, "reading attributes for tenant_id", slog.String("tenant_id", tenantID))
10✔
340

10✔
341
        // Decode the snapshot value.
10✔
342
        var st token.SnapToken
10✔
343
        st, err = snapshot.EncodedToken{Value: snap}.Decode()
10✔
344
        if err != nil {
10✔
345
                return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
346
        }
×
347

348
        // Build the relationships query based on the provided filter, snapshot value, and pagination settings.
349
        builder := r.database.Builder.Select("id, entity_type, entity_id, attribute, value").From(AttributesTable).Where(squirrel.Eq{"tenant_id": tenantID})
10✔
350
        builder = utils.AttributesFilterQueryForSelectBuilder(builder, filter)
10✔
351
        builder = utils.SnapshotQuery(builder, st.(snapshot.Token).Value.Uint)
10✔
352

10✔
353
        // Apply the pagination token and limit to the query.
10✔
354
        if pagination.Token() != "" {
11✔
355
                var t database.ContinuousToken
1✔
356
                t, err = utils.EncodedContinuousToken{Value: pagination.Token()}.Decode()
1✔
357
                if err != nil {
1✔
358
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INVALID_CONTINUOUS_TOKEN)
×
359
                }
×
360
                var v uint64
1✔
361
                v, err = strconv.ParseUint(t.(utils.ContinuousToken).Value, 10, 64)
1✔
362
                if err != nil {
1✔
363
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INVALID_CONTINUOUS_TOKEN)
×
364
                }
×
365
                builder = builder.Where(squirrel.GtOrEq{"id": v})
1✔
366
        }
367

368
        builder = builder.OrderBy("id")
10✔
369

10✔
370
        if pagination.PageSize() != 0 {
20✔
371
                builder = builder.Limit(uint64(pagination.PageSize() + 1))
10✔
372
        }
10✔
373

374
        // Generate the SQL query and arguments.
375
        var query string
10✔
376
        var args []interface{}
10✔
377
        query, args, err = builder.ToSql()
10✔
378
        if err != nil {
10✔
379
                return nil, database.NewNoopContinuousToken().Encode(), utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SQL_BUILDER)
×
380
        }
×
381

382
        slog.DebugContext(ctx, "generated sql query", slog.String("query", query), "with args", slog.Any("arguments", args))
10✔
383

10✔
384
        // Execute the query and retrieve the rows.
10✔
385
        var rows pgx.Rows
10✔
386
        rows, err = r.database.ReadPool.Query(ctx, query, args...)
10✔
387
        if err != nil {
10✔
388
                return nil, database.NewNoopContinuousToken().Encode(), utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
×
389
        }
×
390
        defer rows.Close()
10✔
391

10✔
392
        var lastID uint64
10✔
393

10✔
394
        // Iterate through the rows and scan the result into a RelationTuple struct.
10✔
395
        attributes := make([]*base.Attribute, 0, pagination.PageSize()+1)
10✔
396
        for rows.Next() {
31✔
397
                rt := storage.Attribute{}
21✔
398

21✔
399
                // Suppose you have a struct `rt` with a field `Value` of type `*anypb.Any`.
21✔
400
                var valueStr string
21✔
401

21✔
402
                // Scan the row from the database into the fields of `rt` and `valueStr`.
21✔
403
                err := rows.Scan(&rt.ID, &rt.EntityType, &rt.EntityID, &rt.Attribute, &valueStr)
21✔
404
                if err != nil {
21✔
405
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
406
                }
×
407
                lastID = rt.ID
21✔
408

21✔
409
                // Unmarshal the JSON data from `valueStr` into `rt.Value`.
21✔
410
                rt.Value = &anypb.Any{}
21✔
411
                unmarshaler := &jsonpb.Unmarshaler{}
21✔
412
                err = unmarshaler.Unmarshal(strings.NewReader(valueStr), rt.Value)
21✔
413
                if err != nil {
21✔
414
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
415
                }
×
416

417
                attributes = append(attributes, rt.ToAttribute())
21✔
418
        }
419
        // Check for any errors during iteration.
420
        if err = rows.Err(); err != nil {
10✔
421
                return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
422
        }
×
423

424
        slog.DebugContext(ctx, "successfully read attributes from the database")
10✔
425

10✔
426
        // Return the results and encoded continuous token for pagination.
10✔
427
        if len(attributes) > int(pagination.PageSize()) {
11✔
428
                return database.NewAttributeCollection(attributes[:pagination.PageSize()]...), utils.NewContinuousToken(strconv.FormatUint(lastID, 10)).Encode(), nil
1✔
429
        }
1✔
430

431
        return database.NewAttributeCollection(attributes...), database.NewNoopContinuousToken().Encode(), nil
9✔
432
}
433

434
// QueryUniqueEntities reads unique entities from the storage based on the given filter and pagination.
435
func (r *DataReader) QueryUniqueEntities(ctx context.Context, tenantID, name, snap string, pagination database.Pagination) (ids []string, ct database.EncodedContinuousToken, err error) {
4✔
436
        // Start a new trace span and end it when the function exits.
4✔
437
        ctx, span := tracer.Start(ctx, "data-reader.query-unique-entities")
4✔
438
        defer span.End()
4✔
439

4✔
440
        slog.DebugContext(ctx, "querying unique entities for tenant_id", slog.String("tenant_id", tenantID))
4✔
441

4✔
442
        // Decode the snapshot value.
4✔
443
        var st token.SnapToken
4✔
444
        st, err = snapshot.EncodedToken{Value: snap}.Decode()
4✔
445
        if err != nil {
4✔
446
                return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
447
        }
×
448

449
        query := utils.BulkEntityFilterQuery(tenantID, name, st.(snapshot.Token).Value.Uint)
4✔
450

4✔
451
        // Apply the pagination token and limit to the subQuery.
4✔
452
        if pagination.Token() != "" {
5✔
453
                var t database.ContinuousToken
1✔
454
                t, err = utils.EncodedContinuousToken{Value: pagination.Token()}.Decode()
1✔
455
                if err != nil {
1✔
456
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INVALID_CONTINUOUS_TOKEN)
×
457
                }
×
458
                query = fmt.Sprintf("%s WHERE entity_id >= '%s'", query, t.(utils.ContinuousToken).Value)
1✔
459
        }
460

461
        // Append ORDER BY and LIMIT clauses.
462
        query = fmt.Sprintf("%s ORDER BY entity_id", query)
4✔
463

4✔
464
        if pagination.PageSize() != 0 {
8✔
465
                query = fmt.Sprintf("%s LIMIT %d", query, pagination.PageSize()+1)
4✔
466
        }
4✔
467

468
        slog.DebugContext(ctx, "generated sql query", slog.String("query", query))
4✔
469

4✔
470
        // Execute the query and retrieve the rows.
4✔
471
        var rows pgx.Rows
4✔
472
        rows, err = r.database.ReadPool.Query(ctx, query)
4✔
473
        if err != nil {
4✔
474
                return nil, database.NewNoopContinuousToken().Encode(), utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
×
475
        }
×
476
        defer rows.Close()
4✔
477

4✔
478
        var lastID string
4✔
479

4✔
480
        // Iterate through the rows and scan the result into a RelationTuple struct.
4✔
481
        entityIDs := make([]string, 0, pagination.PageSize()+1)
4✔
482
        for rows.Next() {
31✔
483
                var entityId string
27✔
484
                err = rows.Scan(&entityId)
27✔
485
                if err != nil {
27✔
486
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
487
                }
×
488

489
                entityIDs = append(entityIDs, entityId)
27✔
490
                lastID = entityId
27✔
491
        }
492

493
        // Check for any errors during iteration.
494
        if err = rows.Err(); err != nil {
4✔
495
                return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
496
        }
×
497

498
        slog.DebugContext(ctx, "successfully retrieved unique entities from the database")
4✔
499

4✔
500
        // Return the results and encoded continuous token for pagination.
4✔
501
        if pagination.PageSize() != 0 && len(entityIDs) > int(pagination.PageSize()) {
5✔
502
                return entityIDs[:pagination.PageSize()], utils.NewContinuousToken(lastID).Encode(), nil
1✔
503
        }
1✔
504

505
        return entityIDs, database.NewNoopContinuousToken().Encode(), nil
3✔
506
}
507

508
// QueryUniqueSubjectReferences reads unique subject references from the storage based on the given filter and pagination.
509
func (r *DataReader) QueryUniqueSubjectReferences(ctx context.Context, tenantID string, subjectReference *base.RelationReference, snap string, pagination database.Pagination) (ids []string, ct database.EncodedContinuousToken, err error) {
4✔
510
        // Start a new trace span and end it when the function exits.
4✔
511
        ctx, span := tracer.Start(ctx, "data-reader.query-unique-subject-reference")
4✔
512
        defer span.End()
4✔
513

4✔
514
        slog.DebugContext(ctx, "querying unique subject references for tenant_id", slog.String("tenant_id", tenantID))
4✔
515

4✔
516
        // Decode the snapshot value.
4✔
517
        var st token.SnapToken
4✔
518
        st, err = snapshot.EncodedToken{Value: snap}.Decode()
4✔
519
        if err != nil {
4✔
520
                return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
521
        }
×
522

523
        // Build the relationships query based on the provided filter, snapshot value, and pagination settings.
524
        builder := r.database.Builder.
4✔
525
                Select("subject_id"). // This will pick the smallest `id` for each unique `subject_id`.
4✔
526
                From(RelationTuplesTable).
4✔
527
                Where(squirrel.Eq{"tenant_id": tenantID}).
4✔
528
                GroupBy("subject_id")
4✔
529
        builder = utils.TuplesFilterQueryForSelectBuilder(builder, &base.TupleFilter{Subject: &base.SubjectFilter{Type: subjectReference.GetType(), Relation: subjectReference.GetRelation()}})
4✔
530
        builder = utils.SnapshotQuery(builder, st.(snapshot.Token).Value.Uint)
4✔
531

4✔
532
        // Apply the pagination token and limit to the query.
4✔
533
        if pagination.Token() != "" {
5✔
534
                var t database.ContinuousToken
1✔
535
                t, err = utils.EncodedContinuousToken{Value: pagination.Token()}.Decode()
1✔
536
                if err != nil {
1✔
537
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INVALID_CONTINUOUS_TOKEN)
×
538
                }
×
539
                builder = builder.Where(squirrel.GtOrEq{"subject_id": t.(utils.ContinuousToken).Value})
1✔
540
        }
541

542
        builder = builder.OrderBy("subject_id")
4✔
543

4✔
544
        if pagination.PageSize() != 0 {
8✔
545
                builder = builder.Limit(uint64(pagination.PageSize() + 1))
4✔
546
        }
4✔
547

548
        // Generate the SQL query and arguments.
549
        var query string
4✔
550
        var args []interface{}
4✔
551
        query, args, err = builder.ToSql()
4✔
552
        if err != nil {
4✔
553
                return nil, database.NewNoopContinuousToken().Encode(), utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SQL_BUILDER)
×
554
        }
×
555

556
        slog.DebugContext(ctx, "generated sql query", slog.String("query", query), "with args", slog.Any("arguments", args))
4✔
557

4✔
558
        // Execute the query and retrieve the rows.
4✔
559
        var rows pgx.Rows
4✔
560
        rows, err = r.database.ReadPool.Query(ctx, query, args...)
4✔
561
        if err != nil {
4✔
562
                return nil, database.NewNoopContinuousToken().Encode(), utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
×
563
        }
×
564
        defer rows.Close()
4✔
565

4✔
566
        var lastID string
4✔
567

4✔
568
        // Iterate through the rows and scan the result into a RelationTuple struct.
4✔
569
        subjectIDs := make([]string, 0, pagination.PageSize()+1)
4✔
570
        for rows.Next() {
14✔
571
                var subjectID string
10✔
572
                err = rows.Scan(&subjectID)
10✔
573
                if err != nil {
10✔
NEW
574
                        return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_INTERNAL)
×
575
                }
×
576

577
                subjectIDs = append(subjectIDs, subjectID)
10✔
578
                lastID = subjectID
10✔
579
        }
580
        // Check for any errors during iteration.
581
        if err = rows.Err(); err != nil {
4✔
582
                return nil, nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
583
        }
×
584

585
        slog.DebugContext(ctx, "successfully retrieved unique subject references from the database")
4✔
586

4✔
587
        // Return the results and encoded continuous token for pagination.
4✔
588
        if pagination.PageSize() != 0 && len(subjectIDs) > int(pagination.PageSize()) {
5✔
589
                return subjectIDs[:pagination.PageSize()], utils.NewContinuousToken(lastID).Encode(), nil
1✔
590
        }
1✔
591

592
        return subjectIDs, database.NewNoopContinuousToken().Encode(), nil
3✔
593
}
594

595
// HeadSnapshot retrieves the latest snapshot token associated with the tenant.
596
func (r *DataReader) HeadSnapshot(ctx context.Context, tenantID string) (token.SnapToken, error) {
1✔
597
        // Start a new trace span and end it when the function exits.
1✔
598
        ctx, span := tracer.Start(ctx, "data-reader.head-snapshot")
1✔
599
        defer span.End()
1✔
600

1✔
601
        slog.DebugContext(ctx, "getting head snapshot for tenant_id", slog.String("tenant_id", tenantID))
1✔
602

1✔
603
        var xid types.XID8
1✔
604

1✔
605
        // Build the query to find the highest transaction ID associated with the tenant.
1✔
606
        builder := r.database.Builder.Select("id").From(TransactionsTable).Where(squirrel.Eq{"tenant_id": tenantID}).OrderBy("id DESC").Limit(1)
1✔
607
        query, args, err := builder.ToSql()
1✔
608
        if err != nil {
1✔
609
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SQL_BUILDER)
×
610
        }
×
611

612
        // Execute the query and retrieve the highest transaction ID.
613
        err = r.database.ReadPool.QueryRow(ctx, query, args...).Scan(&xid)
1✔
614
        if err != nil {
1✔
615
                // If no rows are found, return a snapshot token with a value of 0.
×
616
                if errors.Is(err, pgx.ErrNoRows) {
×
617
                        return snapshot.Token{Value: types.XID8{Uint: 0}}, nil
×
618
                }
×
619
                return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SCAN)
×
620
        }
621

622
        slog.DebugContext(ctx, "successfully retrieved latest snapshot token")
1✔
623

1✔
624
        // Return the latest snapshot token associated with the tenant.
1✔
625
        return snapshot.Token{Value: xid}, nil
1✔
626
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc