-
Notifications
You must be signed in to change notification settings - Fork 128
/
schemaWriter.go
61 lines (46 loc) · 1.8 KB
/
schemaWriter.go
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
package postgres
import (
"context"
"log/slog"
"github.com/jackc/pgx/v5"
"github.com/Permify/permify/internal/storage"
"github.com/Permify/permify/internal/storage/postgres/utils"
db "github.com/Permify/permify/pkg/database/postgres"
base "github.com/Permify/permify/pkg/pb/base/v1"
)
// SchemaWriter - Structure for SchemaWriter
type SchemaWriter struct {
database *db.Postgres
// options
txOptions pgx.TxOptions
}
// NewSchemaWriter creates a new SchemaWriter
func NewSchemaWriter(database *db.Postgres) *SchemaWriter {
return &SchemaWriter{
database: database,
txOptions: pgx.TxOptions{IsoLevel: pgx.ReadCommitted, AccessMode: pgx.ReadWrite},
}
}
// WriteSchema writes a schema to the database
func (w *SchemaWriter) WriteSchema(ctx context.Context, schemas []storage.SchemaDefinition) (err error) {
ctx, span := tracer.Start(ctx, "schema-writer.write-schema")
defer span.End()
slog.Debug("writing schemas to the database", slog.Any("number_of_schemas", len(schemas)))
insertBuilder := w.database.Builder.Insert(SchemaDefinitionTable).Columns("name, serialized_definition, version, tenant_id")
for _, schema := range schemas {
insertBuilder = insertBuilder.Values(schema.Name, schema.SerializedDefinition, schema.Version, schema.TenantID)
}
var query string
var args []interface{}
query, args, err = insertBuilder.ToSql()
if err != nil {
return utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_SQL_BUILDER)
}
slog.Debug("executing sql insert query", slog.Any("query", query), slog.Any("arguments", args))
_, err = w.database.WritePool.Exec(ctx, query, args...)
if err != nil {
return utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
}
slog.Debug("successfully wrote schemas to the database", slog.Any("number_of_schemas", len(schemas)))
return nil
}