-
Notifications
You must be signed in to change notification settings - Fork 307
/
staging.go
313 lines (264 loc) · 8.14 KB
/
staging.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package repo
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/rudderlabs/rudder-server/utils/timeutil"
"github.com/rudderlabs/rudder-server/warehouse/internal/model"
warehouseutils "github.com/rudderlabs/rudder-server/warehouse/utils"
)
const stagingTableName = warehouseutils.WarehouseStagingFilesTable
const stagingTableColumns = `
id,
location,
source_id,
destination_id,
error,
status,
first_event_at,
last_event_at,
total_events,
created_at,
updated_at,
metadata,
workspace_id
`
// StagingFiles is a repository for inserting and querying staging files.
type StagingFiles struct {
DB *sql.DB
Now func() time.Time
once sync.Once
}
type metadataSchema struct {
UseRudderStorage bool `json:"use_rudder_storage"`
SourceBatchID string `json:"source_batch_id"`
SourceTaskID string `json:"source_task_id"`
SourceTaskRunID string `json:"source_task_run_id"`
SourceJobID string `json:"source_job_id"`
SourceJobRunID string `json:"source_job_run_id"`
TimeWindowYear int `json:"time_window_year"`
TimeWindowMonth int `json:"time_window_month"`
TimeWindowDay int `json:"time_window_day"`
TimeWindowHour int `json:"time_window_hour"`
DestinationRevisionID string `json:"destination_revision_id"`
}
func metadataFromStagingFile(stagingFile *model.StagingFile) metadataSchema {
return metadataSchema{
UseRudderStorage: stagingFile.UseRudderStorage,
SourceBatchID: stagingFile.SourceBatchID,
SourceTaskID: stagingFile.SourceTaskID,
SourceTaskRunID: stagingFile.SourceTaskRunID,
SourceJobID: stagingFile.SourceJobID,
SourceJobRunID: stagingFile.SourceJobRunID,
TimeWindowYear: stagingFile.TimeWindow.Year(),
TimeWindowMonth: int(stagingFile.TimeWindow.Month()),
TimeWindowDay: stagingFile.TimeWindow.Day(),
TimeWindowHour: stagingFile.TimeWindow.Hour(),
DestinationRevisionID: stagingFile.DestinationRevisionID,
}
}
func (m *metadataSchema) SetStagingFile(stagingFile *model.StagingFile) {
stagingFile.UseRudderStorage = m.UseRudderStorage
stagingFile.SourceBatchID = m.SourceBatchID
stagingFile.SourceTaskID = m.SourceTaskID
stagingFile.SourceTaskRunID = m.SourceTaskRunID
stagingFile.SourceJobID = m.SourceJobID
stagingFile.SourceJobRunID = m.SourceJobRunID
stagingFile.TimeWindow = time.Date(m.TimeWindowYear, time.Month(m.TimeWindowMonth), m.TimeWindowDay, m.TimeWindowHour, 0, 0, 0, time.UTC)
stagingFile.DestinationRevisionID = m.DestinationRevisionID
}
func (repo *StagingFiles) init() {
repo.once.Do(func() {
if repo.Now == nil {
repo.Now = timeutil.Now
}
})
}
// Insert inserts a staging file into the staging files table. It returns the ID of the inserted staging file.
//
// NOTE: The following fields are ignored and set by the database:
// - ID
// - Error
// - CreatedAt
// - UpdatedAt
func (repo *StagingFiles) Insert(ctx context.Context, stagingFile *model.StagingFileWithSchema) (int64, error) {
repo.init()
var (
id int64
firstEventAt, lastEventAt interface{}
)
firstEventAt = stagingFile.FirstEventAt.UTC()
if stagingFile.FirstEventAt.IsZero() {
firstEventAt = nil
}
lastEventAt = stagingFile.LastEventAt.UTC()
if stagingFile.LastEventAt.IsZero() {
lastEventAt = nil
}
m := metadataFromStagingFile(&stagingFile.StagingFile)
rawMetadata, err := json.Marshal(&m)
if err != nil {
return id, fmt.Errorf("marshaling metadata: %w", err)
}
now := repo.Now()
schemaPayload, err := json.Marshal(stagingFile.Schema)
if err != nil {
return id, fmt.Errorf("marshaling schema: %w", err)
}
err = repo.DB.QueryRowContext(ctx,
`INSERT INTO `+stagingTableName+` (
location,
schema,
workspace_id,
source_id,
destination_id,
status,
total_events,
first_event_at,
last_event_at,
created_at,
updated_at,
metadata
)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING id`,
stagingFile.Location,
schemaPayload,
stagingFile.WorkspaceID,
stagingFile.SourceID,
stagingFile.DestinationID,
stagingFile.Status,
stagingFile.TotalEvents,
firstEventAt,
lastEventAt,
now.UTC(),
now.UTC(),
rawMetadata,
).Scan(&id)
if err != nil {
return id, fmt.Errorf("inserting staging file: %w", err)
}
return id, nil
}
// praseRow is a helper for mapping a row of tableColumns to a model.StagingFile.
func (*StagingFiles) parseRows(rows *sql.Rows) ([]model.StagingFile, error) {
var stagingFiles []model.StagingFile
defer func() { _ = rows.Close() }()
for rows.Next() {
var (
stagingFile model.StagingFile
metadataRaw []byte
firstEventAt, lastEventAt sql.NullTime
errorRaw sql.NullString
)
err := rows.Scan(
&stagingFile.ID,
&stagingFile.Location,
&stagingFile.SourceID,
&stagingFile.DestinationID,
&errorRaw,
&stagingFile.Status,
&firstEventAt,
&lastEventAt,
&stagingFile.TotalEvents,
&stagingFile.CreatedAt,
&stagingFile.UpdatedAt,
&metadataRaw,
&stagingFile.WorkspaceID,
)
if err != nil {
return nil, fmt.Errorf("scanning row: %w", err)
}
stagingFile.CreatedAt = stagingFile.CreatedAt.UTC()
stagingFile.UpdatedAt = stagingFile.UpdatedAt.UTC()
if firstEventAt.Valid {
stagingFile.FirstEventAt = firstEventAt.Time.UTC()
}
if lastEventAt.Valid {
stagingFile.LastEventAt = lastEventAt.Time.UTC()
}
if errorRaw.Valid {
stagingFile.Error = errors.New(errorRaw.String)
}
var m metadataSchema
err = json.Unmarshal(metadataRaw, &m)
if err != nil {
return nil, fmt.Errorf("unmarshal metadata: %w", err)
}
m.SetStagingFile(&stagingFile)
stagingFiles = append(stagingFiles, stagingFile)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterating rows: %w", err)
}
return stagingFiles, nil
}
// GetByID returns staging file with the given ID.
func (repo *StagingFiles) GetByID(ctx context.Context, ID int64) (model.StagingFile, error) {
repo.init()
query := `SELECT ` + stagingTableColumns + ` FROM ` + stagingTableName + ` WHERE id = $1`
rows, err := repo.DB.QueryContext(ctx, query, ID)
if err != nil {
return model.StagingFile{}, fmt.Errorf("querying staging files: %w", err)
}
entries, err := repo.parseRows(rows)
if err != nil {
return model.StagingFile{}, fmt.Errorf("parsing rows: %w", err)
}
if len(entries) == 0 {
return model.StagingFile{}, fmt.Errorf("no staging file found with id: %d", ID)
}
return entries[0], err
}
// GetSchemaByID returns staging file schema field the given ID.
func (repo *StagingFiles) GetSchemaByID(ctx context.Context, ID int64) (json.RawMessage, error) {
repo.init()
query := `SELECT schema FROM ` + stagingTableName + ` WHERE id = $1`
row := repo.DB.QueryRowContext(ctx, query, ID)
if row.Err() != nil {
return nil, fmt.Errorf("querying staging files: %w", row.Err())
}
var schema json.RawMessage
err := row.Scan(&schema)
if err != nil {
return nil, fmt.Errorf("parsing rows: %w", err)
}
return schema, err
}
// GetInRange returns staging files in [startID, endID] range inclusive.
func (repo *StagingFiles) GetInRange(ctx context.Context, sourceID, destinationID string, startID, endID int64) ([]model.StagingFile, error) {
repo.init()
query := `SELECT ` + stagingTableColumns + ` FROM ` + stagingTableName + ` ST
WHERE
id >= $1 AND id <= $2
AND source_id = $3
AND destination_id = $4
ORDER BY
id ASC;`
rows, err := repo.DB.QueryContext(ctx, query, startID, endID, sourceID, destinationID)
if err != nil {
return nil, fmt.Errorf("querying staging files: %w", err)
}
return repo.parseRows(rows)
}
// GetAfterID returns staging files in (startID, +Inf) range.
func (repo *StagingFiles) GetAfterID(ctx context.Context, sourceID, destinationID string, startID int64) ([]model.StagingFile, error) {
repo.init()
query := `SELECT ` + stagingTableColumns + ` FROM ` + stagingTableName + `
WHERE
id > $1
AND source_id = $2
AND destination_id = $3
ORDER BY
id ASC;`
rows, err := repo.DB.QueryContext(ctx, query, startID, sourceID, destinationID)
if err != nil {
return nil, fmt.Errorf("querying staging files: %w", err)
}
return repo.parseRows(rows)
}