diff --git a/app/common/customer.go b/app/common/customer.go index c8ab1b525c..8987cee8a9 100644 --- a/app/common/customer.go +++ b/app/common/customer.go @@ -8,7 +8,6 @@ import ( "go.opentelemetry.io/otel/trace" "github.com/openmeterio/openmeter/app/config" - "github.com/openmeterio/openmeter/openmeter/billing" "github.com/openmeterio/openmeter/openmeter/customer" customeradapter "github.com/openmeterio/openmeter/openmeter/customer/adapter" customerservice "github.com/openmeterio/openmeter/openmeter/customer/service" @@ -65,7 +64,6 @@ func NewCustomerSubjectServiceHook( tracer trace.Tracer, subjectService subject.Service, customerService customer.Service, - customerOverrideService billing.CustomerOverrideService, ) (CustomerSubjectHook, error) { if !config.EnableSubjectHook { return new(customerservicehooks.NoopSubjectCustomerHook), nil @@ -73,11 +71,10 @@ func NewCustomerSubjectServiceHook( // Initialize the subject customer hook and register it for Subject service h, err := customerservicehooks.NewSubjectCustomerHook(customerservicehooks.SubjectCustomerHookConfig{ - Customer: customerService, - CustomerOverride: customerOverrideService, - Logger: logger, - Tracer: tracer, - IgnoreErrors: config.IgnoreErrors, + Customer: customerService, + Logger: logger, + Tracer: tracer, + IgnoreErrors: config.IgnoreErrors, }) if err != nil { return nil, fmt.Errorf("failed to create customer subject hook: %w", err) diff --git a/cmd/server/wire_gen.go b/cmd/server/wire_gen.go index 10f7000ba4..2bff76ded0 100644 --- a/cmd/server/wire_gen.go +++ b/cmd/server/wire_gen.go @@ -363,7 +363,7 @@ func initializeApplication(ctx context.Context, conf config.Configuration) (Appl cleanup() return Application{}, nil, err } - customerSubjectHook, err := common.NewCustomerSubjectServiceHook(customerConfiguration, logger, tracer, subjectService, customerService, billingService) + customerSubjectHook, err := common.NewCustomerSubjectServiceHook(customerConfiguration, logger, tracer, subjectService, customerService) if err != nil { cleanup6() cleanup5() diff --git a/go.mod b/go.mod index 53c59dbbd7..c75a53f9d7 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( github.com/brianvoe/gofakeit/v6 v6.28.0 github.com/cloudevents/sdk-go/v2 v2.16.1 github.com/confluentinc/confluent-kafka-go/v2 v2.11.1 + github.com/forscht/namegen v1.0.1 github.com/getkin/kin-openapi v0.133.0 github.com/go-chi/chi/v5 v5.2.3 github.com/go-chi/cors v1.2.2 diff --git a/go.sum b/go.sum index 9cdfd2dea9..7290d85c22 100644 --- a/go.sum +++ b/go.sum @@ -1259,6 +1259,8 @@ github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSw github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= +github.com/forscht/namegen v1.0.1 h1:HipCEuyIKECsb1Yt68xaX7XTCDDrd+aDdEROoayY52I= +github.com/forscht/namegen v1.0.1/go.mod h1:Vnu8EC4fPGwaP7ogYi7kTPvRQHAUZUe1i1wN1RlgzII= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= diff --git a/openmeter/app/stripe/adapter/customer.go b/openmeter/app/stripe/adapter/customer.go index a13c647d7f..2b9ef2cd2f 100644 --- a/openmeter/app/stripe/adapter/customer.go +++ b/openmeter/app/stripe/adapter/customer.go @@ -129,12 +129,19 @@ func (a *adapter) UpsertStripeCustomerData(ctx context.Context, input appstripee SetStripeCustomerID(input.StripeCustomerID). SetNillableStripeDefaultPaymentMethodID(input.StripeDefaultPaymentMethodID). // Upsert - OnConflictColumns(appstripecustomerdb.FieldNamespace, appstripecustomerdb.FieldAppID, appstripecustomerdb.FieldCustomerID, appstripecustomerdb.FieldStripeCustomerID). + OnConflictColumns(appstripecustomerdb.FieldNamespace, appstripecustomerdb.FieldAppID, appstripecustomerdb.FieldCustomerID). UpdateStripeCustomerID(). UpdateStripeDefaultPaymentMethodID(). Exec(ctx) if err != nil { if entdb.IsConstraintError(err) { + a.logger.WarnContext(ctx, "failed to upsert app stripe customer data", + "error", err, + "app_id", input.AppID.ID, + "customer_id", input.CustomerID.ID, + "stripe_customer_id", input.StripeCustomerID, + ) + return nil, app.NewAppCustomerPreConditionError( input.AppID, app.AppTypeStripe, diff --git a/openmeter/billing/adapter/invoicelinediff.go b/openmeter/billing/adapter/invoicelinediff.go index 01ef2b28e9..a84b928133 100644 --- a/openmeter/billing/adapter/invoicelinediff.go +++ b/openmeter/billing/adapter/invoicelinediff.go @@ -196,11 +196,6 @@ func diffInvoiceLines(lines []*billing.Line) (*invoiceLineDiff, error) { // Let's figure out what we need to do about child lines for _, childUpdate := range childUpdates { - // If the children are not present, we don't need to do anything (a.k.a. do not touch) - if len(childUpdate.Children) == 0 { - continue - } - if err := getChildrenActions( childUpdate.DBState.Children, childUpdate.Children, diff --git a/openmeter/billing/worker/subscription/sync_test.go b/openmeter/billing/worker/subscription/sync_test.go index f0b8d3aa9c..cbf520cf5b 100644 --- a/openmeter/billing/worker/subscription/sync_test.go +++ b/openmeter/billing/worker/subscription/sync_test.go @@ -4500,13 +4500,12 @@ func (s *SubscriptionHandlerTestSuite) TestSyncronizeSubscriptionPeriodAlgorithm }, { Start: s.mustParseTime("2025-03-02T00:00:00Z"), - End: s.mustParseTime("2025-03-28T00:00:00Z"), // TODO: once we implement sticky recurrence (sticking to end of month) this should be 03-31 + End: s.mustParseTime("2025-03-31T00:00:00Z"), }, }, InvoiceAt: mo.Some([]time.Time{ s.mustParseTime("2025-01-31T00:00:00Z"), - // TODO: Once the period fix is there, this should be 03-31 s.mustParseTime("2025-03-02T00:00:00Z"), }), }, diff --git a/openmeter/credit/helper.go b/openmeter/credit/helper.go index 07d38c01ae..db12bd65f0 100644 --- a/openmeter/credit/helper.go +++ b/openmeter/credit/helper.go @@ -27,7 +27,7 @@ func (m *connector) GetLastValidSnapshotAt(ctx context.Context, owner models.Nam bal, err := m.BalanceSnapshotService.GetLatestValidAt(ctx, owner, at) if err != nil { - if _, ok := err.(*balance.NoSavedBalanceForOwnerError); ok { + if _, ok := lo.ErrorsAs[*balance.NoSavedBalanceForOwnerError](err); ok { // if no snapshot is found we have to calculate from start of time on all grants and usage m.Logger.Debug(fmt.Sprintf("no saved balance found for owner %s before %s, calculating from start of time", owner.ID, at)) diff --git a/openmeter/entitlement/adapter/entitlement_test.go b/openmeter/entitlement/adapter/entitlement_test.go index 8a2cbe73e9..6d4b8e21cb 100644 --- a/openmeter/entitlement/adapter/entitlement_test.go +++ b/openmeter/entitlement/adapter/entitlement_test.go @@ -469,6 +469,7 @@ func TestEntitlementLoadsSubjectAndCustomerAndPreservesAcrossTypedMapping(t *tes Interval: timeutil.RecurrencePeriodMonth, Anchor: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC), })), + IsSoftLimit: lo.ToPtr(true), }) require.NoError(t, err) diff --git a/openmeter/entitlement/metered/balance_test.go b/openmeter/entitlement/metered/balance_test.go index 7a2bf96969..89d60e3e01 100644 --- a/openmeter/entitlement/metered/balance_test.go +++ b/openmeter/entitlement/metered/balance_test.go @@ -1,7 +1,6 @@ package meteredentitlement_test import ( - "context" "testing" "time" @@ -11,6 +10,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/credit/balance" "github.com/openmeterio/openmeter/openmeter/credit/grant" + dbbalancesnapshot "github.com/openmeterio/openmeter/openmeter/ent/db/balancesnapshot" "github.com/openmeterio/openmeter/openmeter/entitlement" meteredentitlement "github.com/openmeterio/openmeter/openmeter/entitlement/metered" "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" @@ -48,7 +48,7 @@ func TestGetEntitlementBalance(t *testing.T) { FeatureID: feature.ID, FeatureKey: feature.Key, UsageAttribution: usageAttribution, - MeasureUsageFrom: convert.ToPointer(testutils.GetRFC3339Time(t, "1024-03-01T00:00:00Z")), // old, override in tests + MeasureUsageFrom: convert.ToPointer(testutils.GetRFC3339Time(t, "1983-03-01T00:00:00Z")), // old, override in tests EntitlementType: entitlement.EntitlementTypeMetered, IssueAfterReset: convert.ToPointer(0.0), IsSoftLimit: convert.ToPointer(false), @@ -59,11 +59,21 @@ func TestGetEntitlementBalance(t *testing.T) { } currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(time.Now()) - assert.NoError(t, err) + require.NoError(t, err) input.CurrentUsagePeriod = ¤tUsagePeriod return input } + connector, deps := setupConnector(t) + defer deps.Teardown() + + // create featute in db + feat, err := deps.featureRepo.CreateFeature(t.Context(), exampleFeature) + require.NoError(t, err) + + _, err = deps.dbClient.Subject.Create().SetNamespace(namespace).SetKey("subject1").Save(t.Context()) + require.NoError(t, err) + tt := []struct { name string run func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) @@ -71,27 +81,25 @@ func TestGetEntitlementBalance(t *testing.T) { { name: "Should ignore usage before start of measurement", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime // create entitlement in db entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startTime.Add(-time.Minute)) entBalance, err := connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, startTime.Add(time.Hour)) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, entBalance.UsageInPeriod) assert.Equal(t, 0.0, entBalance.Overage) @@ -100,19 +108,17 @@ func TestGetEntitlementBalance(t *testing.T) { { name: "Should return overage if there's no active grant", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, getEntitlement(t, feature, cust.GetUsageAttribution())) - assert.NoError(t, err) + entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, getEntitlement(t, feat, cust.GetUsageAttribution())) + require.NoError(t, err) queryTime := startTime.Add(time.Hour) @@ -121,7 +127,7 @@ func TestGetEntitlementBalance(t *testing.T) { deps.streamingConnector.AddSimpleEvent(meterSlug, 100, queryTime.Add(time.Minute)) entBalance, err := connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, queryTime) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 100.0, entBalance.UsageInPeriod) assert.Equal(t, 100.0, entBalance.Overage) @@ -130,22 +136,20 @@ func TestGetEntitlementBalance(t *testing.T) { { name: "Should return overage until very first grant after reset", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // add dummy usage so meter is found deps.streamingConnector.AddSimpleEvent(meterSlug, 0, startTime.Add(-time.Minute)) @@ -158,7 +162,7 @@ func TestGetEntitlementBalance(t *testing.T) { At: resetTime, }, ) - assert.NoError(t, err) + require.NoError(t, err) // usage on ledger that will be deducted deps.streamingConnector.AddSimpleEvent(meterSlug, 600, resetTime.Add(time.Minute)) @@ -167,7 +171,7 @@ func TestGetEntitlementBalance(t *testing.T) { queryTime := resetTime.Add(time.Hour) entBalance, err := connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}, queryTime) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 600.0, entBalance.UsageInPeriod) assert.Equal(t, 600.0, entBalance.Overage) assert.Equal(t, 0.0, entBalance.Balance) @@ -176,21 +180,19 @@ func TestGetEntitlementBalance(t *testing.T) { { name: "Should return correct usage and balance", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) queryTime := startTime.Add(time.Hour) @@ -207,7 +209,7 @@ func TestGetEntitlementBalance(t *testing.T) { EffectiveAt: startTime, ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ OwnerID: entitlement.ID, @@ -217,10 +219,10 @@ func TestGetEntitlementBalance(t *testing.T) { EffectiveAt: queryTime.Add(time.Hour), ExpiresAt: queryTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) entBalance, err := connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, queryTime) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 100.0, entBalance.UsageInPeriod) assert.Equal(t, 900.0, entBalance.Balance) @@ -230,7 +232,7 @@ func TestGetEntitlementBalance(t *testing.T) { { name: "Should save new snapshot", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) clock.SetTime(startTime) defer clock.ResetTime() @@ -238,22 +240,20 @@ func TestGetEntitlementBalance(t *testing.T) { // register usage so meter is found deps.streamingConnector.AddSimpleEvent(meterSlug, 1, startTime.AddDate(5, 0, 0)) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime inp.UsagePeriod = lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ Interval: timeutil.RecurrencePeriodDaily, // we need a faster recurrence as we wont save snapshots in the current usage period Anchor: inp.UsagePeriod.GetValue().Anchor, })) entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) queryTime := startTime.AddDate(0, 0, 9) // longer than grace period for saving snapshots @@ -272,7 +272,7 @@ func TestGetEntitlementBalance(t *testing.T) { EffectiveAt: startTime, ExpiresAt: startTime.AddDate(0, 0, 10), }) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature deps.streamingConnector.AddSimpleEvent(meterSlug, 200, g1.EffectiveAt.Add(time.Minute)) @@ -293,13 +293,13 @@ func TestGetEntitlementBalance(t *testing.T) { At: g1.EffectiveAt, }, }) - assert.NoError(t, err) + require.NoError(t, err) clock.SetTime(queryTime) // get last vaild snapshot snap1, err := deps.balanceSnapshotService.GetLatestValidAt(ctx, owner, queryTime) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, balance.Snapshot{ Usage: balance.SnapshottedUsage{ Since: startTime, @@ -313,7 +313,7 @@ func TestGetEntitlementBalance(t *testing.T) { }, snap1) entBalance, err := connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, queryTime) - assert.NoError(t, err) + require.NoError(t, err) // validate balance calc for good measure assert.Equal(t, 0.0, entBalance.UsageInPeriod) @@ -321,7 +321,7 @@ func TestGetEntitlementBalance(t *testing.T) { assert.Equal(t, 0.0, entBalance.Overage) snap2, err := deps.balanceSnapshotService.GetLatestValidAt(ctx, owner, queryTime) - assert.NoError(t, err) + require.NoError(t, err) // check snapshots assert.NotEqual(t, snap1.At, snap2.At) @@ -341,7 +341,7 @@ func TestGetEntitlementBalance(t *testing.T) { { name: "Should save snapshot with correct usage data for period", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() // TODO: let's revert this once we have fixed the period calculation // startTime := getAnchor(t) startTime := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC) @@ -351,22 +351,20 @@ func TestGetEntitlementBalance(t *testing.T) { // register usage so meter is found deps.streamingConnector.AddSimpleEvent(meterSlug, 1, startTime.AddDate(5, 0, 0)) // far in future - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime inp.UsagePeriod = lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ Interval: timeutil.RecurrencePeriodMonth, Anchor: inp.UsagePeriod.GetValue().Anchor, })) entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) queryTime := startTime.AddDate(0, 1, 9) // will fall in next usageperiod @@ -385,7 +383,7 @@ func TestGetEntitlementBalance(t *testing.T) { EffectiveAt: startTime, ExpiresAt: startTime.AddDate(1, 0, 0), // far future }) - assert.NoError(t, err) + require.NoError(t, err) // add a balance snapshot err = deps.balanceSnapshotService.Save( @@ -403,7 +401,7 @@ func TestGetEntitlementBalance(t *testing.T) { At: g1.EffectiveAt, }, }) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature in first period deps.streamingConnector.AddSimpleEvent(meterSlug, 200, g1.EffectiveAt.Add(time.Minute)) @@ -422,7 +420,7 @@ func TestGetEntitlementBalance(t *testing.T) { EffectiveAt: startTime.AddDate(0, 1, 2), // After the second round of usage is in ExpiresAt: startTime.AddDate(1, 0, 0), }) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature in second period after grant deps.streamingConnector.AddSimpleEvent(meterSlug, 200, startTime.AddDate(0, 1, 3)) @@ -431,7 +429,7 @@ func TestGetEntitlementBalance(t *testing.T) { // get last vaild snapshot snap1, err := deps.balanceSnapshotService.GetLatestValidAt(ctx, owner, queryTime) - assert.NoError(t, err) + require.NoError(t, err) // Should be the first and only snapshot we created assert.Equal(t, balance.Snapshot{ Usage: balance.SnapshottedUsage{ @@ -446,7 +444,7 @@ func TestGetEntitlementBalance(t *testing.T) { }, snap1) entBalance, err := connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, queryTime) - assert.NoError(t, err) + require.NoError(t, err) // validate balance calc for good measure assert.Equal(t, 400.0, entBalance.UsageInPeriod) @@ -454,7 +452,7 @@ func TestGetEntitlementBalance(t *testing.T) { assert.Equal(t, 0.0, entBalance.Overage) snap2, err := deps.balanceSnapshotService.GetLatestValidAt(ctx, owner, queryTime) - assert.NoError(t, err) + require.NoError(t, err) // check snapshots assert.NotEqual(t, snap1.At, snap2.At) @@ -475,27 +473,25 @@ func TestGetEntitlementBalance(t *testing.T) { { name: "Should not save the same snapshot over and over again", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) clock.SetTime(startTime) defer clock.ResetTime() - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime inp.UsagePeriod = lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ Interval: timeutil.RecurrencePeriodDaily, // we need a faster recurrence as we wont save snapshots in the current usage period Anchor: inp.UsagePeriod.GetValue().Anchor, })) entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) queryTime := startTime.AddDate(0, 0, 10) // longer than grace period for saving snapshots @@ -514,7 +510,7 @@ func TestGetEntitlementBalance(t *testing.T) { EffectiveAt: startTime, ExpiresAt: startTime.AddDate(0, 5, 0), }) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature deps.streamingConnector.AddSimpleEvent(meterSlug, 200, g1.EffectiveAt.Add(time.Minute*5)) @@ -531,16 +527,16 @@ func TestGetEntitlementBalance(t *testing.T) { At: g1.EffectiveAt, }, }) - assert.NoError(t, err) + require.NoError(t, err) // get last vaild snapshot snap1, err := deps.balanceSnapshotService.GetLatestValidAt(ctx, owner, queryTime) - assert.NoError(t, err) + require.NoError(t, err) clock.SetTime(queryTime) entBalance, err := connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, queryTime) - assert.NoError(t, err) + require.NoError(t, err) // validate balance calc for good measure assert.Equal(t, 0.0, entBalance.UsageInPeriod) @@ -548,7 +544,7 @@ func TestGetEntitlementBalance(t *testing.T) { assert.Equal(t, 0.0, entBalance.Overage) snap2, err := deps.balanceSnapshotService.GetLatestValidAt(ctx, owner, queryTime) - assert.NoError(t, err) + require.NoError(t, err) // check snapshots assert.NotEqual(t, snap1.At, snap2.At) @@ -559,7 +555,7 @@ func TestGetEntitlementBalance(t *testing.T) { // run the calc again entBalance, err = connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, queryTime) - assert.NoError(t, err) + require.NoError(t, err) // validate balance calc for good measure assert.Equal(t, 0.0, entBalance.UsageInPeriod) @@ -567,21 +563,20 @@ func TestGetEntitlementBalance(t *testing.T) { assert.Equal(t, 0.0, entBalance.Overage) // FIXME: we shouldn't check things that the contract is unable to tell us - snaps, err := deps.dbClient.BalanceSnapshot.Query().All(ctx) - assert.NoError(t, err) + snaps, err := deps.dbClient.BalanceSnapshot. + Query(). + Where(dbbalancesnapshot.OwnerID(entitlement.ID)). + All(ctx) + require.NoError(t, err) assert.Len(t, snaps, 2) // one for the initial and one we made last time }, }, } for _, tc := range tt { - tc := tc t.Run(tc.name, func(t *testing.T) { - t.Parallel() - connector, deps := setupConnector(t) - defer deps.Teardown() - ctx := context.Background() - _, _ = deps.dbClient.Subject.Create().SetNamespace(namespace).SetKey("subject1").Save(ctx) + deps.streamingConnector.Reset() + tc.run(t, connector, deps) }) } @@ -606,7 +601,7 @@ func TestGetEntitlementHistory(t *testing.T) { FeatureID: feature.ID, FeatureKey: feature.Key, UsageAttribution: usageAttribution, - MeasureUsageFrom: convert.ToPointer(testutils.GetRFC3339Time(t, "1024-03-01T00:00:00Z")), // old, override in tests + MeasureUsageFrom: convert.ToPointer(testutils.GetRFC3339Time(t, "1983-01-05T00:00:00Z")), // old, override in tests EntitlementType: entitlement.EntitlementTypeMetered, IssueAfterReset: convert.ToPointer(0.0), IsSoftLimit: convert.ToPointer(false), @@ -617,11 +612,20 @@ func TestGetEntitlementHistory(t *testing.T) { } currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(time.Now()) - assert.NoError(t, err) + require.NoError(t, err) input.CurrentUsagePeriod = ¤tUsagePeriod return input } + connector, deps := setupConnector(t) + defer deps.Teardown() + + _, _ = deps.dbClient.Subject.Create().SetNamespace(namespace).SetKey("subject1").Save(t.Context()) + + // create featute in db + feat, err := deps.featureRepo.CreateFeature(t.Context(), exampleFeature) + require.NoError(t, err) + tt := []struct { name string run func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) @@ -629,21 +633,19 @@ func TestGetEntitlementHistory(t *testing.T) { { name: "Should return windowed history", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) queryTime := startTime.Add(time.Hour * 12) @@ -665,7 +667,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startTime, ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // grant falling on 3h window _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -676,7 +678,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startTime.Add(time.Hour * 3), ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // grant between windows _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -687,7 +689,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startTime.Add(time.Hour * 5).Add(time.Minute * 30), ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) t.Run("Should return correct value for the entire period", func(t *testing.T) { windowedHistory, burndownHistory, err := connector.GetEntitlementBalanceHistory(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}, meteredentitlement.BalanceHistoryParams{ @@ -778,7 +780,7 @@ func TestGetEntitlementHistory(t *testing.T) { WindowTimeZone: *time.UTC, WindowSize: meteredentitlement.WindowSizeHour, }) - assert.NoError(t, err) + require.NoError(t, err) // check returned burndownhistory segments := burndownHistory.Segments() @@ -817,21 +819,19 @@ func TestGetEntitlementHistory(t *testing.T) { { name: "If start time is not specified we are defaulting to the last reset", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // grant at start _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -842,7 +842,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startTime, ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startTime.Add(time.Minute)) @@ -856,7 +856,7 @@ func TestGetEntitlementHistory(t *testing.T) { RetainAnchor: true, }, ) - assert.NoError(t, err) + require.NoError(t, err) queryTime := startTime.Add(time.Hour * 12) @@ -876,14 +876,14 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: resetTime, ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) windowedHistory, burndownHistory, err := connector.GetEntitlementBalanceHistory(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}, meteredentitlement.BalanceHistoryParams{ To: &queryTime, WindowTimeZone: *time.UTC, WindowSize: meteredentitlement.WindowSizeHour, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, windowedHistory, 10) @@ -915,21 +915,19 @@ func TestGetEntitlementHistory(t *testing.T) { { name: "If start time is not specified we are defaulting to NEXT WINDOW after start of measurement if there were no manual resets", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // grant at start _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -940,7 +938,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startTime, ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // grant again later _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -951,7 +949,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startTime.Add(time.Hour * 2), ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startTime.Add(time.Minute)) @@ -970,7 +968,7 @@ func TestGetEntitlementHistory(t *testing.T) { WindowTimeZone: *time.UTC, WindowSize: meteredentitlement.WindowSizeHour, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, windowedHistory, 12) @@ -1007,22 +1005,20 @@ func TestGetEntitlementHistory(t *testing.T) { { name: "If start time is not specified we are defaulting to NEXT WINDOWED after start of measurement if there were no manual resets and measurement starts not at a window boundary", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) startOfMeasurement := startTime.Add(time.Minute * 29) inp.MeasureUsageFrom = lo.ToPtr(startOfMeasurement) ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // grant at start _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -1033,7 +1029,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startOfMeasurement, ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // grant again later _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -1044,7 +1040,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startTime.Add(time.Hour * 2), ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startOfMeasurement.Add(time.Minute)) @@ -1063,7 +1059,7 @@ func TestGetEntitlementHistory(t *testing.T) { WindowTimeZone: *time.UTC, WindowSize: meteredentitlement.WindowSizeHour, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, windowedHistory, 11) @@ -1100,21 +1096,19 @@ func TestGetEntitlementHistory(t *testing.T) { { name: "Should return history if WINDOWSIZE and entitlements events dont align", run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // We'll query with WINDOWSIZE_DAY, so lets use 12h precision for the different events @@ -1127,7 +1121,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: startTime, ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // register usage for meter & feature deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startTime.Add(time.Hour)) @@ -1141,7 +1135,7 @@ func TestGetEntitlementHistory(t *testing.T) { RetainAnchor: true, }, ) - assert.NoError(t, err) + require.NoError(t, err) queryTime := startTime.AddDate(0, 0, 2) @@ -1159,7 +1153,7 @@ func TestGetEntitlementHistory(t *testing.T) { EffectiveAt: resetTime, ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) windowedHistory, burndownHistory, err := connector.GetEntitlementBalanceHistory(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}, meteredentitlement.BalanceHistoryParams{ To: &queryTime, @@ -1167,7 +1161,7 @@ func TestGetEntitlementHistory(t *testing.T) { WindowTimeZone: *time.UTC, WindowSize: meteredentitlement.WindowSizeDay, }) - assert.NoError(t, err) + require.NoError(t, err) // check returned burndownhistory segments := burndownHistory.Segments() @@ -1186,13 +1180,8 @@ func TestGetEntitlementHistory(t *testing.T) { } for _, tc := range tt { - tc := tc t.Run(tc.name, func(t *testing.T) { - t.Parallel() - connector, deps := setupConnector(t) - defer deps.Teardown() - ctx := context.Background() - _, _ = deps.dbClient.Subject.Create().SetNamespace(namespace).SetKey("subject1").Save(ctx) + deps.streamingConnector.Reset() tc.run(t, connector, deps) }) } diff --git a/openmeter/entitlement/metered/grant_owner_adapter_test.go b/openmeter/entitlement/metered/grant_owner_adapter_test.go index cf8bb556be..b6ffb910ac 100644 --- a/openmeter/entitlement/metered/grant_owner_adapter_test.go +++ b/openmeter/entitlement/metered/grant_owner_adapter_test.go @@ -36,7 +36,10 @@ func TestEntitlementGrantOwnerAdapter(t *testing.T) { }) require.NoError(t, err) - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + randName := testutils.NameGenerator.Generate() + + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) return f, cust } @@ -643,7 +646,10 @@ func TestEntitlementGrantOwnerAdapter(t *testing.T) { }) require.NoError(t, err) - c := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + randName := testutils.NameGenerator.Generate() + + // create customer and subject + c := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create entitlement diff --git a/openmeter/entitlement/metered/lateevents_test.go b/openmeter/entitlement/metered/lateevents_test.go index 91fdaf4e05..0a63d12ab7 100644 --- a/openmeter/entitlement/metered/lateevents_test.go +++ b/openmeter/entitlement/metered/lateevents_test.go @@ -238,8 +238,10 @@ func TestGetEntitlementBalanceConsistency(t *testing.T) { feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() + // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db inp := getEntitlement(t, feature, cust.GetUsageAttribution()) diff --git a/openmeter/entitlement/metered/reset_test.go b/openmeter/entitlement/metered/reset_test.go index e9b8be4b2c..b3930e786c 100644 --- a/openmeter/entitlement/metered/reset_test.go +++ b/openmeter/entitlement/metered/reset_test.go @@ -41,7 +41,7 @@ func TestResetEntitlementUsage(t *testing.T) { FeatureID: feature.ID, FeatureKey: feature.Key, UsageAttribution: usageAttribution, - MeasureUsageFrom: convert.ToPointer(testutils.GetRFC3339Time(t, "1024-03-01T00:00:00Z")), // old, override in tests + MeasureUsageFrom: convert.ToPointer(testutils.GetRFC3339Time(t, "1983-12-24T00:00:00Z")), // old, override in tests EntitlementType: entitlement.EntitlementTypeMetered, IssueAfterReset: convert.ToPointer(0.0), IsSoftLimit: convert.ToPointer(false), @@ -52,11 +52,19 @@ func TestResetEntitlementUsage(t *testing.T) { } currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(time.Now()) // This should be calculated properly when testing batch resets - assert.NoError(t, err) + require.NoError(t, err) input.CurrentUsagePeriod = ¤tUsagePeriod return input } + connector, deps := setupConnector(t) + defer deps.Teardown() + + // create featute in db + feat, err := deps.featureRepo.CreateFeature(t.Context(), exampleFeature) + require.NoError(t, err) + require.NotEmpty(t, feat) + tt := []struct { name string run func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) @@ -69,28 +77,26 @@ func TestResetEntitlementUsage(t *testing.T) { resetTime := startTime.Add(time.Hour * 3) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime - entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) + require.NoError(t, err) // some usage on ledger, should be inconsequential deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startTime.Add(time.Minute)) startingBalance, err := connector.ResetEntitlementUsage(ctx, - models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, + models.NamespacedID{Namespace: namespace, ID: ent.ID}, meteredentitlement.ResetEntitlementUsageParams{ At: resetTime, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, startingBalance.UsageInPeriod) // cannot be usage assert.Equal(t, 0.0, startingBalance.Balance) // no balance as there are no grants @@ -103,18 +109,17 @@ func TestResetEntitlementUsage(t *testing.T) { ctx := context.Background() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime - entitlement, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) + require.NoError(t, err) + assert.NotNil(t, ent) // some usage on ledger, should be inconsequential deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startTime.Add(time.Minute)) @@ -122,7 +127,7 @@ func TestResetEntitlementUsage(t *testing.T) { // resetTime before start of measurement resetTime := startTime.Add(-time.Hour) _, err = connector.ResetEntitlementUsage(ctx, - models.NamespacedID{Namespace: namespace, ID: entitlement.ID}, + models.NamespacedID{Namespace: namespace, ID: ent.ID}, meteredentitlement.ResetEntitlementUsageParams{ At: resetTime, }) @@ -134,19 +139,16 @@ func TestResetEntitlementUsage(t *testing.T) { run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { ctx := context.Background() startTime := getAnchor(t) - - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // some usage on ledger, should be inconsequential deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startTime.Add(time.Minute)) @@ -160,7 +162,7 @@ func TestResetEntitlementUsage(t *testing.T) { EntitlementID: ent.ID, UsagePeriodInterval: ent.UsagePeriod.GetOriginalValueAsUsagePeriodInput().GetValue().Interval.ISOString(), }) - assert.NoError(t, err) + require.NoError(t, err) // resetTime before prior reset time resetTime := priorResetTime.Add(-time.Minute) @@ -178,19 +180,16 @@ func TestResetEntitlementUsage(t *testing.T) { ctx := context.Background() now := time.Now().Truncate(time.Minute) aDayAgo := now.Add(-time.Hour * 24) - - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &aDayAgo ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // some usage on ledger, should be inconsequential deps.streamingConnector.AddSimpleEvent(meterSlug, 100, aDayAgo.Add(time.Minute)) @@ -211,18 +210,16 @@ func TestResetEntitlementUsage(t *testing.T) { ctx := context.Background() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // we force snapshot creation the intended way by checking the balance @@ -235,7 +232,7 @@ func TestResetEntitlementUsage(t *testing.T) { EffectiveAt: startTime.Add(time.Hour * 2), ExpiresAt: startTime.AddDate(0, 0, 3), }) - assert.NoError(t, err) + require.NoError(t, err) // some usage on ledger, should be inconsequential deps.streamingConnector.AddSimpleEvent(meterSlug, 100, startTime.Add(time.Minute)) @@ -288,18 +285,16 @@ func TestResetEntitlementUsage(t *testing.T) { ctx := context.Background() startTime := getAnchor(t) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // issue grants g1, err := deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -359,16 +354,13 @@ func TestResetEntitlementUsage(t *testing.T) { run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { ctx := context.Background() startTime := getAnchor(t) - - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) assert.NoError(t, err) @@ -434,19 +426,16 @@ func TestResetEntitlementUsage(t *testing.T) { run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { ctx := context.Background() startTime := getAnchor(t) - - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // issue grants g1, err := deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -458,7 +447,7 @@ func TestResetEntitlementUsage(t *testing.T) { ExpiresAt: startTime.AddDate(0, 0, 3), ResetMaxRollover: 1000, // full amount can be rolled over }) - assert.NoError(t, err) + require.NoError(t, err) g2, err := deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ OwnerID: ent.ID, @@ -471,7 +460,7 @@ func TestResetEntitlementUsage(t *testing.T) { ResetMaxRollover: 500, ResetMinRollover: 500, }) - assert.NoError(t, err) + require.NoError(t, err) // usage on ledger that will cause overage deps.streamingConnector.AddSimpleEvent(meterSlug, 2600, startTime.Add(time.Minute)) @@ -485,7 +474,7 @@ func TestResetEntitlementUsage(t *testing.T) { PreserveOverage: convert.ToPointer(true), }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, balanceAfterReset.UsageInPeriod) // 0 usage right after reset assert.Equal(t, 0.0, balanceAfterReset.Balance) // (1000 + 1000 - 2600) + 500 = -100 => 0 assert.Equal(t, 100.0, balanceAfterReset.Overage) // Overage is carried to new period @@ -496,7 +485,7 @@ func TestResetEntitlementUsage(t *testing.T) { Namespace: namespace, ID: ent.ID, }, resetTime) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, balance.Map{ g1.ID: 0, @@ -509,22 +498,19 @@ func TestResetEntitlementUsage(t *testing.T) { run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { ctx := context.Background() startTime := getAnchor(t) - - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) ent, err = deps.entitlementRepo.GetEntitlement(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, startTime.Format(time.RFC3339), ent.LastReset.Format(time.RFC3339)) deps.streamingConnector.AddSimpleEvent(meterSlug, 600, startTime.Add(time.Minute)) @@ -536,11 +522,11 @@ func TestResetEntitlementUsage(t *testing.T) { meteredentitlement.ResetEntitlementUsageParams{ At: resetTime, }) - assert.NoError(t, err) + require.NoError(t, err) // validate that lastReset time is properly set ent, err = deps.entitlementRepo.GetEntitlement(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, resetTime.Format(time.RFC3339), ent.LastReset.Format(time.RFC3339)) }, }, @@ -549,19 +535,16 @@ func TestResetEntitlementUsage(t *testing.T) { run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { ctx := context.Background() startTime := getAnchor(t) - - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // issue grants g1, err := deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -573,7 +556,7 @@ func TestResetEntitlementUsage(t *testing.T) { ExpiresAt: startTime.AddDate(0, 0, 3), ResetMaxRollover: 1000, // full amount can be rolled over }) - assert.NoError(t, err) + require.NoError(t, err) g2, err := deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ OwnerID: ent.ID, @@ -584,7 +567,7 @@ func TestResetEntitlementUsage(t *testing.T) { ExpiresAt: startTime.AddDate(0, 0, 3), ResetMaxRollover: 100, // full amount can be rolled over }) - assert.NoError(t, err) + require.NoError(t, err) // usage on ledger that will be deducted from g1 deps.streamingConnector.AddSimpleEvent(meterSlug, 600, startTime.Add(time.Minute)) @@ -597,7 +580,7 @@ func TestResetEntitlementUsage(t *testing.T) { At: resetTime1, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, balanceAfterReset.UsageInPeriod) // 0 usage right after reset assert.Equal(t, 500.0, balanceAfterReset.Balance) // 1000 - 600 = 400 rolled over + MAX(1000 - 0, 100)=100 = 500 assert.Equal(t, 0.0, balanceAfterReset.Overage) // no overage @@ -608,7 +591,7 @@ func TestResetEntitlementUsage(t *testing.T) { Namespace: namespace, ID: ent.ID, }, resetTime1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, balance.Map{ g1.ID: 400, @@ -625,7 +608,7 @@ func TestResetEntitlementUsage(t *testing.T) { ExpiresAt: resetTime1.AddDate(0, 0, 3), ResetMaxRollover: 1000, // full amount can be rolled over }) - assert.NoError(t, err) + require.NoError(t, err) // add usage after reset 1 deps.streamingConnector.AddSimpleEvent(meterSlug, 300, resetTime1.Add(time.Minute*10)) @@ -638,7 +621,7 @@ func TestResetEntitlementUsage(t *testing.T) { At: resetTime2, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, balanceAfterReset.UsageInPeriod) // 0 usage right after reset assert.Equal(t, 1200.0, balanceAfterReset.Balance) // 1000 + 500 - 300 = 1200 assert.Equal(t, 0.0, balanceAfterReset.Overage) // no overage @@ -649,7 +632,7 @@ func TestResetEntitlementUsage(t *testing.T) { Namespace: namespace, ID: ent.ID, }, resetTime2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, balance.Map{ g1.ID: 100, @@ -667,19 +650,17 @@ func TestResetEntitlementUsage(t *testing.T) { // add 0 usage so meter is found in mock deps.streamingConnector.AddSimpleEvent(meterSlug, 0, startTime) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // issue grants _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -691,7 +672,7 @@ func TestResetEntitlementUsage(t *testing.T) { ExpiresAt: startTime.AddDate(0, 0, 3), ResetMaxRollover: 0, // full amount can be rolled over }) - assert.NoError(t, err) + require.NoError(t, err) // do a reset resetTime := startTime.Add(time.Hour * 5) @@ -702,7 +683,7 @@ func TestResetEntitlementUsage(t *testing.T) { }) // assert balance after reset is 0 for grant - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, balanceAfterReset.UsageInPeriod) // 0 usage right after reset assert.Equal(t, 0.0, balanceAfterReset.Balance) // 1000 - 1000 = 0 @@ -716,18 +697,18 @@ func TestResetEntitlementUsage(t *testing.T) { ExpiresAt: resetTime.AddDate(0, 0, 3), ResetMaxRollover: 1000, // full amount can be rolled over }) - assert.NoError(t, err) + require.NoError(t, err) // fetch balance for reset & grant, balance should be full grant amount balanceAfterReset, err = connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}, resetTime) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, balanceAfterReset.UsageInPeriod) // 0 usage right after reset assert.Equal(t, g2.Amount, balanceAfterReset.Balance) // 1000 - 0 = 1000 // fetch balance for AFTER reset & grant, balance should be full grant amount balanceAfterReset, err = connector.GetEntitlementBalance(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}, resetTime.Add(time.Minute)) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, balanceAfterReset.UsageInPeriod) // 0 usage right after reset assert.Equal(t, g2.Amount, balanceAfterReset.Balance) // 1000 - 0 = 1000 @@ -743,18 +724,16 @@ func TestResetEntitlementUsage(t *testing.T) { // add 0 usage so meter is found in mock deps.streamingConnector.AddSimpleEvent(meterSlug, 0, startTime) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // issue grants _, err = deps.grantRepo.CreateGrant(ctx, grant.RepoCreateInput{ @@ -766,7 +745,7 @@ func TestResetEntitlementUsage(t *testing.T) { ExpiresAt: resetTime, ResetMaxRollover: 1000, // full amount can be rolled over }) - assert.NoError(t, err) + require.NoError(t, err) // do a reset balanceAfterReset, err := connector.ResetEntitlementUsage(ctx, @@ -776,7 +755,7 @@ func TestResetEntitlementUsage(t *testing.T) { }) // assert balance after reset is 0 for grant - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0.0, balanceAfterReset.UsageInPeriod) // 0 usage right after reset assert.Equal(t, 0.0, balanceAfterReset.Balance) // Grant expires at reset time so we should see no balance }, @@ -787,15 +766,13 @@ func TestResetEntitlementUsage(t *testing.T) { ctx := context.Background() startTime := time.Now().Add(-12 * time.Hour).Truncate(time.Minute) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime anchor := startTime.Add(time.Hour) inp.UsagePeriod = lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ @@ -807,7 +784,7 @@ func TestResetEntitlementUsage(t *testing.T) { } ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) deps.streamingConnector.AddSimpleEvent(meterSlug, 600, startTime.Add(time.Minute)) @@ -819,9 +796,9 @@ func TestResetEntitlementUsage(t *testing.T) { RetainAnchor: true, }) - assert.NoError(t, err) + require.NoError(t, err) ent, err = deps.entitlementRepo.GetEntitlement(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}) - assert.NoError(t, err) + require.NoError(t, err) assertUsagePeriodInputsEquals(t, inp.UsagePeriod, ent.UsagePeriod.GetOriginalValueAsUsagePeriodInput()) }, }, @@ -831,15 +808,13 @@ func TestResetEntitlementUsage(t *testing.T) { ctx := context.Background() startTime := time.Now().Add(-12 * time.Hour).Truncate(time.Minute) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime anchor := startTime.Add(time.Hour) inp.UsagePeriod = lo.ToPtr(entitlement.NewStartingUsagePeriodInput(timeutil.Recurrence{ @@ -851,7 +826,7 @@ func TestResetEntitlementUsage(t *testing.T) { } ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) deps.streamingConnector.AddSimpleEvent(meterSlug, 600, startTime.Add(time.Minute)) @@ -862,12 +837,12 @@ func TestResetEntitlementUsage(t *testing.T) { At: resetTime, }) - assert.NoError(t, err) + require.NoError(t, err) ent, err = deps.entitlementRepo.GetEntitlement(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}) - assert.NoError(t, err) + require.NoError(t, err) uInpNow, _, err := ent.UsagePeriod.GetUsagePeriodInputAt(clock.Now()) - assert.NoError(t, err) + require.NoError(t, err) assertUsagePeriodInputsEquals(t, lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ Interval: timeutil.RecurrencePeriodDaily, @@ -880,16 +855,13 @@ func TestResetEntitlementUsage(t *testing.T) { run: func(t *testing.T, connector meteredentitlement.Connector, deps *dependencies) { ctx := context.Background() startTime := time.Now().Add(-12 * time.Hour).Truncate(time.Minute) - - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &startTime anchor := startTime.Add(time.Hour) inp.UsagePeriod = lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ @@ -901,7 +873,7 @@ func TestResetEntitlementUsage(t *testing.T) { } ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) deps.streamingConnector.AddSimpleEvent(meterSlug, 600, startTime.Add(time.Minute)) @@ -912,12 +884,12 @@ func TestResetEntitlementUsage(t *testing.T) { At: resetTime, }) - assert.NoError(t, err) + require.NoError(t, err) ent, err = deps.entitlementRepo.GetEntitlement(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}) - assert.NoError(t, err) + require.NoError(t, err) uInpNow, _, err := ent.UsagePeriod.GetUsagePeriodInputAt(clock.Now()) - assert.NoError(t, err) + require.NoError(t, err) assertUsagePeriodInputsEquals(t, lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ Interval: timeutil.RecurrencePeriodDaily, @@ -949,15 +921,13 @@ func TestResetEntitlementUsage(t *testing.T) { // Let's time-travel to the start time so resources have existed for a while clock.SetTime(entitlementTime) - // create featute in db - feature, err := deps.featureRepo.CreateFeature(ctx, exampleFeature) - assert.NoError(t, err) + randName := testutils.NameGenerator.Generate() // create customer and subject - cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1") + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // create entitlement in db - inp := getEntitlement(t, feature, cust.GetUsageAttribution()) + inp := getEntitlement(t, feat, cust.GetUsageAttribution()) inp.MeasureUsageFrom = &entitlementTime anchor := entitlementTime inp.UsagePeriod = lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ @@ -966,7 +936,7 @@ func TestResetEntitlementUsage(t *testing.T) { })) ent, err := deps.entitlementRepo.CreateEntitlement(ctx, inp) - assert.NoError(t, err) + require.NoError(t, err) // Let's time travel back to the current time clock.SetTime(startTime) @@ -978,13 +948,13 @@ func TestResetEntitlementUsage(t *testing.T) { RetainAnchor: false, }) - assert.NoError(t, err) + require.NoError(t, err) ent, err = deps.entitlementRepo.GetEntitlement(ctx, models.NamespacedID{Namespace: namespace, ID: ent.ID}) - assert.NoError(t, err) + require.NoError(t, err) uInpNow, _, err := ent.UsagePeriod.GetUsagePeriodInputAt(clock.Now()) - assert.NoError(t, err) + require.NoError(t, err) assertUsagePeriodInputsEquals(t, lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{ Interval: timeutil.RecurrencePeriodDaily, @@ -995,10 +965,8 @@ func TestResetEntitlementUsage(t *testing.T) { } for _, tc := range tt { - tc := tc t.Run(tc.name, func(t *testing.T) { - connector, deps := setupConnector(t) - defer deps.Teardown() + deps.streamingConnector.Reset() tc.run(t, connector, deps) }) } diff --git a/openmeter/entitlement/metered/utils_test.go b/openmeter/entitlement/metered/utils_test.go index f0ef907cbc..9d21bbc1da 100644 --- a/openmeter/entitlement/metered/utils_test.go +++ b/openmeter/entitlement/metered/utils_test.go @@ -201,23 +201,25 @@ func assertUsagePeriodInputsEquals(t *testing.T, expected, actual *entitlement.U assert.NotNil(t, expected, "expected is nil") assert.NotNil(t, actual, "actual is nil") assert.Equal(t, expected.GetValue().Interval, actual.GetValue().Interval, "periods do not match") - assert.Equal(t, expected.GetValue().Anchor.Format(time.RFC3339), actual.GetValue().Anchor.Format(time.RFC3339), "anchors do not match") + assert.Equal(t, expected.GetValue().Anchor.UTC().Format(time.RFC3339), actual.GetValue().Anchor.UTC().Format(time.RFC3339), "anchors do not match") } -func createCustomerAndSubject(t *testing.T, subjectService subject.Service, customerService customer.Adapter, ns string, subjectKey string) *customer.Customer { +func createCustomerAndSubject(t *testing.T, subjectService subject.Service, customerService customer.Adapter, ns, key, name string) *customer.Customer { t.Helper() - _, err := subjectService.Create(context.Background(), subject.CreateInput{ + + _, err := subjectService.Create(t.Context(), subject.CreateInput{ Namespace: ns, - Key: subjectKey, + Key: key, }) require.NoError(t, err) - cust, err := customerService.CreateCustomer(context.Background(), customer.CreateCustomerInput{ + cust, err := customerService.CreateCustomer(t.Context(), customer.CreateCustomerInput{ Namespace: ns, CustomerMutate: customer.CustomerMutate{ - Key: lo.ToPtr(subjectKey), + Key: lo.ToPtr(key), + Name: name, UsageAttribution: customer.CustomerUsageAttribution{ - SubjectKeys: []string{subjectKey}, + SubjectKeys: []string{key}, }, }, }) diff --git a/openmeter/entitlement/service/access_test.go b/openmeter/entitlement/service/access_test.go index d696e3ea20..f2810eccb1 100644 --- a/openmeter/entitlement/service/access_test.go +++ b/openmeter/entitlement/service/access_test.go @@ -1,7 +1,6 @@ package service_test import ( - "context" "fmt" "testing" "time" @@ -10,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/openmeterio/openmeter/openmeter/entitlement" + "github.com/openmeterio/openmeter/openmeter/meter" "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" "github.com/openmeterio/openmeter/openmeter/testutils" "github.com/openmeterio/openmeter/pkg/clock" @@ -17,44 +17,58 @@ import ( ) func TestGetAccess(t *testing.T) { - t.Run("Should return empty access if no entitlements are found", func(t *testing.T) { - conn, deps := setupDependecies(t) - defer deps.Teardown() + conn, deps := setupDependecies(t) + defer deps.Teardown() - access, err := conn.GetAccess(context.Background(), "test", "test") + t.Run("Should return empty access if no entitlements are found", func(t *testing.T) { + access, err := conn.GetAccess(t.Context(), "test", "test") require.NoError(t, err) require.Equal(t, access, entitlement.Access{}) }) t.Run("Should return access for a single entitlement", func(t *testing.T) { - conn, deps := setupDependecies(t) - defer deps.Teardown() + namespace := "ns1" now := testutils.GetRFC3339Time(t, "2025-01-01T00:00:00Z") clock.SetTime(now) defer clock.ResetTime() - subjectKey := "test" - featureKey := "test" - ns := "ns1" + mtr, err := deps.meterService.CreateMeter(t.Context(), meter.CreateMeterInput{ + Namespace: namespace, + Name: "Meter 1", + Key: "meter1", + Description: nil, + Aggregation: meter.MeterAggregationSum, + EventType: "test", + EventFrom: nil, + ValueProperty: lo.ToPtr("$.value"), + GroupBy: nil, + }) + require.NoError(t, err) + require.NotNil(t, mtr) // First, create the subject and the customer - cust := createCustomerAndSubject(t, deps, ns, subjectKey) + randName := testutils.NameGenerator.Generate() + + featureKey := randName.Key + + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Then set up a feature and an entitlement - feat, err := deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{ - Key: featureKey, - Name: "test", - Namespace: ns, - MeterSlug: lo.ToPtr("meter1"), + feat, err := deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ + Key: randName.Key, + Name: randName.Name, + Namespace: namespace, + MeterSlug: lo.ToPtr(mtr.Key), }) require.NoError(t, err) require.NotNil(t, feat) // Let's create a bool entitlement - ent, err := conn.CreateEntitlement(context.Background(), entitlement.CreateEntitlementInputs{ - Namespace: ns, + ent, err := conn.CreateEntitlement(t.Context(), entitlement.CreateEntitlementInputs{ + Namespace: namespace, UsageAttribution: cust.GetUsageAttribution(), FeatureKey: &featureKey, FeatureID: &feat.ID, @@ -67,7 +81,7 @@ func TestGetAccess(t *testing.T) { clock.SetTime(clock.Now().Add(time.Hour)) // Let's get the access - access, err := conn.GetAccess(context.Background(), ns, cust.ID) + access, err := conn.GetAccess(t.Context(), namespace, cust.ID) require.NoError(t, err) require.Len(t, access.Entitlements, 1) require.NotNil(t, access.Entitlements[featureKey]) @@ -76,34 +90,47 @@ func TestGetAccess(t *testing.T) { }) t.Run("Should return access for multiple entitlements (< than max concurrency)", func(t *testing.T) { - conn, deps := setupDependecies(t) - defer deps.Teardown() + namespace := "ns2" now := testutils.GetRFC3339Time(t, "2025-01-01T00:00:00Z") clock.SetTime(now) defer clock.ResetTime() - subjectKey := "test" - ns := "ns1" + mtr, err := deps.meterService.CreateMeter(t.Context(), meter.CreateMeterInput{ + Namespace: namespace, + Name: "Meter 1", + Key: "meter1", + Description: nil, + Aggregation: meter.MeterAggregationSum, + EventType: "test", + EventFrom: nil, + ValueProperty: lo.ToPtr("$.value"), + GroupBy: nil, + }) + require.NoError(t, err) + require.NotNil(t, mtr) - // First, create the subject - cust := createCustomerAndSubject(t, deps, ns, subjectKey) + // First, create the subject and the customer + randName := testutils.NameGenerator.Generate() + + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) count := 5 entIds := make([]string, count) for i := 0; i < count; i++ { - feat, err := deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{ + feat, err := deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ Key: fmt.Sprintf("test-%d", i), Name: "test", - Namespace: ns, - MeterSlug: lo.ToPtr("meter1"), + Namespace: namespace, + MeterSlug: lo.ToPtr(mtr.Key), }) require.NoError(t, err) require.NotNil(t, feat) - ent, err := conn.CreateEntitlement(context.Background(), entitlement.CreateEntitlementInputs{ - Namespace: ns, + ent, err := conn.CreateEntitlement(t.Context(), entitlement.CreateEntitlementInputs{ + Namespace: namespace, UsageAttribution: cust.GetUsageAttribution(), FeatureKey: lo.ToPtr(fmt.Sprintf("test-%d", i)), FeatureID: &feat.ID, @@ -119,7 +146,7 @@ func TestGetAccess(t *testing.T) { clock.SetTime(clock.Now().Add(time.Hour)) // Let's get the access - access, err := conn.GetAccess(context.Background(), ns, cust.ID) + access, err := conn.GetAccess(t.Context(), namespace, cust.ID) require.NoError(t, err) require.Len(t, access.Entitlements, count) for _, ent := range access.Entitlements { @@ -129,31 +156,45 @@ func TestGetAccess(t *testing.T) { }) t.Run("Should return access for multiple entitlements of multiple types", func(t *testing.T) { - conn, deps := setupDependecies(t) - defer deps.Teardown() + namespace := "ns3" now := testutils.GetRFC3339Time(t, "2025-01-01T00:00:00Z") clock.SetTime(now) defer clock.ResetTime() - subjectKey := "test" - ns := "ns1" + + mtr, err := deps.meterService.CreateMeter(t.Context(), meter.CreateMeterInput{ + Namespace: namespace, + Name: "Meter 1", + Key: "meter1", + Description: nil, + Aggregation: meter.MeterAggregationSum, + EventType: "test", + EventFrom: nil, + ValueProperty: lo.ToPtr("$.value"), + GroupBy: nil, + }) + require.NoError(t, err) + require.NotNil(t, mtr) // First, create the subject - cust := createCustomerAndSubject(t, deps, ns, subjectKey) + randName := testutils.NameGenerator.Generate() + + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Let's make a bool entitlement - feat, err := deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{ + feat, err := deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ Key: "test-bool", Name: "test", - Namespace: ns, - MeterSlug: lo.ToPtr("meter1"), + Namespace: namespace, + MeterSlug: lo.ToPtr(mtr.Key), }) require.NoError(t, err) require.NotNil(t, feat) - ent, err := conn.CreateEntitlement(context.Background(), entitlement.CreateEntitlementInputs{ - Namespace: ns, + ent, err := conn.CreateEntitlement(t.Context(), entitlement.CreateEntitlementInputs{ + Namespace: namespace, UsageAttribution: cust.GetUsageAttribution(), FeatureKey: lo.ToPtr("test-bool"), FeatureID: &feat.ID, @@ -163,17 +204,17 @@ func TestGetAccess(t *testing.T) { require.NotNil(t, ent) // Let's make a static entitlement - feat, err = deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{ + feat, err = deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ Key: "test-static", Name: "test", - Namespace: ns, - MeterSlug: lo.ToPtr("meter1"), + Namespace: namespace, + MeterSlug: lo.ToPtr(mtr.Key), }) require.NoError(t, err) require.NotNil(t, feat) - ent, err = conn.CreateEntitlement(context.Background(), entitlement.CreateEntitlementInputs{ - Namespace: ns, + ent, err = conn.CreateEntitlement(t.Context(), entitlement.CreateEntitlementInputs{ + Namespace: namespace, UsageAttribution: cust.GetUsageAttribution(), FeatureKey: lo.ToPtr("test-static"), FeatureID: &feat.ID, @@ -184,17 +225,17 @@ func TestGetAccess(t *testing.T) { require.NotNil(t, ent) // Let's make a metered entitlement - feat, err = deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{ + feat, err = deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ Key: "test-metered", Name: "test", - Namespace: ns, - MeterSlug: lo.ToPtr("meter1"), + Namespace: namespace, + MeterSlug: lo.ToPtr(mtr.Key), }) require.NoError(t, err) require.NotNil(t, feat) - ent, err = conn.CreateEntitlement(context.Background(), entitlement.CreateEntitlementInputs{ - Namespace: ns, + ent, err = conn.CreateEntitlement(t.Context(), entitlement.CreateEntitlementInputs{ + Namespace: namespace, UsageAttribution: cust.GetUsageAttribution(), FeatureKey: lo.ToPtr("test-metered"), FeatureID: &feat.ID, @@ -209,13 +250,13 @@ func TestGetAccess(t *testing.T) { require.NotNil(t, ent) // We need to add an event so streming mock finds the meter - deps.streamingConnector.AddSimpleEvent("meter1", 1, now) + deps.streamingConnector.AddSimpleEvent(mtr.Key, 1, now) // Let's pass some time clock.SetTime(clock.Now().Add(time.Hour)) // Let's get the access - access, err := conn.GetAccess(context.Background(), ns, cust.ID) + access, err := conn.GetAccess(t.Context(), namespace, cust.ID) require.NoError(t, err) require.Len(t, access.Entitlements, 3) @@ -229,34 +270,46 @@ func TestGetAccess(t *testing.T) { }) t.Run("Should return access for multiple entitlements (> than max concurrency)", func(t *testing.T) { - conn, deps := setupDependecies(t) - defer deps.Teardown() + namespace := "ns4" now := testutils.GetRFC3339Time(t, "2025-01-01T00:00:00Z") clock.SetTime(now) defer clock.ResetTime() - subjectKey := "test" - ns := "ns1" + mtr, err := deps.meterService.CreateMeter(t.Context(), meter.CreateMeterInput{ + Namespace: namespace, + Name: "Meter 1", + Key: "meter1", + Description: nil, + Aggregation: meter.MeterAggregationSum, + EventType: "test", + EventFrom: nil, + ValueProperty: lo.ToPtr("$.value"), + GroupBy: nil, + }) + require.NoError(t, err) + require.NotNil(t, mtr) - // First, create the subject - cust := createCustomerAndSubject(t, deps, ns, subjectKey) + randName := testutils.NameGenerator.Generate() + + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) count := 20 entIds := make([]string, count) for i := 0; i < count; i++ { - feat, err := deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{ + feat, err := deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ Key: fmt.Sprintf("test-%d", i), Name: "test", - Namespace: ns, - MeterSlug: lo.ToPtr("meter1"), + Namespace: namespace, + MeterSlug: lo.ToPtr(mtr.Key), }) require.NoError(t, err) require.NotNil(t, feat) - ent, err := conn.CreateEntitlement(context.Background(), entitlement.CreateEntitlementInputs{ - Namespace: ns, + ent, err := conn.CreateEntitlement(t.Context(), entitlement.CreateEntitlementInputs{ + Namespace: namespace, UsageAttribution: cust.GetUsageAttribution(), FeatureKey: lo.ToPtr(fmt.Sprintf("test-%d", i)), FeatureID: &feat.ID, @@ -272,7 +325,7 @@ func TestGetAccess(t *testing.T) { clock.SetTime(clock.Now().Add(time.Hour)) // Let's get the access - access, err := conn.GetAccess(context.Background(), ns, cust.ID) + access, err := conn.GetAccess(t.Context(), namespace, cust.ID) require.NoError(t, err) require.Len(t, access.Entitlements, count) for _, ent := range access.Entitlements { diff --git a/openmeter/entitlement/service/scheduling_test.go b/openmeter/entitlement/service/scheduling_test.go index ddbc7d8a3a..f02f46e68c 100644 --- a/openmeter/entitlement/service/scheduling_test.go +++ b/openmeter/entitlement/service/scheduling_test.go @@ -1,14 +1,16 @@ package service_test import ( - "context" + "fmt" "testing" "time" "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/openmeterio/openmeter/openmeter/entitlement" + "github.com/openmeterio/openmeter/openmeter/meter" "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" "github.com/openmeterio/openmeter/openmeter/streaming" "github.com/openmeterio/openmeter/openmeter/testutils" @@ -18,6 +20,8 @@ import ( ) func TestScheduling(t *testing.T) { + namespace := "ns1" + dummyAttribution := streaming.CustomerUsageAttribution{ ID: "01K3HJMFE6FW7PS470BYZ3NCR2", SubjectKeys: []string{ @@ -25,6 +29,33 @@ func TestScheduling(t *testing.T) { }, } + conn, deps := setupDependecies(t) + defer deps.Teardown() + + mtr, err := deps.meterService.CreateMeter(t.Context(), meter.CreateMeterInput{ + Namespace: namespace, + Name: "Meter 1", + Key: "meter1", + Description: nil, + Aggregation: meter.MeterAggregationSum, + EventType: "test", + EventFrom: nil, + ValueProperty: lo.ToPtr("$.value"), + GroupBy: nil, + }) + require.NoError(t, err) + require.NotNil(t, mtr) + + // Create feature + feat, err := deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ + Name: "feature1", + Key: "feature1", + Namespace: namespace, + MeterSlug: lo.ToPtr(mtr.Key), + }) + require.NoError(t, err) + require.NotEmpty(t, feat) + tt := []struct { name string fn func(t *testing.T, conn entitlement.Connector, deps *dependencies) @@ -32,12 +63,12 @@ func TestScheduling(t *testing.T) { { name: "Should not allow scheduling via create", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() _, err := conn.CreateEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: dummyAttribution, EntitlementType: entitlement.EntitlementTypeBoolean, ActiveFrom: lo.ToPtr(testutils.GetRFC3339Time(t, "2025-01-01T00:00:00Z")), @@ -48,8 +79,8 @@ func TestScheduling(t *testing.T) { _, err = conn.CreateEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: dummyAttribution, EntitlementType: entitlement.EntitlementTypeBoolean, ActiveTo: lo.ToPtr(testutils.GetRFC3339Time(t, "2025-01-01T00:00:00Z")), @@ -61,31 +92,24 @@ func TestScheduling(t *testing.T) { { name: "Should fail scheduling is contradictory", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) activeFrom := testutils.GetRFC3339Time(t, "2024-01-03T15:00:00Z") activeTo := testutils.GetRFC3339Time(t, "2024-01-03T12:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) + randName := testutils.NameGenerator.Generate() - assert.Nil(t, err) - - // Create subject - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // From after To _, err = conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -99,8 +123,8 @@ func TestScheduling(t *testing.T) { _, err = conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -109,14 +133,14 @@ func TestScheduling(t *testing.T) { }, ) // ActiveFrom and ActiveTo can be the same - assert.Nil(t, err) + assert.NoError(t, err) // ActiveTo present but not ActiveFrom _, err = conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -129,29 +153,22 @@ func TestScheduling(t *testing.T) { { name: "Should allow scheduling entitlement if no entitlement is present for pair", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) activeFrom := testutils.GetRFC3339Time(t, "2024-01-03T12:00:00Z") activeTo := testutils.GetRFC3339Time(t, "2024-01-03T15:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) - - assert.Nil(t, err) + randName := testutils.NameGenerator.Generate() - // Create subject - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) ent, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", + Namespace: namespace, FeatureKey: lo.ToPtr("feature1"), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, @@ -160,7 +177,7 @@ func TestScheduling(t *testing.T) { ActiveTo: lo.ToPtr(activeTo), }, ) - assert.Nil(t, err) + assert.NoError(t, err) assert.NotNil(t, ent) assert.Equal(t, &activeFrom, ent.ActiveFrom) assert.Equal(t, &activeTo, ent.ActiveTo) @@ -169,7 +186,7 @@ func TestScheduling(t *testing.T) { { name: "Should allow scheduling entitlement after current scheduled entitlement", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) @@ -179,24 +196,17 @@ func TestScheduling(t *testing.T) { activeFrom2 := testutils.GetRFC3339Time(t, "2024-01-03T18:00:00Z") activeTo2 := testutils.GetRFC3339Time(t, "2024-01-03T19:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) + randName := testutils.NameGenerator.Generate() - assert.Nil(t, err) - - // Create subject - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create first entitlement _, err = conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -204,14 +214,14 @@ func TestScheduling(t *testing.T) { ActiveTo: lo.ToPtr(activeTo1), }, ) - assert.Nil(t, err) + assert.NoError(t, err) // Create second entitlement _, err = conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -219,13 +229,13 @@ func TestScheduling(t *testing.T) { ActiveTo: lo.ToPtr(activeTo2), }, ) - assert.Nil(t, err) + assert.NoError(t, err) }, }, { name: "Should error if entitlements with defined schedules overlap", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) @@ -235,24 +245,17 @@ func TestScheduling(t *testing.T) { activeFrom2 := testutils.GetRFC3339Time(t, "2024-01-03T14:00:00Z") activeTo2 := testutils.GetRFC3339Time(t, "2024-01-03T16:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) - - assert.Nil(t, err) + randName := testutils.NameGenerator.Generate() - // Create subject - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create first entitlement ent1, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -260,14 +263,14 @@ func TestScheduling(t *testing.T) { ActiveTo: lo.ToPtr(activeTo1), }, ) - assert.Nil(t, err) + assert.NoError(t, err) // Create second entitlement _, err = conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -284,7 +287,7 @@ func TestScheduling(t *testing.T) { { name: "Should error when attempting to schedule after indefinite entitlement", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) @@ -293,24 +296,17 @@ func TestScheduling(t *testing.T) { activeFrom2 := testutils.GetRFC3339Time(t, "2024-01-03T14:00:00Z") activeTo2 := testutils.GetRFC3339Time(t, "2024-01-03T16:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) - - assert.Nil(t, err) + randName := testutils.NameGenerator.Generate() - // Create subject - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create first entitlement ent1, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -323,8 +319,8 @@ func TestScheduling(t *testing.T) { _, err = conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -341,29 +337,24 @@ func TestScheduling(t *testing.T) { { name: "Should save annotations for all entitlement types", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() - - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - MeterSlug: lo.ToPtr("meter1"), - }) + ctx := t.Context() - assert.Nil(t, err) + // create customer and subject + randName1 := testutils.NameGenerator.Generate() + cust1 := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName1.Key, randName1.Name) + + randName2 := testutils.NameGenerator.Generate() + cust2 := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName2.Key, randName2.Name) - // Create subject - cust1 := createCustomerAndSubject(t, deps, "ns1", "subject1") - cust2 := createCustomerAndSubject(t, deps, "ns1", "subject2") - cust3 := createCustomerAndSubject(t, deps, "ns1", "subject2") + randName3 := testutils.NameGenerator.Generate() + cust3 := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName3.Key, randName3.Name) t.Run("Boolean entitlement", func(t *testing.T) { ent, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust1.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, Annotations: models.Annotations{ @@ -371,7 +362,7 @@ func TestScheduling(t *testing.T) { }, }, ) - assert.Nil(t, err) + assert.NoError(t, err) assert.NotNil(t, ent) assert.Equal(t, models.Annotations{ "subscription.id": "sub_123", @@ -382,8 +373,8 @@ func TestScheduling(t *testing.T) { ent, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust2.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeStatic, Annotations: models.Annotations{ @@ -392,7 +383,7 @@ func TestScheduling(t *testing.T) { Config: []byte(`{"value": "100"}`), }, ) - assert.Nil(t, err) + assert.NoError(t, err) assert.NotNil(t, ent) assert.Equal(t, models.Annotations{ "subscription.id": "sub_123", @@ -403,8 +394,8 @@ func TestScheduling(t *testing.T) { ent, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust3.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeMetered, Annotations: models.Annotations{ @@ -416,7 +407,7 @@ func TestScheduling(t *testing.T) { })), }, ) - assert.Nil(t, err) + assert.NoError(t, err) assert.NotNil(t, ent) assert.Equal(t, models.Annotations{ "subscription.id": "sub_123", @@ -428,14 +419,14 @@ func TestScheduling(t *testing.T) { for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { - conn, deps := setupDependecies(t) - defer deps.Teardown() tc.fn(t, conn, deps) }) } } func TestSuperseding(t *testing.T) { + namespace := "ns2" + dummyAttribution := streaming.CustomerUsageAttribution{ ID: "01K3HJMFE6FW7PS470BYZ3NCR2", SubjectKeys: []string{ @@ -443,6 +434,26 @@ func TestSuperseding(t *testing.T) { }, } + conn, deps := setupDependecies(t) + defer deps.Teardown() + + // Create feature + feat, err := deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ + Name: "feature1", + Key: "feature1", + Namespace: namespace, + }) + require.NoError(t, err) + require.NotEmpty(t, feat) + + feat2, err := deps.featureRepo.CreateFeature(t.Context(), feature.CreateFeatureInputs{ + Name: "feature2", + Key: "feature2", + Namespace: namespace, + }) + require.NoError(t, err) + require.NotEmpty(t, feat2) + tt := []struct { name string fn func(t *testing.T, conn entitlement.Connector, deps *dependencies) @@ -450,120 +461,95 @@ func TestSuperseding(t *testing.T) { { name: "Should error if original entitlement is not found", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) activeFrom1 := testutils.GetRFC3339Time(t, "2024-01-03T12:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) - - assert.Nil(t, err) - // Supersede nonexistent entitlement _, err = conn.SupersedeEntitlement( ctx, "bogus-id", entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: dummyAttribution, EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future ActiveFrom: lo.ToPtr(activeFrom1), }, ) - assert.EqualError(t, err, "entitlement not found bogus-id in namespace ns1") + assert.EqualError(t, err, fmt.Sprintf("entitlement not found bogus-id in namespace %s", namespace)) }, }, { name: "Should error if feature is not found", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) activeFrom1 := testutils.GetRFC3339Time(t, "2024-01-03T12:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) + randName := testutils.NameGenerator.Generate() - assert.Nil(t, err) + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create first entitlement ent1, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), - UsageAttribution: dummyAttribution, + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), + UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future ActiveFrom: lo.ToPtr(activeFrom1), }, ) - assert.Nil(t, err) + require.NoError(t, err) + require.NotNil(t, ent1) + + invalidFeatureKey := "invalid-feature-key" // Supersede entitlement _, err = conn.SupersedeEntitlement( ctx, ent1.ID, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature2"), // invalid value - UsageAttribution: dummyAttribution, + Namespace: namespace, + FeatureKey: lo.ToPtr(invalidFeatureKey), // invalid value + UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future ActiveFrom: lo.ToPtr(activeFrom1.Add(time.Hour)), }, ) - assert.EqualError(t, err, "feature not found: feature2") + assert.EqualError(t, err, fmt.Sprintf("feature not found: %s", invalidFeatureKey)) }, }, { name: "Should error for differing feature", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) activeFrom1 := testutils.GetRFC3339Time(t, "2024-01-03T12:00:00Z") - // Create customer - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") + randName := testutils.NameGenerator.Generate() - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) - - assert.Nil(t, err) - - _, err = deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature2", - Key: "feature2", - Namespace: "ns1", - }) - - assert.Nil(t, err) + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create first entitlement ent1, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -577,8 +563,8 @@ func TestSuperseding(t *testing.T) { ctx, ent1.ID, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature2"), // invalid value + Namespace: namespace, + FeatureKey: lo.ToPtr(feat2.Key), // invalid value UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -591,105 +577,92 @@ func TestSuperseding(t *testing.T) { { name: "Should error for differing subjects", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) activeFrom1 := testutils.GetRFC3339Time(t, "2024-01-03T12:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) + // create customer and subject + randName1 := testutils.NameGenerator.Generate() + cust1 := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName1.Key, randName1.Name) - // Create customer - cust1 := createCustomerAndSubject(t, deps, "ns1", "subject1") - cust2 := createCustomerAndSubject(t, deps, "ns1", "subject2") - - assert.Nil(t, err) + randName2 := testutils.NameGenerator.Generate() + cust2 := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName2.Key, randName2.Name) // Create first entitlement ent1, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust1.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future ActiveFrom: lo.ToPtr(activeFrom1), }, ) - assert.Nil(t, err) + require.NoError(t, err) + require.NotNil(t, ent1) // Supersede entitlement _, err = conn.SupersedeEntitlement( ctx, ent1.ID, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust2.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, ActiveFrom: lo.ToPtr(activeFrom1.Add(time.Hour)), }, ) - assert.EqualError(t, err, "validation error: old and new entitlements belong to different subjects") + assert.EqualError(t, err, "validation error: old and new entitlements belong to different customers") }, }, { name: "Should supersede entitlement", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) activeFrom1 := testutils.GetRFC3339Time(t, "2024-01-03T12:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) - - // Create customer - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") - - assert.Nil(t, err) + // create customer and subject + randName := testutils.NameGenerator.Generate() + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create first entitlement ent1, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future ActiveFrom: lo.ToPtr(activeFrom1), }, ) - assert.Nil(t, err) + require.NoError(t, err) // Supersede entitlement ent2, err := conn.SupersedeEntitlement( ctx, ent1.ID, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, ActiveFrom: lo.ToPtr(activeFrom1.Add(time.Hour)), }, ) - assert.Nil(t, err) + require.NoError(t, err) ent1, err = conn.GetEntitlement(ctx, ent1.Namespace, ent1.ID) - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, lo.ToPtr(activeFrom1.Add(time.Hour)), ent1.ActiveTo) assert.Equal(t, lo.ToPtr(activeFrom1.Add(time.Hour)), ent2.ActiveFrom) @@ -699,30 +672,23 @@ func TestSuperseding(t *testing.T) { { name: "Should error if entitlements are not continuous", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() clock.SetTime(testutils.GetRFC3339Time(t, "2024-01-03T00:00:00Z")) activeFrom1 := testutils.GetRFC3339Time(t, "2024-01-03T12:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) - - assert.Nil(t, err) + randName := testutils.NameGenerator.Generate() - // Create customer - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create first entitlement ent1, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -737,8 +703,8 @@ func TestSuperseding(t *testing.T) { ctx, ent1.ID, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, ActiveFrom: lo.ToPtr(activeFrom1.Add(time.Hour * 2)), @@ -751,27 +717,21 @@ func TestSuperseding(t *testing.T) { { name: "Should use current time for scheduling if activeFrom is not provided", fn: func(t *testing.T, conn entitlement.Connector, deps *dependencies) { - ctx := context.Background() + ctx := t.Context() activeFrom1 := testutils.GetRFC3339Time(t, "2024-01-01T12:00:00Z") - // Create feature - _, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{ - Name: "feature1", - Key: "feature1", - Namespace: "ns1", - }) - - assert.Nil(t, err) + randName := testutils.NameGenerator.Generate() - cust := createCustomerAndSubject(t, deps, "ns1", "subject1") + // create customer and subject + cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, randName.Key, randName.Name) // Create first entitlement ent1, err := conn.ScheduleEntitlement( ctx, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, // 12h in future @@ -789,8 +749,8 @@ func TestSuperseding(t *testing.T) { ctx, ent1.ID, entitlement.CreateEntitlementInputs{ - Namespace: "ns1", - FeatureKey: lo.ToPtr("feature1"), + Namespace: namespace, + FeatureKey: lo.ToPtr(feat.Key), UsageAttribution: cust.GetUsageAttribution(), EntitlementType: entitlement.EntitlementTypeBoolean, }, @@ -810,8 +770,6 @@ func TestSuperseding(t *testing.T) { for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { - conn, deps := setupDependecies(t) - defer deps.Teardown() tc.fn(t, conn, deps) }) } diff --git a/openmeter/entitlement/service/utils_test.go b/openmeter/entitlement/service/utils_test.go index e088c3d11e..96705d6633 100644 --- a/openmeter/entitlement/service/utils_test.go +++ b/openmeter/entitlement/service/utils_test.go @@ -6,7 +6,6 @@ import ( "testing" "time" - "github.com/oklog/ulid/v2" "github.com/samber/lo" "github.com/stretchr/testify/require" "go.opentelemetry.io/otel/trace/noop" @@ -31,7 +30,6 @@ import ( "github.com/openmeterio/openmeter/pkg/framework/entutils/entdriver" "github.com/openmeterio/openmeter/pkg/framework/lockr" "github.com/openmeterio/openmeter/pkg/framework/pgdriver" - "github.com/openmeterio/openmeter/pkg/models" ) // Meant to work for boolean entitlements @@ -74,6 +72,7 @@ type dependencies struct { streamingConnector *streamingtestutils.MockStreamingConnector subjectService subject.Service customerService customer.Service + meterService meter.ManageService } // Teardown cleans up the dependencies @@ -89,25 +88,9 @@ var m sync.Mutex func setupDependecies(t *testing.T) (entitlement.Connector, *dependencies) { testLogger := testutils.NewLogger(t) - meterAdapter, err := meteradapter.New([]meter.Meter{{ - ManagedResource: models.ManagedResource{ - ID: ulid.Make().String(), - NamespacedModel: models.NamespacedModel{ - Namespace: "ns1", - }, - ManagedModel: models.ManagedModel{ - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }, - Name: "Meter 1", - }, - Key: "meter1", - Aggregation: meter.MeterAggregationSum, - EventType: "test", - ValueProperty: lo.ToPtr("$.value"), - }}) + meterService, err := meteradapter.NewManage(nil) if err != nil { - t.Fatalf("failed to create meter adapter: %v", err) + t.Fatalf("failed to create meter service: %v", err) } // create isolated pg db for tests @@ -136,7 +119,7 @@ func setupDependecies(t *testing.T) (entitlement.Connector, *dependencies) { StreamingConnector: streamingConnector, Logger: testLogger, Tracer: noop.NewTracerProvider().Tracer("test"), - MeterService: meterAdapter, + MeterService: meterService, Publisher: eventbus.NewMock(t), EntitlementsConfiguration: config.EntitlementsConfiguration{ GracePeriod: datetime.ISODurationString("P1D"), @@ -179,25 +162,28 @@ func setupDependecies(t *testing.T) (entitlement.Connector, *dependencies) { streamingConnector: streamingConnector, subjectService: subjectService, customerService: customerService, + meterService: meterService, } return entitlementRegistry.Entitlement, deps } -func createCustomerAndSubject(t *testing.T, deps *dependencies, ns string, subjectKey string) *customer.Customer { +func createCustomerAndSubject(t *testing.T, subjectService subject.Service, customerService customer.Service, ns, key, name string) *customer.Customer { t.Helper() - _, err := deps.subjectService.Create(context.Background(), subject.CreateInput{ + + _, err := subjectService.Create(t.Context(), subject.CreateInput{ Namespace: ns, - Key: subjectKey, + Key: key, }) require.NoError(t, err) - cust, err := deps.customerService.CreateCustomer(context.Background(), customer.CreateCustomerInput{ + cust, err := customerService.CreateCustomer(t.Context(), customer.CreateCustomerInput{ Namespace: ns, CustomerMutate: customer.CustomerMutate{ - Key: lo.ToPtr(subjectKey), + Key: lo.ToPtr(key), + Name: name, UsageAttribution: customer.CustomerUsageAttribution{ - SubjectKeys: []string{subjectKey}, + SubjectKeys: []string{key}, }, }, }) diff --git a/openmeter/subscription/testutils/billing.go b/openmeter/subscription/testutils/billing.go new file mode 100644 index 0000000000..c094f964ec --- /dev/null +++ b/openmeter/subscription/testutils/billing.go @@ -0,0 +1,32 @@ +package subscriptiontestutils + +import ( + "context" + + "github.com/openmeterio/openmeter/openmeter/app" + "github.com/openmeterio/openmeter/openmeter/billing" +) + +var _ billing.CustomerOverrideService = (*NoopCustomerOverrideService)(nil) + +type NoopCustomerOverrideService struct{} + +func (n NoopCustomerOverrideService) UpsertCustomerOverride(ctx context.Context, input billing.UpsertCustomerOverrideInput) (billing.CustomerOverrideWithDetails, error) { + return billing.CustomerOverrideWithDetails{}, nil +} + +func (n NoopCustomerOverrideService) DeleteCustomerOverride(ctx context.Context, input billing.DeleteCustomerOverrideInput) error { + return nil +} + +func (n NoopCustomerOverrideService) GetCustomerOverride(ctx context.Context, input billing.GetCustomerOverrideInput) (billing.CustomerOverrideWithDetails, error) { + return billing.CustomerOverrideWithDetails{}, nil +} + +func (n NoopCustomerOverrideService) GetCustomerApp(ctx context.Context, input billing.GetCustomerAppInput) (app.App, error) { + return nil, nil +} + +func (n NoopCustomerOverrideService) ListCustomerOverrides(ctx context.Context, input billing.ListCustomerOverridesInput) (billing.ListCustomerOverridesResult, error) { + return billing.ListCustomerOverridesResult{}, nil +} diff --git a/openmeter/subscription/testutils/service.go b/openmeter/subscription/testutils/service.go index 731582ccc1..b602e97cb6 100644 --- a/openmeter/subscription/testutils/service.go +++ b/openmeter/subscription/testutils/service.go @@ -1,6 +1,7 @@ package subscriptiontestutils import ( + "log/slog" "testing" "time" @@ -11,6 +12,7 @@ import ( "github.com/openmeterio/openmeter/app/config" "github.com/openmeterio/openmeter/openmeter/customer" + customerservicehooks "github.com/openmeterio/openmeter/openmeter/customer/service/hooks" "github.com/openmeterio/openmeter/openmeter/meter" meteradapter "github.com/openmeterio/openmeter/openmeter/meter/mockadapter" addonrepo "github.com/openmeterio/openmeter/openmeter/productcatalog/addon/adapter" @@ -25,6 +27,7 @@ import ( registrybuilder "github.com/openmeterio/openmeter/openmeter/registry/builder" streamingtestutils "github.com/openmeterio/openmeter/openmeter/streaming/testutils" "github.com/openmeterio/openmeter/openmeter/subject" + subjecthooks "github.com/openmeterio/openmeter/openmeter/subject/service/hooks" "github.com/openmeterio/openmeter/openmeter/subscription" subscriptionaddon "github.com/openmeterio/openmeter/openmeter/subscription/addon" subscriptionaddonrepo "github.com/openmeterio/openmeter/openmeter/subscription/addon/repo" @@ -113,9 +116,50 @@ func NewService(t *testing.T, dbDeps *DBDeps) SubscriptionDependencies { ) customerAdapter := NewCustomerAdapter(t, dbDeps) - customer := NewCustomerService(t, dbDeps) + customerService := NewCustomerService(t, dbDeps) subjectService := NewSubjectService(t, dbDeps) + // Hooks + + // Subject hooks + + subjectCustomerHook, err := subjecthooks.NewCustomerSubjectHook(subjecthooks.CustomerSubjectHookConfig{ + Subject: subjectService, + Logger: logger, + Tracer: noop.NewTracerProvider().Tracer("test_env"), + }) + require.NoError(t, err) + customerService.RegisterHooks(subjectCustomerHook) + + subjectEntitlementValidatorHook, err := subjecthooks.NewEntitlementValidatorHook(subjecthooks.EntitlementValidatorHookConfig{ + EntitlementService: entitlementRegistry.Entitlement, + }) + require.NoError(t, err) + subjectService.RegisterHooks(subjectEntitlementValidatorHook) + + // customer hooks + customerSubjectHook, err := customerservicehooks.NewSubjectCustomerHook(customerservicehooks.SubjectCustomerHookConfig{ + Customer: customerService, + CustomerOverride: NoopCustomerOverrideService{}, + Logger: logger, + Tracer: noop.NewTracerProvider().Tracer("test_env"), + }) + require.NoError(t, err) + subjectService.RegisterHooks(customerSubjectHook) + + customerSubjectValidatorHook, err := customerservicehooks.NewSubjectValidatorHook(customerservicehooks.SubjectValidatorHookConfig{ + Customer: customerService, + Logger: slog.Default(), + }) + require.NoError(t, err) + subjectService.RegisterHooks(customerSubjectValidatorHook) + + entitlementValidatorHook, err := customerservicehooks.NewEntitlementValidatorHook(customerservicehooks.EntitlementValidatorHookConfig{ + EntitlementService: entitlementRegistry.Entitlement, + }) + require.NoError(t, err) + customerService.RegisterHooks(entitlementValidatorHook) + planRepo, err := planrepo.New(planrepo.Config{ Client: dbDeps.DBClient, Logger: logger, @@ -136,7 +180,7 @@ func NewService(t *testing.T, dbDeps *DBDeps) SubscriptionDependencies { SubscriptionRepo: subRepo, SubscriptionPhaseRepo: subPhaseRepo, SubscriptionItemRepo: subItemRepo, - CustomerService: customer, + CustomerService: customerService, EntitlementAdapter: entitlementAdapter, FeatureService: entitlementRegistry.Feature, TransactionManager: subItemRepo, @@ -189,7 +233,7 @@ func NewService(t *testing.T, dbDeps *DBDeps) SubscriptionDependencies { workflowSvc := subscriptionworkflowservice.NewWorkflowService(subscriptionworkflowservice.WorkflowServiceConfig{ Service: svc, - CustomerService: customer, + CustomerService: customerService, TransactionManager: subItemRepo, AddonService: subAddSvc, Logger: logger.With("subsystem", "subscription.workflow.service"), @@ -200,7 +244,7 @@ func NewService(t *testing.T, dbDeps *DBDeps) SubscriptionDependencies { SubscriptionService: svc, WorkflowService: workflowSvc, CustomerAdapter: customerAdapter, - CustomerService: customer, + CustomerService: customerService, SubjectService: subjectService, FeatureConnector: NewTestFeatureConnector(entitlementRegistry.Feature), EntitlementAdapter: entitlementAdapter, diff --git a/openmeter/subscription/workflow/service/addon_test.go b/openmeter/subscription/workflow/service/addon_test.go index d80262201f..99922dd4ea 100644 --- a/openmeter/subscription/workflow/service/addon_test.go +++ b/openmeter/subscription/workflow/service/addon_test.go @@ -31,11 +31,7 @@ import ( func TestAddAddon(t *testing.T) { now := testutils.GetRFC3339Time(t, "2025-04-01T00:00:00Z") - type testCaseDeps struct { - deps subscriptiontestutils.SubscriptionDependencies - } - - runWithDeps := func(fn func(t *testing.T, deps testCaseDeps)) func(t *testing.T) { + runWithDeps := func(fn func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies)) func(t *testing.T) { return func(t *testing.T) { clock.SetTime(now) defer clock.ResetTime() @@ -44,14 +40,14 @@ func TestAddAddon(t *testing.T) { defer dbDeps.Cleanup(t) deps := subscriptiontestutils.NewService(t, dbDeps) - fn(t, testCaseDeps{deps: deps}) + fn(t, deps) } } - t.Run("Should error on invalid input", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should error on invalid input", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.GetExamplePlanInput(t), subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{ @@ -64,7 +60,7 @@ func TestAddAddon(t *testing.T) { ), ) - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) addonInp := subscriptionworkflow.AddAddonWorkflowInput{ AddonID: add.ID, @@ -77,17 +73,17 @@ func TestAddAddon(t *testing.T) { expectedErr := addonInp.Validate() require.NotNil(t, expectedErr) - _, _, err := deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + _, _, err := deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.Error(t, err) require.True(t, models.IsGenericValidationError(err)) require.ErrorContains(t, err, expectedErr.Error()) })) - t.Run("Should error if the subscription is inactive or in wrong state", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should error if the subscription is inactive or in wrong state", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.GetExamplePlanInput(t), subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{ @@ -101,10 +97,10 @@ func TestAddAddon(t *testing.T) { ) // Let's create a subscription from the plan - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) // Let's cancel the subscription - _, err := deps.deps.SubscriptionService.Cancel(context.Background(), subView.Subscription.NamespacedID, subscription.Timing{ + _, err := deps.SubscriptionService.Cancel(context.Background(), subView.Subscription.NamespacedID, subscription.Timing{ Enum: lo.ToPtr(subscription.TimingNextBillingCycle), }) require.NoError(t, err) @@ -118,18 +114,18 @@ func TestAddAddon(t *testing.T) { }, } - _, _, err = deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + _, _, err = deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.Error(t, err) require.ErrorAs(t, err, lo.ToPtr(&models.GenericForbiddenError{})) require.True(t, models.IsGenericForbiddenError(err)) require.ErrorContains(t, err, "state canceled not allowed") })) - t.Run("Should add a new addon to a subscription that already has a different addon", runWithDeps(func(t *testing.T, deps testCaseDeps) { - _ = deps.deps.FeatureConnector.CreateExampleFeatures(t) + t.Run("Should add a new addon to a subscription that already has a different addon", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { + _ = deps.FeatureConnector.CreateExampleFeatures(t) // Let's create a plan - p, err := deps.deps.PlanService.CreatePlan(context.Background(), subscriptiontestutils.BuildTestPlan(t). + p, err := deps.PlanService.CreatePlan(context.Background(), subscriptiontestutils.BuildTestPlan(t). AddPhase(nil, &subscriptiontestutils.ExampleRateCard1). Build()) require.Nil(t, err) @@ -145,14 +141,14 @@ func TestAddAddon(t *testing.T) { subscriptiontestutils.ExampleAddonRateCard5.Clone(), ) - add1 := deps.deps.AddonService.CreateTestAddon(t, addonInp) + add1 := deps.AddonService.CreateTestAddon(t, addonInp) addonInp.Key = "some-new-key" - add2 := deps.deps.AddonService.CreateTestAddon(t, addonInp) + add2 := deps.AddonService.CreateTestAddon(t, addonInp) // Let's link both addons to the plan - _, err = deps.deps.PlanAddonService.CreatePlanAddon(context.Background(), planaddon.CreatePlanAddonInput{ + _, err = deps.PlanAddonService.CreatePlanAddon(context.Background(), planaddon.CreatePlanAddonInput{ NamespacedModel: models.NamespacedModel{ Namespace: subscriptiontestutils.ExampleNamespace, }, @@ -162,7 +158,7 @@ func TestAddAddon(t *testing.T) { }) require.Nil(t, err, "received error: %s", err) - _, err = deps.deps.PlanAddonService.CreatePlanAddon(context.Background(), planaddon.CreatePlanAddonInput{ + _, err = deps.PlanAddonService.CreatePlanAddon(context.Background(), planaddon.CreatePlanAddonInput{ NamespacedModel: models.NamespacedModel{ Namespace: subscriptiontestutils.ExampleNamespace, }, @@ -174,7 +170,7 @@ func TestAddAddon(t *testing.T) { // Let's publish the plan - p, err = deps.deps.PlanService.PublishPlan(context.Background(), plan.PublishPlanInput{ + p, err = deps.PlanService.PublishPlan(context.Background(), plan.PublishPlanInput{ NamespacedID: p.NamespacedID, EffectivePeriod: productcatalog.EffectivePeriod{ EffectiveFrom: lo.ToPtr(clock.Now()), @@ -185,13 +181,13 @@ func TestAddAddon(t *testing.T) { // Let's create a subscription from the plan - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, &plansubscription.Plan{ + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, &plansubscription.Plan{ Plan: p.AsProductCatalogPlan(), Ref: &p.NamespacedID, }, now) // Let's add the first addon - _, _, err = deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, subscriptionworkflow.AddAddonWorkflowInput{ + _, _, err = deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, subscriptionworkflow.AddAddonWorkflowInput{ AddonID: add1.ID, InitialQuantity: 1, Timing: subscription.Timing{ @@ -201,7 +197,7 @@ func TestAddAddon(t *testing.T) { require.NoError(t, err) // Now let's add the second addon - subView, _, err = deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, subscriptionworkflow.AddAddonWorkflowInput{ + subView, _, err = deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, subscriptionworkflow.AddAddonWorkflowInput{ AddonID: add2.ID, InitialQuantity: 1, Timing: subscription.Timing{ @@ -215,10 +211,10 @@ func TestAddAddon(t *testing.T) { require.Equal(t, 200.0, *item.Entitlement.Entitlement.IssueAfterReset) })) - t.Run("Should sync subscription with new addons contents", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should sync subscription with new addons contents", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.GetExamplePlanInput(t), subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{ @@ -232,7 +228,7 @@ func TestAddAddon(t *testing.T) { ) // Let's create a subscription from the plan - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) ogView := subView require.NotNil(t, ogView) @@ -247,7 +243,7 @@ func TestAddAddon(t *testing.T) { }, } - subView, subAdd, err := deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + subView, subAdd, err := deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.NoError(t, err) // Let's figure out what the expected spec should be @@ -270,10 +266,10 @@ func TestAddAddon(t *testing.T) { subscriptiontestutils.SpecsEqual(t, newSpec, spec) })) - t.Run("Should return conflict error if subscription already has that addon purchased", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should return conflict error if subscription already has that addon purchased", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.GetExamplePlanInput(t), subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{ @@ -286,7 +282,7 @@ func TestAddAddon(t *testing.T) { ), ) - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) addonInp := subscriptionworkflow.AddAddonWorkflowInput{ AddonID: add.ID, @@ -296,10 +292,10 @@ func TestAddAddon(t *testing.T) { }, } - _, _, err := deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + _, _, err := deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.NoError(t, err) - _, _, err = deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + _, _, err = deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.Error(t, err) require.ErrorAs(t, err, lo.ToPtr(&models.GenericConflictError{})) require.True(t, models.IsGenericConflictError(err)) @@ -309,11 +305,7 @@ func TestAddAddon(t *testing.T) { func TestChangeAddonQuantity(t *testing.T) { now := testutils.GetRFC3339Time(t, "2025-04-01T00:00:00Z") - type testCaseDeps struct { - deps subscriptiontestutils.SubscriptionDependencies - } - - runWithDeps := func(fn func(t *testing.T, deps testCaseDeps)) func(t *testing.T) { + runWithDeps := func(fn func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies)) func(t *testing.T) { return func(t *testing.T) { clock.SetTime(now) defer clock.ResetTime() @@ -322,14 +314,14 @@ func TestChangeAddonQuantity(t *testing.T) { defer dbDeps.Cleanup(t) deps := subscriptiontestutils.NewService(t, dbDeps) - fn(t, testCaseDeps{deps: deps}) + fn(t, deps) } } - t.Run("Should error if SubscriptionAddon and Subscription are in different namespaces", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should error if SubscriptionAddon and Subscription are in different namespaces", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.GetExamplePlanInput(t), subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{ @@ -342,7 +334,7 @@ func TestChangeAddonQuantity(t *testing.T) { ), ) - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) addonInp := subscriptionworkflow.AddAddonWorkflowInput{ AddonID: add.ID, @@ -352,7 +344,7 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - subView, subAdd, err := deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + subView, subAdd, err := deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.NoError(t, err) changeTime := now.AddDate(0, 0, 1) @@ -368,16 +360,16 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - _, _, err = deps.deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) + _, _, err = deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) require.Error(t, err) require.ErrorAs(t, err, lo.ToPtr(&models.GenericValidationError{})) require.True(t, models.IsGenericValidationError(err)) })) - t.Run("Should error if SubscriptionAddon doesn't belong to Subscription", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should error if SubscriptionAddon doesn't belong to Subscription", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.GetExamplePlanInput(t), subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{ @@ -390,7 +382,7 @@ func TestChangeAddonQuantity(t *testing.T) { ), ) - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) addonInp := subscriptionworkflow.AddAddonWorkflowInput{ AddonID: add.ID, @@ -400,7 +392,7 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - cust2, err := deps.deps.CustomerAdapter.CreateCustomer(context.Background(), customer.CreateCustomerInput{ + cust2, err := deps.CustomerService.CreateCustomer(context.Background(), customer.CreateCustomerInput{ Namespace: subscriptiontestutils.ExampleNamespace, CustomerMutate: customer.CustomerMutate{ Name: "another", @@ -413,7 +405,7 @@ func TestChangeAddonQuantity(t *testing.T) { }) require.NoError(t, err) - subView2, err := deps.deps.WorkflowService.CreateFromPlan(context.Background(), subscriptionworkflow.CreateSubscriptionWorkflowInput{ + subView2, err := deps.WorkflowService.CreateFromPlan(context.Background(), subscriptionworkflow.CreateSubscriptionWorkflowInput{ Namespace: cust2.Namespace, CustomerID: cust2.ID, ChangeSubscriptionWorkflowInput: subscriptionworkflow.ChangeSubscriptionWorkflowInput{ @@ -425,10 +417,10 @@ func TestChangeAddonQuantity(t *testing.T) { }, p) require.NoError(t, err) - subView, _, err = deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + subView, _, err = deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.NoError(t, err) - subView2, subAdd2, err := deps.deps.WorkflowService.AddAddon(context.Background(), subView2.Subscription.NamespacedID, addonInp) + subView2, subAdd2, err := deps.WorkflowService.AddAddon(context.Background(), subView2.Subscription.NamespacedID, addonInp) require.NoError(t, err) changeTime := now.AddDate(0, 0, 1) @@ -442,16 +434,16 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - _, _, err = deps.deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) + _, _, err = deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) require.Error(t, err) require.ErrorAs(t, err, lo.ToPtr(&models.GenericValidationError{})) require.True(t, models.IsGenericValidationError(err)) })) - t.Run("Should error if the subscription is inactive or in wrong state", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should error if the subscription is inactive or in wrong state", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.GetExamplePlanInput(t), subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{ @@ -465,7 +457,7 @@ func TestChangeAddonQuantity(t *testing.T) { ) // Let's create a subscription from the plan - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) // Let's add an addon to the subscription addonInp := subscriptionworkflow.AddAddonWorkflowInput{ @@ -476,11 +468,11 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - _, subAdd, err := deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + _, subAdd, err := deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.NoError(t, err) // Let's cancel the subscription - _, err = deps.deps.SubscriptionService.Cancel(context.Background(), subView.Subscription.NamespacedID, subscription.Timing{ + _, err = deps.SubscriptionService.Cancel(context.Background(), subView.Subscription.NamespacedID, subscription.Timing{ Enum: lo.ToPtr(subscription.TimingNextBillingCycle), }) require.NoError(t, err) @@ -494,17 +486,17 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - _, _, err = deps.deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) + _, _, err = deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) require.Error(t, err) require.ErrorAs(t, err, lo.ToPtr(&models.GenericForbiddenError{})) require.True(t, models.IsGenericForbiddenError(err)) require.ErrorContains(t, err, "state canceled not allowed") })) - t.Run("Should update the quantity of the addon", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should update the quantity of the addon", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.BuildTestPlan(t). AddPhase(nil, &subscriptiontestutils.ExampleRateCard1). Build(), @@ -518,7 +510,7 @@ func TestChangeAddonQuantity(t *testing.T) { ), ) - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) addonInp := subscriptionworkflow.AddAddonWorkflowInput{ AddonID: add.ID, @@ -528,7 +520,7 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - subView, subAdd, err := deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + subView, subAdd, err := deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.NoError(t, err) changeTime := now.AddDate(0, 0, 1) @@ -541,7 +533,7 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - subView, subAdd, err = deps.deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) + subView, subAdd, err = deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) require.NoError(t, err) require.Len(t, subAdd.Quantities.GetTimes(), 2) @@ -551,14 +543,14 @@ func TestChangeAddonQuantity(t *testing.T) { require.Len(t, subView.Phases[0].ItemsByKey[subscriptiontestutils.ExampleRateCard1.Key()], 2) })) - t.Run("Should not combine two subsequent identical items (present due to an edit) when changing the quantity after an addon is already purchased", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should not combine two subsequent identical items (present due to an edit) when changing the quantity after an addon is already purchased", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { twoMonths := datetime.MustParseDuration(t, "P2M") twoMonthsFromNow, _ := twoMonths.AddTo(now) p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, subscriptiontestutils.BuildTestPlan(t). SetMeta(productcatalog.PlanMeta{ Name: "Test Plan", @@ -583,7 +575,7 @@ func TestChangeAddonQuantity(t *testing.T) { ), ) - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) // Now let's edit the sub ogItem := subView.Phases[0].ItemsByKey[subscriptiontestutils.ExampleRateCard1.Key()][0].Spec @@ -592,7 +584,7 @@ func TestChangeAddonQuantity(t *testing.T) { Enum: lo.ToPtr(subscription.TimingNextBillingCycle), } - subView, err := deps.deps.WorkflowService.EditRunning(context.Background(), subView.Subscription.NamespacedID, []subscription.Patch{ + subView, err := deps.WorkflowService.EditRunning(context.Background(), subView.Subscription.NamespacedID, []subscription.Patch{ patch.PatchRemoveItem{ PhaseKey: ogItem.PhaseKey, ItemKey: ogItem.ItemKey, @@ -617,7 +609,7 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - subView, subAdd, err := deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) + subView, subAdd, err := deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, addonInp) require.NoError(t, err) // assert that its still two items @@ -632,7 +624,7 @@ func TestChangeAddonQuantity(t *testing.T) { }, } - subView, subAdd, err = deps.deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) + subView, subAdd, err = deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInp) require.NoError(t, err) // Now it should be three items: original two with addon included + 3rd without the addon after 3 months @@ -657,11 +649,7 @@ func stripFeatureIDs(spec *subscription.SubscriptionSpec) { func TestAddonCombinations(t *testing.T) { now := testutils.GetRFC3339Time(t, "2025-04-01T00:00:00Z") - type testCaseDeps struct { - deps subscriptiontestutils.SubscriptionDependencies - } - - runWithDeps := func(fn func(t *testing.T, deps testCaseDeps)) func(t *testing.T) { + runWithDeps := func(fn func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies)) func(t *testing.T) { return func(t *testing.T) { clock.SetTime(now) defer clock.ResetTime() @@ -670,11 +658,11 @@ func TestAddonCombinations(t *testing.T) { defer dbDeps.Cleanup(t) deps := subscriptiontestutils.NewService(t, dbDeps) - fn(t, testCaseDeps{deps: deps}) + fn(t, deps) } } - t.Run("Should handle repeated add/remove of single instance addon with dynamic price", runWithDeps(func(t *testing.T, deps testCaseDeps) { + t.Run("Should handle repeated add/remove of single instance addon with dynamic price", runWithDeps(func(t *testing.T, deps subscriptiontestutils.SubscriptionDependencies) { // Create a plan with mixed rate cards planInput := subscriptiontestutils.BuildTestPlan(t). AddPhase(nil, @@ -707,7 +695,7 @@ func TestAddonCombinations(t *testing.T) { Build() p, add := subscriptiontestutils.CreatePlanWithAddon( t, - deps.deps, + deps, planInput, subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{ @@ -737,13 +725,13 @@ func TestAddonCombinations(t *testing.T) { ) // Create a subscription from the plan - subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now) + subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps, p, now) // Add the addon initially addTime := now var subAdd subscriptionaddon.SubscriptionAddon var err error - subView, subAdd, err = deps.deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, subscriptionworkflow.AddAddonWorkflowInput{ + subView, subAdd, err = deps.WorkflowService.AddAddon(context.Background(), subView.Subscription.NamespacedID, subscriptionworkflow.AddAddonWorkflowInput{ AddonID: add.ID, InitialQuantity: 1, Timing: subscription.Timing{ @@ -766,7 +754,7 @@ func TestAddonCombinations(t *testing.T) { Custom: lo.ToPtr(clock.Now()), }, } - subView, _, err = deps.deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInpZero) + subView, _, err = deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInpZero) require.NoError(t, err, "failed to change addon quantity to 0 on iteration %d", i) // Let's pass time @@ -780,7 +768,7 @@ func TestAddonCombinations(t *testing.T) { Custom: lo.ToPtr(clock.Now()), }, } - subView, subAdd, err = deps.deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInpOne) + subView, subAdd, err = deps.WorkflowService.ChangeAddonQuantity(context.Background(), subView.Subscription.NamespacedID, changeInpOne) require.NoError(t, err, "failed to change addon quantity to 1 on iteration %d", i) // Let's pass time diff --git a/openmeter/subscription/workflow/service/subscription_test.go b/openmeter/subscription/workflow/service/subscription_test.go index 1097c4c0b4..8f31783d4d 100644 --- a/openmeter/subscription/workflow/service/subscription_test.go +++ b/openmeter/subscription/workflow/service/subscription_test.go @@ -29,7 +29,6 @@ import ( "github.com/openmeterio/openmeter/pkg/datetime" "github.com/openmeterio/openmeter/pkg/framework/lockr" "github.com/openmeterio/openmeter/pkg/models" - "github.com/openmeterio/openmeter/pkg/timeutil" ) func TestCreateFromPlan(t *testing.T) { @@ -92,41 +91,6 @@ func TestCreateFromPlan(t *testing.T) { } }, }, - { - Name: "Should normalize billing anchor to the closest iteration", - Handler: func(t *testing.T, deps testCaseDeps) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - cad := deps.Plan.ToCreateSubscriptionPlanInput().BillingCadence - - activeFrom := deps.CurrentTime - - billingAnchor := activeFrom.Add(time.Hour) - - cadRec, err := timeutil.NewRecurrenceFromISODuration(cad, billingAnchor) - require.Nil(t, err) - - // Let's set an anchor one hour after the activeFrom, which will then be set to one iteration before - - expectedBillingAnchor, err := cadRec.Iterator().Prev() - require.Nil(t, err) - - subView, err := deps.WorkflowService.CreateFromPlan(ctx, subscriptionworkflow.CreateSubscriptionWorkflowInput{ - ChangeSubscriptionWorkflowInput: subscriptionworkflow.ChangeSubscriptionWorkflowInput{ - Timing: subscription.Timing{ - Custom: &deps.CurrentTime, - }, - }, - CustomerID: deps.Customer.ID, - Namespace: subscriptiontestutils.ExampleNamespace, - BillingAnchor: &billingAnchor, - }, deps.Plan) - require.Nil(t, err) - - require.Equal(t, expectedBillingAnchor, subView.Subscription.BillingAnchor) - }, - }, } for _, tc := range testCases { @@ -1034,7 +998,7 @@ func TestChangeToPlan(t *testing.T) { CustomerId: curr.CustomerId, Currency: deps.Plan2.Currency(), ActiveFrom: testutils.GetRFC3339Time(t, "2021-02-01T00:00:00Z"), - BillingAnchor: sub.Subscription.BillingAnchor.AddDate(0, 1, 0), // shift 1 month due to normalization + BillingAnchor: sub.Subscription.BillingAnchor, ActiveTo: nil, }) require.Nil(t, err) @@ -1302,7 +1266,7 @@ func TestEditCombinations(t *testing.T) { // - grants left withDeps(t)(func(t *testing.T, deps testCaseDeps) { // Let's create an example subscription - _, err := deps.WorkflowService.CreateFromPlan(context.Background(), subscriptionworkflow.CreateSubscriptionWorkflowInput{ + _, err := deps.WorkflowService.CreateFromPlan(t.Context(), subscriptionworkflow.CreateSubscriptionWorkflowInput{ ChangeSubscriptionWorkflowInput: subscriptionworkflow.ChangeSubscriptionWorkflowInput{ Timing: subscription.Timing{ Custom: &deps.CurrentTime, @@ -1316,7 +1280,7 @@ func TestEditCombinations(t *testing.T) { // Now that we've got a subscription we'll use raw SQL to do the rest, this is the hacky part - res, err := deps.DBDeps.DBClient.ExecContext(context.Background(), `DELETE FROM subscriptions`) + res, err := deps.DBDeps.DBClient.ExecContext(t.Context(), `DELETE FROM subscriptions`) require.Nil(t, err) affected, err := res.RowsAffected() @@ -1325,7 +1289,7 @@ func TestEditCombinations(t *testing.T) { // Now let's query the DB, lets encapsulate in inline functions for referential integrity func() { - rows, err := deps.DBDeps.DBClient.QueryContext(context.Background(), `SELECT COUNT(*) FROM subscription_phases`) + rows, err := deps.DBDeps.DBClient.QueryContext(t.Context(), `SELECT COUNT(*) FROM subscription_phases`) require.Nil(t, err) defer rows.Close() @@ -1337,7 +1301,7 @@ func TestEditCombinations(t *testing.T) { }() func() { - rows, err := deps.DBDeps.DBClient.QueryContext(context.Background(), `SELECT COUNT(*) FROM subscription_items`) + rows, err := deps.DBDeps.DBClient.QueryContext(t.Context(), `SELECT COUNT(*) FROM subscription_items`) require.Nil(t, err) defer rows.Close() @@ -1349,7 +1313,7 @@ func TestEditCombinations(t *testing.T) { }() func() { - rows, err := deps.DBDeps.DBClient.QueryContext(context.Background(), `SELECT COUNT(*) FROM entitlements`) + rows, err := deps.DBDeps.DBClient.QueryContext(t.Context(), `SELECT COUNT(*) FROM entitlements`) require.Nil(t, err) defer rows.Close() @@ -1361,7 +1325,7 @@ func TestEditCombinations(t *testing.T) { }() func() { - rows, err := deps.DBDeps.DBClient.QueryContext(context.Background(), `SELECT COUNT(*) FROM grants`) + rows, err := deps.DBDeps.DBClient.QueryContext(t.Context(), `SELECT COUNT(*) FROM grants`) require.Nil(t, err) defer rows.Close() @@ -1377,7 +1341,7 @@ func TestEditCombinations(t *testing.T) { // - plans // - features func() { - rows, err := deps.DBDeps.DBClient.QueryContext(context.Background(), `SELECT COUNT(*) FROM customers`) + rows, err := deps.DBDeps.DBClient.QueryContext(t.Context(), `SELECT COUNT(*) FROM customers`) require.Nil(t, err) defer rows.Close() @@ -1389,7 +1353,7 @@ func TestEditCombinations(t *testing.T) { }() func() { - rows, err := deps.DBDeps.DBClient.QueryContext(context.Background(), `SELECT COUNT(*) FROM plans`) + rows, err := deps.DBDeps.DBClient.QueryContext(t.Context(), `SELECT COUNT(*) FROM plans`) require.Nil(t, err) defer rows.Close() @@ -1401,7 +1365,7 @@ func TestEditCombinations(t *testing.T) { }() func() { - rows, err := deps.DBDeps.DBClient.QueryContext(context.Background(), `SELECT COUNT(*) FROM features`) + rows, err := deps.DBDeps.DBClient.QueryContext(t.Context(), `SELECT COUNT(*) FROM features`) require.Nil(t, err) defer rows.Close() diff --git a/openmeter/testutils/namegen.go b/openmeter/testutils/namegen.go new file mode 100644 index 0000000000..0f576c8040 --- /dev/null +++ b/openmeter/testutils/namegen.go @@ -0,0 +1,38 @@ +package testutils + +import ( + "strings" + "time" + + "github.com/forscht/namegen" + "github.com/forscht/namegen/dictionaries" +) + +var NameGenerator = newNameGenerator() + +type nameGenerator struct { + *namegen.Generator +} + +func newNameGenerator() *nameGenerator { + return &nameGenerator{ + Generator: namegen.New(). + WithSeed(time.Now().UnixNano()). + WithDictionaries(dictionaries.Adjectives, dictionaries.Animals). + WithNumberOfWords(2), + } +} + +type GeneratedName struct { + Key string + Name string +} + +func (g *nameGenerator) Generate() GeneratedName { + name := g.Generator.WithStyle(namegen.Title).WithWordSeparator(" ").Generate() + + return GeneratedName{ + Key: strings.ReplaceAll(strings.ToLower(name), " ", "-"), + Name: name, + } +} diff --git a/openmeter/testutils/namegen_test.go b/openmeter/testutils/namegen_test.go new file mode 100644 index 0000000000..9c4e792ade --- /dev/null +++ b/openmeter/testutils/namegen_test.go @@ -0,0 +1,19 @@ +package testutils + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_NameGen(t *testing.T) { + t.Run("Generate", func(t *testing.T) { + names := NameGenerator.Generate() + t.Logf("Generated name: %v", names) + + require.NotEmpty(t, names) + assert.NotEmpty(t, names.Key) + assert.NotEmpty(t, names.Name) + }) +} diff --git a/pkg/timeutil/recurrence.go b/pkg/timeutil/recurrence.go index 5217371011..560e728289 100644 --- a/pkg/timeutil/recurrence.go +++ b/pkg/timeutil/recurrence.go @@ -107,6 +107,7 @@ func (r Recurrence) iterateFromNextAfterInclusive(t time.Time) (RecurrenceIterat // Calculate the inclusive nextAfter value for res.After(t) { + // TODO: Right now we cannot iterate backwards past 1733, please fix this. if ic <= -MAX_SAFE_ITERATIONS { return RecurrenceIterator{}, fmt.Errorf("recurrence.NextAfter: too many iterations") } diff --git a/test/app/stripe/app_test.go b/test/app/stripe/app_test.go index b2c6278c33..40dbc50ce3 100644 --- a/test/app/stripe/app_test.go +++ b/test/app/stripe/app_test.go @@ -27,7 +27,8 @@ func TestAppStripe(t *testing.T) { // Test suite covering the stripe app t.Run("AppStripe", func(t *testing.T) { testSuite := AppHandlerTestSuite{ - Env: env, + Env: env, + namespace: "app-handler-test", } t.Run("Create", func(t *testing.T) { diff --git a/test/billing/adapter_test.go b/test/billing/adapter_test.go index 7fa403c5cc..2fa5303b5d 100644 --- a/test/billing/adapter_test.go +++ b/test/billing/adapter_test.go @@ -284,9 +284,8 @@ func (s *BillingAdapterTestSuite) TestDetailedLineHandling() { require.NoError(s.T(), err) lines[0].Children = childrenWithIDReuse - // Not set => should be ignored - lines[1].Children = billing.LineChildren{} // Set to empty array => detailed lines should be deleted + lines[1].Children = billing.LineChildren{} lines[2].Children = billing.NewLineChildren([]*billing.Line{}) // When we persist the changes @@ -314,11 +313,7 @@ func (s *BillingAdapterTestSuite) TestDetailedLineHandling() { return *l.ChildUniqueReferenceID == "ref1" }).UpdatedAt) - require.Len(s.T(), lines[1].Children, 1) - require.ElementsMatch(s.T(), - []string{"ref1"}, - getUniqReferenceNames(lines[1].Children)) - + require.Len(s.T(), lines[1].Children, 0) require.Len(s.T(), lines[2].Children, 0) }) diff --git a/test/billing/suite.go b/test/billing/suite.go index 979e10c15c..6d31db54a5 100644 --- a/test/billing/suite.go +++ b/test/billing/suite.go @@ -17,6 +17,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "go.opentelemetry.io/otel/trace/noop" "github.com/openmeterio/openmeter/app/config" "github.com/openmeterio/openmeter/openmeter/app" @@ -30,6 +31,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/customer" customeradapter "github.com/openmeterio/openmeter/openmeter/customer/adapter" customerservice "github.com/openmeterio/openmeter/openmeter/customer/service" + customerservicehooks "github.com/openmeterio/openmeter/openmeter/customer/service/hooks" "github.com/openmeterio/openmeter/openmeter/ent/db" "github.com/openmeterio/openmeter/openmeter/meter" meteradapter "github.com/openmeterio/openmeter/openmeter/meter/mockadapter" @@ -37,6 +39,10 @@ import ( "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" registrybuilder "github.com/openmeterio/openmeter/openmeter/registry/builder" streamingtestutils "github.com/openmeterio/openmeter/openmeter/streaming/testutils" + "github.com/openmeterio/openmeter/openmeter/subject" + subjectadapter "github.com/openmeterio/openmeter/openmeter/subject/adapter" + subjectservice "github.com/openmeterio/openmeter/openmeter/subject/service" + subjecthooks "github.com/openmeterio/openmeter/openmeter/subject/service/hooks" "github.com/openmeterio/openmeter/openmeter/testutils" "github.com/openmeterio/openmeter/openmeter/watermill/eventbus" "github.com/openmeterio/openmeter/pkg/currencyx" @@ -63,6 +69,7 @@ type BaseSuite struct { MockStreamingConnector *streamingtestutils.MockStreamingConnector CustomerService customer.Service + SubjectService subject.Service AppService app.Service SandboxApp *appsandbox.MockableFactory @@ -135,6 +142,14 @@ func (s *BaseSuite) SetupSuite() { s.FeatureRepo = entitlementRegistry.FeatureRepo s.FeatureService = entitlementRegistry.Feature + // Subject + subjectAdapter, err := subjectadapter.New(dbClient) + require.NoError(t, err) + + subjectService, err := subjectservice.New(subjectAdapter) + require.NoError(t, err) + s.SubjectService = subjectService + // Customer customerAdapter, err := customeradapter.New(customeradapter.Config{ @@ -198,6 +213,47 @@ func (s *BaseSuite) SetupSuite() { require.NoError(t, err) s.SandboxApp = sandboxApp + + // Hooks + + // Subject hooks + + subjectCustomerHook, err := subjecthooks.NewCustomerSubjectHook(subjecthooks.CustomerSubjectHookConfig{ + Subject: subjectService, + Logger: slog.Default(), + Tracer: noop.NewTracerProvider().Tracer("test_env"), + }) + require.NoError(t, err) + customerService.RegisterHooks(subjectCustomerHook) + + subjectEntitlementValidatorHook, err := subjecthooks.NewEntitlementValidatorHook(subjecthooks.EntitlementValidatorHookConfig{ + EntitlementService: entitlementRegistry.Entitlement, + }) + require.NoError(t, err) + subjectService.RegisterHooks(subjectEntitlementValidatorHook) + + // customer hooks + customerSubjectHook, err := customerservicehooks.NewSubjectCustomerHook(customerservicehooks.SubjectCustomerHookConfig{ + Customer: customerService, + CustomerOverride: billingService, + Logger: slog.Default(), + Tracer: noop.NewTracerProvider().Tracer("test_env"), + }) + require.NoError(t, err) + subjectService.RegisterHooks(customerSubjectHook) + + customerSubjectValidatorHook, err := customerservicehooks.NewSubjectValidatorHook(customerservicehooks.SubjectValidatorHookConfig{ + Customer: customerService, + Logger: slog.Default(), + }) + require.NoError(t, err) + subjectService.RegisterHooks(customerSubjectValidatorHook) + + entitlementValidatorHook, err := customerservicehooks.NewEntitlementValidatorHook(customerservicehooks.EntitlementValidatorHookConfig{ + EntitlementService: entitlementRegistry.Entitlement, + }) + require.NoError(t, err) + customerService.RegisterHooks(entitlementValidatorHook) } func (s *BaseSuite) InstallSandboxApp(t *testing.T, ns string) app.App { diff --git a/test/customer/customer.go b/test/customer/customer.go index 48a72cf743..7f816084f8 100644 --- a/test/customer/customer.go +++ b/test/customer/customer.go @@ -18,7 +18,7 @@ import ( "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" "github.com/openmeterio/openmeter/openmeter/productcatalog/plan" plansubscriptionservice "github.com/openmeterio/openmeter/openmeter/productcatalog/subscription/service" - subject "github.com/openmeterio/openmeter/openmeter/subject" + "github.com/openmeterio/openmeter/openmeter/subject" "github.com/openmeterio/openmeter/openmeter/subscription" "github.com/openmeterio/openmeter/pkg/clock" "github.com/openmeterio/openmeter/pkg/currencyx" @@ -765,9 +765,9 @@ func (s *CustomerHandlerTestSuite) TestDelete(ctx context.Context, t *testing.T) require.NoError(t, err, "Getting a deleted customer must not return error") require.NotNil(t, getCustomer.DeletedAt, "DeletedAt must not be nil") - // Delete the customer again should return not found error + // Delete the customer by id again should not return an error err = custService.DeleteCustomer(ctx, customerId) - require.True(t, models.IsGenericNotFoundError(err), "Deleting customer again must return not found error") + require.NoError(t, err, "Deleting customer by id must not return an error") // Should allow to create a customer with the same subject keys createdCustomer, err := custService.CreateCustomer(ctx, input) diff --git a/test/entitlement/regression/framework_test.go b/test/entitlement/regression/framework_test.go index dd871772cc..94499e6a6c 100644 --- a/test/entitlement/regression/framework_test.go +++ b/test/entitlement/regression/framework_test.go @@ -231,21 +231,22 @@ func setupDependencies(t *testing.T) Dependencies { } } -func createCustomerAndSubject(t *testing.T, subjectService subject.Service, customerService customer.Adapter, ns string, subjectKey string) *customer.Customer { +func createCustomerAndSubject(t *testing.T, subjectService subject.Service, customerService customer.Adapter, ns, key, name string) *customer.Customer { t.Helper() _, err := subjectService.Create(context.Background(), subject.CreateInput{ Namespace: ns, - Key: subjectKey, + Key: key, }) require.NoError(t, err) cust, err := customerService.CreateCustomer(context.Background(), customer.CreateCustomerInput{ Namespace: ns, CustomerMutate: customer.CustomerMutate{ - Key: lo.ToPtr(subjectKey), + Key: lo.ToPtr(key), UsageAttribution: customer.CustomerUsageAttribution{ - SubjectKeys: []string{subjectKey}, + SubjectKeys: []string{key}, }, + Name: name, }, }) require.NoError(t, err) diff --git a/test/entitlement/regression/scenario_test.go b/test/entitlement/regression/scenario_test.go index 09fe5b4bfe..80777fcf20 100644 --- a/test/entitlement/regression/scenario_test.go +++ b/test/entitlement/regression/scenario_test.go @@ -42,7 +42,7 @@ func TestGrantExpiringAtReset(t *testing.T) { assert.NotNil(feature) // create customer and subject - cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1") + cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1", "Subject 1") // Let's create a new entitlement for the feature @@ -193,7 +193,7 @@ func TestGrantExpiringAndRecurringAtReset(t *testing.T) { assert.NoError(err) assert.NotNil(feature) - cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1") + cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1", "Subject 1") // Let's create a new entitlement for the feature @@ -297,7 +297,7 @@ func TestBalanceCalculationsAfterVoiding(t *testing.T) { assert.NoError(err) assert.NotNil(feature) - cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1") + cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1", "Subject 1") // Let's create a new entitlement for the feature clock.SetTime(testutils.GetRFC3339Time(t, "2024-07-09T11:20:28Z")) @@ -400,7 +400,7 @@ func TestCreatingEntitlementsForKeyOfArchivedFeatures(t *testing.T) { assert.NoError(err) assert.NotNil(feat) - cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1") + cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1", "Subject 1") // Let's create a new entitlement for the feature clock.SetTime(testutils.GetRFC3339Time(t, "2024-07-09T11:20:28Z")) @@ -438,7 +438,7 @@ func TestCreatingEntitlementsForKeyOfArchivedFeatures(t *testing.T) { assert.NoError(err) assert.NotNil(feature2) - cust2 := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-2") + cust2 := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-2", "Subject 2") // Let's create a new entitlement for feature2 for subject-2 clock.SetTime(testutils.GetRFC3339Time(t, "2024-07-09T14:20:28Z")) @@ -476,7 +476,7 @@ func TestGrantingAfterOverage(t *testing.T) { assert.NoError(err) assert.NotNil(feature) - cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1") + cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1", "Subject 1") // Let's create a new entitlement for the feature clock.SetTime(testutils.GetRFC3339Time(t, "2024-08-22T11:25:00Z")) @@ -587,7 +587,7 @@ func TestBalanceWorkerActiveToFromEntitlementsMapping(t *testing.T) { assert.NoError(err) assert.NotNil(feature) - cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1") + cust := createCustomerAndSubject(t, deps.SubjectService, deps.CustomerService, "namespace-1", "subject-1", "Subject 1") // Let's create a new entitlement for the feature clock.SetTime(testutils.GetRFC3339Time(t, "2024-08-22T11:25:00Z")) diff --git a/test/subscription/scenario_editaligned_test.go b/test/subscription/scenario_editaligned_test.go index 2a7bc6d47a..d31f319470 100644 --- a/test/subscription/scenario_editaligned_test.go +++ b/test/subscription/scenario_editaligned_test.go @@ -14,7 +14,6 @@ import ( "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" "github.com/openmeterio/openmeter/openmeter/productcatalog/plan" pcsubscription "github.com/openmeterio/openmeter/openmeter/productcatalog/subscription" - "github.com/openmeterio/openmeter/openmeter/subject" "github.com/openmeterio/openmeter/openmeter/subscription" "github.com/openmeterio/openmeter/openmeter/subscription/patch" subscriptiontestutils "github.com/openmeterio/openmeter/openmeter/subscription/testutils" @@ -108,13 +107,6 @@ func TestEditingEntitlementOfAlignedSub(t *testing.T) { }) require.NoError(t, err) - // 3rd, let's create the subject first - _, err = tDeps.SubjectService.Create(ctx, subject.CreateInput{ - Namespace: namespace, - Key: "subject_1", - }) - require.NoError(t, err) - // Then create the customer c, err := tDeps.CustomerService.CreateCustomer(ctx, customer.CreateCustomerInput{ Namespace: namespace, diff --git a/test/subscription/scenario_editcancel_test.go b/test/subscription/scenario_editcancel_test.go index dfca7c1a07..6d10d625bc 100644 --- a/test/subscription/scenario_editcancel_test.go +++ b/test/subscription/scenario_editcancel_test.go @@ -15,7 +15,6 @@ import ( "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" "github.com/openmeterio/openmeter/openmeter/productcatalog/plan" pcsubscription "github.com/openmeterio/openmeter/openmeter/productcatalog/subscription" - "github.com/openmeterio/openmeter/openmeter/subject" "github.com/openmeterio/openmeter/openmeter/subscription" "github.com/openmeterio/openmeter/openmeter/subscription/patch" subscriptiontestutils "github.com/openmeterio/openmeter/openmeter/subscription/testutils" @@ -106,13 +105,6 @@ func TestEditingAndCanceling(t *testing.T) { }) require.NoError(t, err) - // Third, let's create the subjects first - _, err = tDeps.SubjectService.Create(ctx, subject.CreateInput{ - Namespace: namespace, - Key: "subject_1", - }) - require.NoError(t, err) - // Then create the customer c, err := tDeps.CustomerService.CreateCustomer(ctx, customer.CreateCustomerInput{ Namespace: namespace, @@ -134,21 +126,13 @@ func TestEditingAndCanceling(t *testing.T) { // And let's create extra customers (with their subjects) custs := []*customer.Customer{} for i := 0; i < 10; i++ { - // Create subject first - subjectKey := fmt.Sprintf("subject_%d", i+2) - _, err := tDeps.SubjectService.Create(ctx, subject.CreateInput{ - Namespace: namespace, - Key: subjectKey, - }) - require.NoError(t, err) - // Then create customer c, err := tDeps.CustomerService.CreateCustomer(ctx, customer.CreateCustomerInput{ Namespace: namespace, CustomerMutate: customer.CustomerMutate{ Name: "Test Customer", UsageAttribution: customer.CustomerUsageAttribution{ - SubjectKeys: []string{subjectKey}, + SubjectKeys: []string{fmt.Sprintf("subject_%d", i+2)}, }, }, }) diff --git a/test/subscription/scenario_entinnextphase_test.go b/test/subscription/scenario_entinnextphase_test.go index bcaa05d91b..00ec8765b3 100644 --- a/test/subscription/scenario_entinnextphase_test.go +++ b/test/subscription/scenario_entinnextphase_test.go @@ -12,7 +12,6 @@ import ( "github.com/openmeterio/openmeter/openmeter/productcatalog" "github.com/openmeterio/openmeter/openmeter/productcatalog/plan" pcsubscription "github.com/openmeterio/openmeter/openmeter/productcatalog/subscription" - "github.com/openmeterio/openmeter/openmeter/subject" subscription "github.com/openmeterio/openmeter/openmeter/subscription" subscriptionworkflow "github.com/openmeterio/openmeter/openmeter/subscription/workflow" "github.com/openmeterio/openmeter/openmeter/testutils" @@ -132,13 +131,6 @@ func TestSubWithMeteredEntitlement(t *testing.T) { _, err = tDeps.billingService.CreateProfile(ctx, minimalCreateProfileInputTemplate(tDeps.sandboxApp.GetID())) require.NoError(t, err) - // 4th, let's create the subject first - _, err = tDeps.SubjectService.Create(ctx, subject.CreateInput{ - Namespace: namespace, - Key: "subject_1", - }) - require.NoError(t, err) - // Then create the customer c, err := tDeps.CustomerService.CreateCustomer(ctx, customer.CreateCustomerInput{ Namespace: namespace, diff --git a/test/subscription/scenario_firstofmonth_test.go b/test/subscription/scenario_firstofmonth_test.go index 117ea94322..0fc9180951 100644 --- a/test/subscription/scenario_firstofmonth_test.go +++ b/test/subscription/scenario_firstofmonth_test.go @@ -16,7 +16,6 @@ import ( "github.com/openmeterio/openmeter/openmeter/productcatalog" "github.com/openmeterio/openmeter/openmeter/productcatalog/plan" pcsubscription "github.com/openmeterio/openmeter/openmeter/productcatalog/subscription" - "github.com/openmeterio/openmeter/openmeter/subject" subscription "github.com/openmeterio/openmeter/openmeter/subscription" subscriptionworkflow "github.com/openmeterio/openmeter/openmeter/subscription/workflow" "github.com/openmeterio/openmeter/openmeter/testutils" @@ -28,7 +27,7 @@ import ( func TestBillingOnFirstOfMonth(t *testing.T) { // Let's declare our variables - // note: this namespace is hardcoded in the test framework + // note: this namespace is hardcoded in the test framework (TuriP: why on earth is it hardcoded in the test framework?) namespace := "test-namespace" startOfSub := testutils.GetRFC3339Time(t, "2025-06-15T12:00:00Z") @@ -151,13 +150,6 @@ func TestBillingOnFirstOfMonth(t *testing.T) { _, err = tDeps.billingService.CreateProfile(ctx, minimalCreateProfileInputTemplate(tDeps.sandboxApp.GetID())) require.NoError(t, err) - // 3rd, let's create the subject first - _, err = tDeps.SubjectService.Create(ctx, subject.CreateInput{ - Namespace: namespace, - Key: "subject_1", - }) - require.NoError(t, err) - // Then create the customer c, err := tDeps.CustomerService.CreateCustomer(ctx, customer.CreateCustomerInput{ Namespace: namespace, diff --git a/tools/migrate/billing_test.go b/tools/migrate/billing_test.go deleted file mode 100644 index 5ccba50e6c..0000000000 --- a/tools/migrate/billing_test.go +++ /dev/null @@ -1,223 +0,0 @@ -package migrate_test - -import ( - "context" - "database/sql" - "encoding/json" - "fmt" - "os" - "strings" - "testing" - "time" - - "github.com/oklog/ulid/v2" - "github.com/stretchr/testify/require" - - v20250605102416 "github.com/openmeterio/openmeter/tools/migrate/testdata/sqlcgen/20250605102416/db" - v20250609172811 "github.com/openmeterio/openmeter/tools/migrate/testdata/sqlcgen/20250609172811/db" -) - -func TestMigrateFlatFeesToUBPFlatFees(t *testing.T) { - runner{stops{ - { - version: 20250605102416, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - loadFixture(t, db, "testdata/sqlcgen/20250605102416/fixture.sql") - }, - }, - { - version: 20250605131637, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - const ( - validFlatFeeLineID = "01JWB2ND43KPCHMXHKD0KETF5M" - validFlatFeeLineIDWithInvoicingExternalID = "01JWB2ND43KPCHMXHKCYEQ13WY" - deletedFlatFeeLineID = "01JWB2ND43KPCHMXHKCW3PFW6W" - ) - - q := v20250605102416.New(db) - t.Run("valid flat fee line", func(t *testing.T) { - // Case 1: Valid flat fee line - - lines, err := q.GetLineHierarchyByDetailedLineID(t.Context(), validFlatFeeLineID) - require.NoError(t, err) - - require.Len(t, lines.DetailedLines, 1) - detailedLine := lines.DetailedLines[0] - ubpLine := lines.Line - - // the ulid generated by pgsql is a valid one - parsedID, err := ulid.Parse(ubpLine.ID) - require.NoError(t, err) - require.Equal(t, parsedID.String(), ubpLine.ID) - - // Let's fetch the child lines - require.NoError(t, err) - - // Let's assert the ubp line - require.Equal(t, detailedLine.ID, validFlatFeeLineID) - require.Equal(t, ubpLine.Namespace, detailedLine.Namespace) - - // Field validations (no ID missmatch) - require.NotEqual(t, detailedLine.ID, ubpLine.ID) - - // Lines are not deleted - require.False(t, ubpLine.DeletedAt.Valid) - - // Detailed line changes - require.Equal(t, detailedLine.ChildUniqueReferenceID.String, "flat-price") - require.False(t, detailedLine.DeletedAt.Valid, "detailed line should not be deleted") - require.Equal(t, detailedLine.ManagedBy, "system") - require.False(t, detailedLine.SubscriptionID.Valid, "detailed line should not have a subscription") - require.False(t, detailedLine.SubscriptionItemID.Valid, "detailed line should not have a subscription item") - require.False(t, detailedLine.SubscriptionPhaseID.Valid, "detailed line should not have a subscription phase") - require.False(t, detailedLine.Metadata.Valid, "detailed line should not have metadata") - - // UBP line changes - require.True(t, strings.HasSuffix(ubpLine.ChildUniqueReferenceID.String, "/first-phase/in-advance/v[0]/period[2]")) - - // metadata - metadata := map[string]string{} - err = json.Unmarshal(ubpLine.Metadata.RawMessage, &metadata) - require.NoError(t, err) - require.Equal(t, metadata["/openmeter-line-reason"], "add-line-wrapping", "metadata should be added signifying why we have added this line") - - // price - price := map[string]string{} - err = json.Unmarshal(ubpLine.Price, &price) - require.NoError(t, err) - require.Equal(t, price["type"], "flat", "price type should be flat") - require.Equal(t, price["amount"], "6", "price amount should be 6") - require.Equal(t, price["paymentTerm"], "in_advance", "price payment term should be in_advance") - - // other fields - require.Equal(t, ubpLine.PriceType, "flat", "price type should be flat") - require.Equal(t, ubpLine.Quantity.String, "1", "quantity should be 1") - require.Equal(t, ubpLine.PreLinePeriodQuantity.String, "0", "pre line period quantity should be 0") - require.Equal(t, ubpLine.MeteredQuantity.String, "1", "metered quantity should be 1") - require.Equal(t, ubpLine.MeteredPreLinePeriodQuantity.String, "0", "metered pre line period quantity should be 0") - require.False(t, ubpLine.ParentLineID.Valid, "there should be no parent line for the ubp one") - require.NotEmpty(t, ubpLine.InvoiceID, "the invoice id should be valid") - - require.Equal(t, ubpLine.InvoiceID, detailedLine.InvoiceID, "the invoice id should be the same") - require.Equal(t, ubpLine.Amount, detailedLine.Amount) - require.Equal(t, ubpLine.Total, detailedLine.Total) - require.Equal(t, "6", ubpLine.Total) - require.Equal(t, "6", ubpLine.Amount) - }) - - t.Run("valid flat fee line with invoicing external id", func(t *testing.T) { - lines, err := q.GetLineHierarchyByDetailedLineID(t.Context(), validFlatFeeLineIDWithInvoicingExternalID) - require.NoError(t, err) - - require.Len(t, lines.DetailedLines, 1) - detailedLine := lines.DetailedLines[0] - ubpLine := lines.Line - - // detailed lines must have invoicing external id set, while the ubp line should not - require.Equal(t, detailedLine.InvoicingAppExternalID.String, "invoicing-external-id", "detailed line should have invoicing external id set") - require.False(t, ubpLine.InvoicingAppExternalID.Valid, "ubp line should not have invoicing external id set") - }) - - t.Run("deleted flat fee line", func(t *testing.T) { - lines, err := q.GetLineHierarchyByDetailedLineID(t.Context(), deletedFlatFeeLineID) - require.NoError(t, err) - - require.Len(t, lines.DetailedLines, 1) - detailedLine := lines.DetailedLines[0] - ubpLine := lines.Line - - require.True(t, ubpLine.DeletedAt.Valid, "ubp line should be deleted") - require.True(t, detailedLine.DeletedAt.Valid, "detailed line should be deleted") - require.Equal(t, detailedLine.DeletedAt.Time, ubpLine.DeletedAt.Time, "detailed line and ubp line should have the same deleted at") - }) - }, - }, - }}.Test(t) -} - -func TestMigrateSplitLinesToSplitLineGroups(t *testing.T) { - var preMigrationLineCountsByType map[string]int64 - runner{stops{ - { - version: 20250609172811, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - loadFixture(t, db, "testdata/sqlcgen/20250609172811/fixture.sql") - - q := v20250609172811.New(db) - lineCounts, err := q.CountLinesByStatusType(t.Context()) - require.NoError(t, err) - - preMigrationLineCountsByType = make(map[string]int64) - for _, lineCount := range lineCounts { - preMigrationLineCountsByType[fmt.Sprintf("%s-%s", lineCount.Status, lineCount.Type)] = lineCount.Count - } - }, - }, - { - version: 20250609204117, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - const ( - SplitLineGroupID = "01JXA7Y5CRJF0NJ5ADKNZVDTGH" - ) - q := v20250609172811.New(db) - - t.Run("split line group exists", func(t *testing.T) { - splitLineGroup, err := q.GetSplitLineGroup(t.Context(), SplitLineGroupID) - require.NoError(t, err) - - require.Equal(t, SplitLineGroupID, splitLineGroup.ID) - require.Equal(t, "ns-ubp-invoicing-progressive", splitLineGroup.Namespace) - require.Equal(t, "flat-per-unit", splitLineGroup.FeatureKey.String) - require.Equal(t, `{"type": "unit", "amount": "100", "maximumAmount": "2000"}`, string(splitLineGroup.Price)) - require.Equal(t, "2024-09-02T12:13:00Z", splitLineGroup.ServicePeriodStart.Format(time.RFC3339)) - require.Equal(t, "2024-09-03T12:13:00Z", splitLineGroup.ServicePeriodEnd.Format(time.RFC3339)) - }) - - t.Run("line counts are unchanged except of the split line", func(t *testing.T) { - lineCounts, err := q.CountLinesByStatusType(t.Context()) - require.NoError(t, err) - - postMigrationLineCountsByType := make(map[string]int64) - for _, lineCount := range lineCounts { - postMigrationLineCountsByType[fmt.Sprintf("%s-%s", lineCount.Status, lineCount.Type)] = lineCount.Count - } - - delete(preMigrationLineCountsByType, "split-usage_based") - - require.Equal(t, preMigrationLineCountsByType, postMigrationLineCountsByType) - }) - - t.Run("split line group is associated with the correct lines", func(t *testing.T) { - splitLineGroup, err := q.GetSplitLineGroup(t.Context(), SplitLineGroupID) - require.NoError(t, err) - - lines, err := q.GetUsageBasedLinesBySplitLineGroup(t.Context(), sql.NullString{String: SplitLineGroupID, Valid: true}) - require.NoError(t, err) - - require.Len(t, lines, 2) - for _, line := range lines { - require.Equal(t, SplitLineGroupID, line.SplitLineGroupID.String) - require.Equal(t, splitLineGroup.FeatureKey.String, line.FeatureKey.String) - require.Equal(t, splitLineGroup.Price, line.Price) - } - }) - }, - }, - }}.Test(t) -} - -// loadFixture loads a fixture SQL file into the database -// -// If you find a better alternative, please replace this function, as it does not understand the SQL syntax, and -// it's barely enough to load the fixture. -func loadFixture(t *testing.T, db *sql.DB, fixturePath string) { - sqlBytes, err := os.ReadFile(fixturePath) - require.NoError(t, err) - - _, err = db.ExecContext(context.Background(), string(sqlBytes)) - require.NoError(t, err) -} diff --git a/tools/migrate/entitlement_test.go b/tools/migrate/entitlement_test.go deleted file mode 100644 index 678c229a8e..0000000000 --- a/tools/migrate/entitlement_test.go +++ /dev/null @@ -1,2378 +0,0 @@ -package migrate_test - -import ( - "context" - "database/sql" - "encoding/json" - "regexp" - "testing" - "time" - - "github.com/oklog/ulid/v2" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/openmeterio/openmeter/openmeter/testutils" - "github.com/openmeterio/openmeter/pkg/datetime" - v20250624115812 "github.com/openmeterio/openmeter/tools/migrate/testdata/sqlcgen/20250624115812/db" - v20250703081943 "github.com/openmeterio/openmeter/tools/migrate/testdata/sqlcgen/20250703081943/db" -) - -func TestUsageResetAnchorTimesMigration(t *testing.T) { - entId1 := ulid.Make() - ent1UPAnchor := testutils.GetRFC3339Time(t, "2025-02-01T00:00:00Z") - ent1ur1Id := ulid.Make() - ent1ur2Id := ulid.Make() - - runner{ - stops: stops{ - { - // before: 20250218161614_billing-profile-fix-constraint.up.sql - // after: 20250220150245_usage-reset-anchor-times.up.sql - version: 20250218161614, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // 1. We need to set up a feature - featId := ulid.Make() - _, err := db.Exec(` - INSERT INTO features ( - namespace, - id, - key, - name, - created_at, - updated_at - ) - VALUES ( - 'default', - $1, - 'feat_1', - 'feat 1', - NOW(), -- don't mind that this is later than entitlement creation time, the DB doesn't care about it - NOW() -- don't mind that this is later than entitlement creation time, the DB doesn't care about it - )`, - featId.String(), - ) - require.NoError(t, err) - - // 2. We need to set up an entitlement - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - usage_period_interval, - usage_period_anchor - ) - VALUES ( - 'default', - $1, - '2025-02-01 23:18:35', - NOW(), - 'METERED', - 'feature_1', - $2, - 'subject_1', - 'MONTH', - $3 - )`, - entId1.String(), - featId.String(), - ent1UPAnchor, - ) - require.NoError(t, err) - - // 3. We need to set up 2 (so it can correctly choose the last one) past usage resets that show some usage - _, err = db.Exec(` - INSERT INTO usage_resets (namespace, id, created_at, updated_at, entitlement_id, reset_time) - VALUES ('default', $1, NOW(), NOW(), $2, '2025-02-05T12:00:00Z')`, - ent1ur1Id.String(), - entId1.String(), - ) - require.NoError(t, err) - - _, err = db.Exec(` - INSERT INTO usage_resets (namespace, id, created_at, updated_at, entitlement_id, reset_time) - VALUES ('default', $1, NOW(), NOW(), $2, '2025-02-011T12:00:00Z')`, - ent1ur2Id.String(), - entId1.String(), - ) - require.NoError(t, err) - }, - }, - { - // After subjects table is created, seed subjects used earlier so later migrations can backfill subject_id - version: 20250606115859, // subject_namespace.up.sql - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - _, err := db.Exec(`INSERT INTO subjects (namespace, id, key, created_at, updated_at) VALUES ('default', $1, 'subject_1', NOW(), NOW())`, ulid.Make().String()) - require.NoError(t, err) - }, - }, - { - // Now we assert that the migration was successful - version: 20250220150245, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Let's assert that for for the first usage-reset (as its not the latest) the anchor is set to the reset time of the usage_reset - var anchor time.Time - var resetTime time.Time - err := db.QueryRow(`SELECT anchor, reset_time FROM usage_resets WHERE id = $1`, ent1ur1Id.String()).Scan(&anchor, &resetTime) - require.NoError(t, err) - require.Equal(t, resetTime, anchor) - - // Let's assert that the second usage-reset was updated with the entitlement's usage_period_anchor - var anchor2 time.Time - err = db.QueryRow(`SELECT anchor FROM usage_resets WHERE id = $1`, ent1ur2Id.String()).Scan(&anchor2) - require.NoError(t, err) - require.Equal(t, ent1UPAnchor, anchor2.UTC()) - }, - }, - }, - }.Test(t) -} - -func TestEntitlementSubscriptionAnnotationMigration(t *testing.T) { - entId := ulid.Make() - featId := ulid.Make() - subId := ulid.Make() - custId := ulid.Make() - phaseId := ulid.Make() - itemId := ulid.Make() - planId := ulid.Make() - - // Add IDs for the additional entitlements - nonSubManagedEntId := ulid.Make() - noItemEntId := ulid.Make() - - runner{ - stops: stops{ - { - // before: 20250325115141_ent-subs-annotation.up.sql - // Using the previous migration version - version: 20250325114848, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // 1. Create a feature - _, err := db.Exec(` - INSERT INTO features ( - namespace, - id, - key, - name, - created_at, - updated_at - ) - VALUES ( - 'default', - $1, - 'feat_1', - 'feat 1', - NOW(), - NOW() - )`, - featId.String(), - ) - require.NoError(t, err) - - // 2. Create a customer - _, err = db.Exec(` - INSERT INTO customers ( - namespace, - id, - created_at, - updated_at, - key, - name - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'cust_1', - 'Customer 1' - )`, - custId.String(), - ) - require.NoError(t, err) - - // 3. Create a plan - _, err = db.Exec(` - INSERT INTO plans ( - namespace, - id, - created_at, - updated_at, - key, - version, - name - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'plan_1', - 1, - 'Test Plan' - )`, - planId.String(), - ) - require.NoError(t, err) - - // 4. Create a subscription - _, err = db.Exec(` - INSERT INTO subscriptions ( - namespace, - id, - created_at, - updated_at, - active_from, - plan_id, - currency, - customer_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - NOW(), - $2, - 'USD', - $3 - )`, - subId.String(), - planId.String(), - custId.String(), - ) - require.NoError(t, err) - - // 5. Create a subscription phase - _, err = db.Exec(` - INSERT INTO subscription_phases ( - namespace, - id, - created_at, - updated_at, - key, - name, - active_from, - subscription_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'phase_1', - 'Phase 1', - NOW(), - $2 - )`, - phaseId.String(), - subId.String(), - ) - require.NoError(t, err) - - // 6. Create a subscription-managed entitlement without annotations - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - subscription_managed - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'METERED', - 'feature_1', - $2, - 'subject_1', - TRUE - )`, - entId.String(), - featId.String(), - ) - require.NoError(t, err) - - // 7. Create a non-subscription-managed entitlement - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - subscription_managed - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'METERED', - 'feature_1', - $2, - 'subject_2', - FALSE - )`, - nonSubManagedEntId.String(), - featId.String(), - ) - require.NoError(t, err) - - // 8. Create a subscription-managed entitlement without subscription item - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - subscription_managed - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'METERED', - 'feature_1', - $2, - 'subject_3', - TRUE - )`, - noItemEntId.String(), - featId.String(), - ) - require.NoError(t, err) - - // 9. Create a subscription item linked to the entitlement - _, err = db.Exec(` - INSERT INTO subscription_items ( - namespace, - id, - created_at, - updated_at, - active_from, - key, - name, - phase_id, - entitlement_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - NOW(), - 'item_1', - 'Item 1', - $2, - $3 - )`, - itemId.String(), - phaseId.String(), - entId.String(), - ) - require.NoError(t, err) - }, - }, - { - // After subjects table exists, seed subjects used by created entitlements so later migrations succeed - version: 20250606115859, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - for _, sk := range []string{"subject_1", "subject_2", "subject_3"} { - _, err := db.Exec(`INSERT INTO subjects (namespace, id, key, created_at, updated_at) VALUES ('default', $1, $2, NOW(), NOW())`, ulid.Make().String(), sk) - require.NoError(t, err) - } - }, - }, - { - // After our migration - version: 20250325115141, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Check that the subscription.id annotation was added to the entitlement - var annotationsJSON string - err := db.QueryRow(` - SELECT annotations::text - FROM entitlements - WHERE id = $1 - `, entId.String()).Scan(&annotationsJSON) - require.NoError(t, err) - - // Parse the JSON and properly validate the structure - annotations := make(map[string]interface{}) - err = json.Unmarshal([]byte(annotationsJSON), &annotations) - require.NoError(t, err) - - // Verify the subscription.id is set correctly - subscriptionID, ok := annotations["subscription.id"] - require.True(t, ok, "subscription.id annotation not found") - require.Equal(t, subId.String(), subscriptionID) - - // Check that non-subscription-managed entitlement doesn't have annotations - var nonSubManagedAnnotations sql.NullString - err = db.QueryRow(` - SELECT annotations::text - FROM entitlements - WHERE id = $1 - `, nonSubManagedEntId.String()).Scan(&nonSubManagedAnnotations) - require.NoError(t, err) - require.False(t, nonSubManagedAnnotations.Valid, "non-subscription-managed entitlement should not have annotations") - - // Check that subscription-managed entitlement without item doesn't have annotations - var noItemAnnotations sql.NullString - err = db.QueryRow(` - SELECT annotations::text - FROM entitlements - WHERE id = $1 - `, noItemEntId.String()).Scan(&noItemAnnotations) - require.NoError(t, err) - require.False(t, noItemAnnotations.Valid, "subscription-managed entitlement without item should not have annotations") - }, - }, - { - // After 20250325115141_ent-subs-annotation.down.sql - version: 20250325114848, - direction: directionDown, - action: func(t *testing.T, db *sql.DB) { - // Check that the subscription.id annotation was removed - var annotationsJSON sql.NullString - err := db.QueryRow(` - SELECT annotations::text - FROM entitlements - WHERE id = $1 - `, entId.String()).Scan(&annotationsJSON) - require.NoError(t, err) - - // If we have annotations (not NULL) - if annotationsJSON.Valid { - // Parse the JSON and verify subscription.id is not present - annotations := make(map[string]interface{}) - err = json.Unmarshal([]byte(annotationsJSON.String), &annotations) - require.NoError(t, err) - - _, hasSubscriptionId := annotations["subscription.id"] - require.False(t, hasSubscriptionId, "subscription.id annotation should have been removed") - } - // If annotations is NULL, no need to check further as there's definitely no subscription.id - }, - }, - { - // We need to add back the subscription_managed=true to our entitlement as the column gets removed in later migration - version: 20250325115141, - direction: directionDown, - action: func(t *testing.T, db *sql.DB) { - // Update the subscription_managed value is set to true for all relevant entitlements - _, err := db.Exec(` - UPDATE entitlements - SET subscription_managed = TRUE - WHERE id IN ($1, $2) - `, entId.String(), noItemEntId.String()) - require.NoError(t, err) - }, - }, - }, - }.Test(t) -} - -func TestBooleanEntitlementCountAnnotationMigration(t *testing.T) { - // Create ULIDs for all entities we'll need - featId := ulid.Make() - entId := ulid.Make() - subId := ulid.Make() - custId := ulid.Make() - phaseId := ulid.Make() - itemId := ulid.Make() - planId := ulid.Make() - - // Create a second subscription item with an existing annotations field - itemId2 := ulid.Make() - entId2 := ulid.Make() - - // Create a third subscription item that doesn't have a boolean entitlement - itemId3 := ulid.Make() - entId3 := ulid.Make() - - runner{ - stops: stops{ - { - // Before our migration - version: 20250422174622, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // 1. Create a feature - _, err := db.Exec(` - INSERT INTO features ( - namespace, - id, - key, - name, - created_at, - updated_at - ) - VALUES ( - 'default', - $1, - 'feat_1', - 'feat 1', - NOW(), - NOW() - )`, - featId.String(), - ) - require.NoError(t, err) - - // 2. Create a customer - _, err = db.Exec(` - INSERT INTO customers ( - namespace, - id, - created_at, - updated_at, - key, - name - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'cust_1', - 'Customer 1' - )`, - custId.String(), - ) - require.NoError(t, err) - - // 3. Create a plan - _, err = db.Exec(` - INSERT INTO plans ( - namespace, - id, - created_at, - updated_at, - key, - version, - name - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'plan_1', - 1, - 'Test Plan' - )`, - planId.String(), - ) - require.NoError(t, err) - - // 4. Create a subscription - _, err = db.Exec(` - INSERT INTO subscriptions ( - namespace, - id, - created_at, - updated_at, - active_from, - plan_id, - currency, - customer_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - NOW(), - $2, - 'USD', - $3 - )`, - subId.String(), - planId.String(), - custId.String(), - ) - require.NoError(t, err) - - // 5. Create a subscription phase - _, err = db.Exec(` - INSERT INTO subscription_phases ( - namespace, - id, - created_at, - updated_at, - key, - name, - active_from, - subscription_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'phase_1', - 'Phase 1', - NOW(), - $2 - )`, - phaseId.String(), - subId.String(), - ) - require.NoError(t, err) - - // 6. Create boolean entitlements - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'boolean', - 'feat_1', - $2, - 'subject_1' - )`, - entId.String(), - featId.String(), - ) - require.NoError(t, err) - - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - annotations - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'boolean', - 'feat_1', - $2, - 'subject_2', - '{"existing.key": "some-value"}' - )`, - entId2.String(), - featId.String(), - ) - require.NoError(t, err) - - // Create a metered entitlement (not boolean) - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'metered', - 'feat_1', - $2, - 'subject_3' - )`, - entId3.String(), - featId.String(), - ) - require.NoError(t, err) - - // 7. Create subscription items linked to the entitlements - _, err = db.Exec(` - INSERT INTO subscription_items ( - namespace, - id, - created_at, - updated_at, - active_from, - key, - name, - phase_id, - entitlement_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - NOW(), - 'item_1', - 'Item 1', - $2, - $3 - )`, - itemId.String(), - phaseId.String(), - entId.String(), - ) - require.NoError(t, err) - - // Second item with existing annotations - _, err = db.Exec(` - INSERT INTO subscription_items ( - namespace, - id, - created_at, - updated_at, - active_from, - key, - name, - phase_id, - entitlement_id, - annotations - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - NOW(), - 'item_2', - 'Item 2', - $2, - $3, - '{"existing.annotation": "value"}' - )`, - itemId2.String(), - phaseId.String(), - entId2.String(), - ) - require.NoError(t, err) - - // Third item linked to a metered entitlement - _, err = db.Exec(` - INSERT INTO subscription_items ( - namespace, - id, - created_at, - updated_at, - active_from, - key, - name, - phase_id, - entitlement_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - NOW(), - 'item_3', - 'Item 3', - $2, - $3 - )`, - itemId3.String(), - phaseId.String(), - entId3.String(), - ) - require.NoError(t, err) - }, - }, - { - // After subjects table exists, seed subjects used by created entitlements so later migrations succeed - version: 20250606115859, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - for _, sk := range []string{"subject_1", "subject_2", "subject_3"} { - _, err := db.Exec(`INSERT INTO subjects (namespace, id, key, created_at, updated_at) VALUES ('default', $1, $2, NOW(), NOW())`, ulid.Make().String(), sk) - require.NoError(t, err) - } - }, - }, - { - // After our migration - version: 20250424160933, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Check item with no previous annotations - var annotationsJSON string - err := db.QueryRow(` - SELECT annotations::text - FROM subscription_items - WHERE id = $1 - `, itemId.String()).Scan(&annotationsJSON) - require.NoError(t, err) - - annotations := make(map[string]interface{}) - err = json.Unmarshal([]byte(annotationsJSON), &annotations) - require.NoError(t, err) - - // Verify the boolean count annotation is set correctly - booleanCount, ok := annotations["subscription.entitlement.boolean.count"] - require.True(t, ok, "subscription.entitlement.boolean.count annotation not found") - require.Equal(t, float64(1), booleanCount) // JSON unmarshals numbers as float64 - - // Check item with existing annotations - err = db.QueryRow(` - SELECT annotations::text - FROM subscription_items - WHERE id = $1 - `, itemId2.String()).Scan(&annotationsJSON) - require.NoError(t, err) - - annotations = make(map[string]interface{}) - err = json.Unmarshal([]byte(annotationsJSON), &annotations) - require.NoError(t, err) - - // Verify both annotations exist - booleanCount, ok = annotations["subscription.entitlement.boolean.count"] - require.True(t, ok, "subscription.entitlement.boolean.count annotation not found") - require.Equal(t, float64(1), booleanCount) - - existingValue, ok := annotations["existing.annotation"] - require.True(t, ok, "existing annotation not preserved") - require.Equal(t, "value", existingValue) - - // Check that metered entitlement item doesn't have the boolean count annotation - var nonBooleanAnnotations sql.NullString - err = db.QueryRow(` - SELECT annotations::text - FROM subscription_items - WHERE id = $1 - `, itemId3.String()).Scan(&nonBooleanAnnotations) - require.NoError(t, err) - - if nonBooleanAnnotations.Valid { - annotations = make(map[string]interface{}) - err = json.Unmarshal([]byte(nonBooleanAnnotations.String), &annotations) - require.NoError(t, err) - - _, ok = annotations["subscription.entitlement.boolean.count"] - require.False(t, ok, "non-boolean entitlement should not have boolean count annotation") - } - }, - }, - { - // Test down migration - version: 20250422174622, - direction: directionDown, - action: func(t *testing.T, db *sql.DB) { - // Check that first item's annotation was removed - var annotations sql.NullString - err := db.QueryRow(` - SELECT annotations::text - FROM subscription_items - WHERE id = $1 - `, itemId.String()).Scan(&annotations) - require.NoError(t, err) - - // Since this item only had the boolean count annotation, it should now be NULL - require.False(t, annotations.Valid, "annotations should be NULL after down migration") - - // Check that the second item's annotation was properly modified - var annotationsJSON string - err = db.QueryRow(` - SELECT annotations::text - FROM subscription_items - WHERE id = $1 - `, itemId2.String()).Scan(&annotationsJSON) - require.NoError(t, err) - - annotationsMap := make(map[string]interface{}) - err = json.Unmarshal([]byte(annotationsJSON), &annotationsMap) - require.NoError(t, err) - - // Verify boolean count annotation was removed - _, ok := annotationsMap["subscription.entitlement.boolean.count"] - require.False(t, ok, "boolean count annotation should be removed") - - // Verify existing annotation still exists - existingValue, ok := annotationsMap["existing.annotation"] - require.True(t, ok, "existing annotation should be preserved") - require.Equal(t, "value", existingValue) - }, - }, - }, - }.Test(t) -} - -func TestUsageResetUsagePeriodIntervalMigration(t *testing.T) { - entId1 := ulid.Make() - entId2 := ulid.Make() - featId1 := ulid.Make() - featId2 := ulid.Make() - ur1Id := ulid.Make() - ur2Id := ulid.Make() - ur3Id := ulid.Make() - - runner{ - stops: stops{ - { - // before: 20250703081943_entitlement-usageperiod-interval-change.up.sql - version: 20250624115812, // Using the actual version before our migration - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Use SQLC-generated queries for type-safe database operations - q := v20250624115812.New(db) - ctx := context.Background() - now := time.Now() - - // 1. Set up features - err := q.CreateFeature(ctx, v20250624115812.CreateFeatureParams{ - Namespace: "default", - ID: featId1.String(), - Key: "feat_1", - Name: "Feature 1", - CreatedAt: now, - UpdatedAt: now, - }) - require.NoError(t, err) - - err = q.CreateFeature(ctx, v20250624115812.CreateFeatureParams{ - Namespace: "default", - ID: featId2.String(), - Key: "feat_2", - Name: "Feature 2", - CreatedAt: now, - UpdatedAt: now, - }) - require.NoError(t, err) - - // 2. Set up entitlements with different usage_period_intervals - err = q.CreateEntitlement(ctx, v20250624115812.CreateEntitlementParams{ - Namespace: "default", - ID: entId1.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "METERED", - FeatureKey: "feat_1", - FeatureID: featId1.String(), - SubjectKey: "subject_1", - UsagePeriodInterval: sql.NullString{String: "P1W", Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: now, Valid: true}, - }) - require.NoError(t, err) - - // Second entitlement with different interval - err = q.CreateEntitlement(ctx, v20250624115812.CreateEntitlementParams{ - Namespace: "default", - ID: entId2.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "METERED", - FeatureKey: "feat_2", - FeatureID: featId2.String(), - SubjectKey: "subject_2", - UsagePeriodInterval: sql.NullString{String: "P1Y", Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: now, Valid: true}, - }) - require.NoError(t, err) - - // 3. Set up usage resets - err = q.CreateUsageReset(ctx, v20250624115812.CreateUsageResetParams{ - Namespace: "default", - ID: ur1Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId1.String(), - ResetTime: now, - Anchor: now, - }) - require.NoError(t, err) - - err = q.CreateUsageReset(ctx, v20250624115812.CreateUsageResetParams{ - Namespace: "default", - ID: ur2Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId1.String(), - ResetTime: now, - Anchor: now, - }) - require.NoError(t, err) - - err = q.CreateUsageReset(ctx, v20250624115812.CreateUsageResetParams{ - Namespace: "default", - ID: ur3Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId2.String(), - ResetTime: now, - Anchor: now, - }) - require.NoError(t, err) - - // Verify that usage_period_interval column doesn't exist in usage_resets yet - _, err = db.Exec(`SELECT usage_period_interval FROM usage_resets LIMIT 1`) - require.Error(t, err, "usage_period_interval column should not exist before migration") - }, - }, - { - // After our migration - version: 20250703081943, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Use SQLC-generated queries for the post-migration schema - q := v20250703081943.New(db) - ctx := context.Background() - - // Verify the column was added and populated correctly - interval1, err := q.GetUsageResetInterval(ctx, ur1Id.String()) - require.NoError(t, err) - require.Equal(t, "P1W", interval1, "usage_period_interval should match entitlement's interval") - - interval2, err := q.GetUsageResetInterval(ctx, ur2Id.String()) - require.NoError(t, err) - require.Equal(t, "P1W", interval2, "usage_period_interval should match entitlement's interval") - - interval3, err := q.GetUsageResetInterval(ctx, ur3Id.String()) - require.NoError(t, err) - require.Equal(t, "P1Y", interval3, "usage_period_interval should match entitlement's interval") - - // Verify the column is NOT NULL - try to insert with an empty string (which should be invalid) - // Note: Since SQLC expects a string type, we can't actually pass NULL through it, - // but we can test with raw SQL to verify the NOT NULL constraint - _, err = db.Exec(`INSERT INTO usage_resets (namespace, id, created_at, updated_at, entitlement_id, reset_time, anchor, usage_period_interval) VALUES ('default', $1, NOW(), NOW(), $2, NOW(), NOW(), NULL)`, ulid.Make().String(), entId1.String()) - require.Error(t, err, "should not allow NULL values in usage_period_interval column") - }, - }, - { - // Test down migration - version: 20250624115812, - direction: directionDown, - action: func(t *testing.T, db *sql.DB) { - // Verify the column was dropped - _, err := db.Exec(`SELECT usage_period_interval FROM usage_resets LIMIT 1`) - require.Error(t, err, "usage_period_interval column should not exist after down migration") - }, - }, - }, - }.Test(t) -} - -func TestUsagePeriodIntervalDurationBackfillMigration(t *testing.T) { - t.Run("om_func_generate_ulid", func(t *testing.T) { - runner{ - stops: stops{ - { - version: 20250807075408, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Let's fuzz it a bit - for i := 0; i < 100; i++ { - var ulid string - - err := db.QueryRow(`SELECT om_func_generate_ulid()`).Scan(&ulid) - require.NoError(t, err) - - ulidRegex := regexp.MustCompile(`^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$`) - require.True(t, ulidRegex.MatchString(ulid), "ULID should match regex") - } - }, - }, - }, - }.Test(t) - }) - - t.Run("om_func_go_add_date_normalized", func(t *testing.T) { - runner{ - stops: stops{ - { - version: 20250807075408, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Should add dates exactly as go's add_date - tt := []struct { - duration datetime.ISODurationString - neg bool - date time.Time - }{ - // Adding only a small calendar duration - {"P1D", false, time.Date(2025, 3, 12, 3, 0, 2, 0, time.UTC)}, - // Adding time components only - {"PT2H3M", false, time.Date(2025, 3, 12, 3, 0, 2, 0, time.UTC)}, - // February is a 27 day month - {"P1M", false, time.Date(2025, 1, 31, 3, 0, 2, 0, time.UTC)}, - {"P3M", false, time.Date(2025, 1, 31, 0, 8, 0, 0, time.UTC)}, - // June is a 30 day month - {"P1M", false, time.Date(2025, 5, 31, 1, 0, 3, 0, time.UTC)}, - {"P3M", false, time.Date(2025, 5, 31, 0, 7, 0, 0, time.UTC)}, - // Just a random complex duration - {"P1Y4M5DT2H3M6S", false, time.Date(2025, 1, 12, 3, 0, 2, 0, time.UTC)}, - // Add negative durations - {"P1D", true, time.Date(2025, 3, 11, 3, 0, 2, 0, time.UTC)}, - {"P1W", true, time.Date(2025, 3, 11, 3, 0, 2, 0, time.UTC)}, - {"P1W", true, time.Date(2025, 3, 4, 3, 0, 2, 0, time.UTC)}, - {"P1M", true, time.Date(2025, 2, 28, 3, 0, 2, 0, time.UTC)}, - {"P1Y", true, time.Date(2024, 1, 12, 3, 0, 2, 0, time.UTC)}, - {"P1Y4M5DT2H3M6S", true, time.Date(2024, 8, 7, 0, 56, 54, 0, time.UTC)}, - } - - for _, tc := range tt { - var res sql.NullTime - query := `SELECT om_func_go_add_date_normalized($1,` - if tc.neg { - query += `$2::INTERVAL * -1` - } else { - query += `$2` - } - query += `);` - - require.NoError(t, db.QueryRow(query, tc.date, tc.duration).Scan(&res)) - require.True(t, res.Valid, "should return a valid time, got inputs: %v, %v", tc.date, tc.duration) - - duration, err := tc.duration.Parse() - require.NoError(t, err) - - if tc.neg { - duration = duration.Negate() - } - - exp, _ := duration.Period.AddTo(tc.date) - - require.Equal(t, exp, res.Time.UTC(), "should add dates exactly as go's add_date, inputs: %v, %v", tc.date, tc.duration) - } - - // PG does not support nanosecond resolution so we'll lose that - { - durStr := datetime.ISODurationString("P3M") - at := time.Date(2025, 1, 31, 0, 8, 0, 1, time.UTC) - - var res sql.NullTime - require.NoError(t, db.QueryRow(`SELECT om_func_go_add_date_normalized($1, $2)`, at, durStr).Scan(&res)) - require.True(t, res.Valid, "should return a valid time, got inputs: %v, %v", at, durStr) - - duration, err := durStr.Parse() - require.NoError(t, err) - - exp, _ := duration.Period.AddTo(at) - - require.NotEqual(t, exp, res.Time.UTC()) - require.Equal(t, exp.Add(-time.Nanosecond), res.Time.UTC()) - } - }, - }, - }, - }.Test(t) - }) - - t.Run("om_func_get_go_normalized_last_iteration_not_after_cutoff", func(t *testing.T) { - runner{ - stops: stops{ - { - version: 20250807075408, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Test if before cutoff - { - var res time.Time - require.NoError(t, db.QueryRow(`SELECT om_func_get_go_normalized_last_iteration_not_after_cutoff($1, $2, $3)`, - time.Date(2025, 1, 5, 0, 0, 0, 0, time.UTC), - "P1M", - time.Date(2025, 4, 12, 0, 0, 0, 0, time.UTC), - ).Scan(&res)) - - require.Equal(t, time.Date(2025, 4, 5, 0, 0, 0, 0, time.UTC), res.UTC()) - } - // Test if after cutoff - { - var res time.Time - require.NoError(t, db.QueryRow(`SELECT om_func_get_go_normalized_last_iteration_not_after_cutoff($1, $2, $3)`, - time.Date(2025, 7, 5, 0, 0, 0, 0, time.UTC), - "P1M", - time.Date(2025, 4, 12, 0, 0, 0, 0, time.UTC), - ).Scan(&res)) - - require.Equal(t, time.Date(2025, 4, 5, 0, 0, 0, 0, time.UTC), res.UTC()) - } - // Test if exactly on cutoff - { - var res time.Time - require.NoError(t, db.QueryRow(`SELECT om_func_get_go_normalized_last_iteration_not_after_cutoff($1, $2, $3)`, - time.Date(2025, 4, 12, 0, 0, 0, 0, time.UTC), - "P1M", - time.Date(2025, 4, 12, 0, 0, 0, 0, time.UTC), - ).Scan(&res)) - - require.Equal(t, time.Date(2025, 4, 12, 0, 0, 0, 0, time.UTC), res.UTC()) - } - // Test if will fall on cutoff - { - var res time.Time - require.NoError(t, db.QueryRow(`SELECT om_func_get_go_normalized_last_iteration_not_after_cutoff($1, $2, $3)`, - time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC), - "P1M", - time.Date(2025, 3, 3, 0, 0, 0, 0, time.UTC), - ).Scan(&res)) - - // Notice the expected normalization - require.Equal(t, time.Date(2025, 3, 3, 0, 0, 0, 0, time.UTC), res.UTC()) - } - // Test the specific failing scenario: anchor after cutoff with P1W interval - { - var res time.Time - require.NoError(t, db.QueryRow(`SELECT om_func_get_go_normalized_last_iteration_not_after_cutoff($1, $2, $3)`, - testutils.GetRFC3339Time(t, "2024-11-06T19:30:00Z"), // anchor - "P1W", // interval - testutils.GetRFC3339Time(t, "2024-11-06T19:29:00Z"), // cutoff (1 minute before anchor) - ).Scan(&res)) - - // Should return the last weekly iteration before the cutoff - // Starting from 2024-11-06T19:30:00Z and going backwards by weeks - // Should be 2024-10-30T19:30:00Z (one week before) - require.Equal(t, testutils.GetRFC3339Time(t, "2024-10-30T19:30:00Z"), res.UTC()) - } - }, - }, - }, - }.Test(t) - }) - - t.Run("om_func_update_usage_period_durations", func(t *testing.T) { - now := time.Now() - - featId := ulid.Make() - - // Ent1 hasn't had any resets yet - entId1 := ulid.Make() - ent1MeasureUsageFrom := time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC) - // Ent2 had a single reset which is not aligned with the entitlement's anchor - entId2 := ulid.Make() - ent2MeasureUsageFrom := time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC) - ent2Ur1Id := ulid.Make() - ent2Ur1ResetTime := time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC) - // Ent3 has a single reset which is misaligned and reanchors - entId3 := ulid.Make() - ent3MeasureUsageFrom := time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC) - ent3Ur1Id := ulid.Make() - ent3Ur1ResetTime := time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC) - ent3Ur1Anchor := time.Date(2025, 3, 11, 0, 0, 0, 0, time.UTC) - // Ent4 has a single reset which is misaligned, reanchors, and changes the interval - entId4 := ulid.Make() - ent4MeasureUsageFrom := time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC) - ent4Ur1Id := ulid.Make() - ent4Ur1ResetTime := time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC) - ent4Ur1Anchor := time.Date(2025, 3, 11, 0, 0, 0, 0, time.UTC) - ent4Ur1Interval := "P1W" // This is not realistic but we need this never the less - // Ent5 has two resets, changing to P1W then back to P1M - // This is simply used as a more complex scenario to assert everything works as expected - entId5 := ulid.Make() - ent5MeasureUsageFrom := time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC) - ent5Ur1Id := ulid.Make() - ent5Ur1ResetTime := time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC) - ent5Ur1Anchor := time.Date(2025, 3, 11, 0, 0, 0, 0, time.UTC) - ent5Ur1Interval := "P1W" - ent5Ur2Id := ulid.Make() - ent5Ur2ResetTime := time.Date(2025, 3, 23, 0, 0, 0, 0, time.UTC) - ent5Ur2Anchor := time.Date(2025, 3, 23, 0, 0, 0, 0, time.UTC) - ent5Ur2Interval := "P1M" - // Ent6 has time components only in the interval - // As the period is measure in hours, we'll set relative times close to current time - entId6 := ulid.Make() - ent6Interval := "PT3H" - ent6MeasureUsageFrom := now.Truncate(time.Hour).Add(-time.Hour * 5) - ent6Ur1Id := ulid.Make() - ent6Ur1ResetTime := ent6MeasureUsageFrom.Add(time.Hour*2 + time.Minute*30) - ent6Ur1Anchor := ent6MeasureUsageFrom - ent6Ur1Interval := "PT1H" - // Ent7 has both time and date components in the interval - entId7 := ulid.Make() - ent7Interval := "P1MT2H" - ent7MeasureUsageFrom := time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC) - ent7Ur1Id := ulid.Make() - ent7Ur1ResetTime := time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC) - ent7Ur1Anchor := time.Date(2025, 3, 11, 0, 0, 0, 0, time.UTC) - ent7Ur1Interval := "P1MT1H" - - runner{ - stops: stops{ - { - // before version: 20250807075408, - version: 20250731160524, - direction: directionUp, - // Let's do setup - action: func(t *testing.T, db *sql.DB) { - now := time.Now() - - q := v20250703081943.New(db) - ctx := context.Background() - - // 1. Create a feature - require.NoError(t, q.CreateFeature( - ctx, - v20250703081943.CreateFeatureParams{ - Namespace: "default", - ID: featId.String(), - Key: "feat_1", - Name: "Feature 1", - CreatedAt: now, - UpdatedAt: now, - }, - )) - - // 2. Create entitlements with different usage_period_intervals - require.NoError(t, q.CreateEntitlement( - ctx, - v20250703081943.CreateEntitlementParams{ - Namespace: "default", - ID: entId1.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "metered", - FeatureKey: "feat_1", - FeatureID: featId.String(), - SubjectKey: "subject_1", - UsagePeriodInterval: sql.NullString{String: "P1M", Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: ent1MeasureUsageFrom, Valid: true}, - MeasureUsageFrom: sql.NullTime{Time: ent1MeasureUsageFrom, Valid: true}, - }, - )) - - require.NoError(t, q.CreateEntitlement( - ctx, - v20250703081943.CreateEntitlementParams{ - Namespace: "default", - ID: entId2.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "metered", - FeatureKey: "feat_1", - FeatureID: featId.String(), - SubjectKey: "subject_2", - UsagePeriodInterval: sql.NullString{String: "P1M", Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: ent2MeasureUsageFrom, Valid: true}, - MeasureUsageFrom: sql.NullTime{Time: ent2MeasureUsageFrom, Valid: true}, - }, - )) - - require.NoError(t, q.CreateEntitlement( - ctx, - v20250703081943.CreateEntitlementParams{ - Namespace: "default", - ID: entId3.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "metered", - FeatureKey: "feat_1", - FeatureID: featId.String(), - SubjectKey: "subject_3", - UsagePeriodInterval: sql.NullString{String: "P1M", Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: ent3MeasureUsageFrom, Valid: true}, - MeasureUsageFrom: sql.NullTime{Time: ent3MeasureUsageFrom, Valid: true}, - }, - )) - - require.NoError(t, q.CreateEntitlement( - ctx, - v20250703081943.CreateEntitlementParams{ - Namespace: "default", - ID: entId4.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "metered", - FeatureKey: "feat_1", - FeatureID: featId.String(), - SubjectKey: "subject_4", - UsagePeriodInterval: sql.NullString{String: "P1M", Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: ent4MeasureUsageFrom, Valid: true}, - MeasureUsageFrom: sql.NullTime{Time: ent4MeasureUsageFrom, Valid: true}, - }, - )) - - require.NoError(t, q.CreateEntitlement( - ctx, - v20250703081943.CreateEntitlementParams{ - Namespace: "default", - ID: entId5.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "metered", - FeatureKey: "feat_1", - FeatureID: featId.String(), - SubjectKey: "subject_5", - UsagePeriodInterval: sql.NullString{String: "P1M", Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: ent5MeasureUsageFrom, Valid: true}, - MeasureUsageFrom: sql.NullTime{Time: ent5MeasureUsageFrom, Valid: true}, - }, - )) - - require.NoError(t, q.CreateEntitlement( - ctx, - v20250703081943.CreateEntitlementParams{ - Namespace: "default", - ID: entId6.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "metered", - FeatureKey: "feat_1", - FeatureID: featId.String(), - SubjectKey: "subject_6", - UsagePeriodInterval: sql.NullString{String: ent6Interval, Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: ent6MeasureUsageFrom, Valid: true}, - MeasureUsageFrom: sql.NullTime{Time: ent6MeasureUsageFrom, Valid: true}, - }, - )) - - require.NoError(t, q.CreateEntitlement( - ctx, - v20250703081943.CreateEntitlementParams{ - Namespace: "default", - ID: entId7.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementType: "metered", - FeatureKey: "feat_1", - FeatureID: featId.String(), - SubjectKey: "subject_7", - UsagePeriodInterval: sql.NullString{String: ent7Interval, Valid: true}, - UsagePeriodAnchor: sql.NullTime{Time: ent7MeasureUsageFrom, Valid: true}, - MeasureUsageFrom: sql.NullTime{Time: ent7MeasureUsageFrom, Valid: true}, - }, - )) - - // 3. Create usage resets - // Ent 2 - require.NoError(t, q.CreateUsageResetWithInterval( - ctx, - v20250703081943.CreateUsageResetWithIntervalParams{ - Namespace: "default", - ID: ent2Ur1Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId2.String(), - Anchor: ent2MeasureUsageFrom, - ResetTime: ent2Ur1ResetTime, - UsagePeriodInterval: "P1M", - }, - )) - - // Ent 3 - require.NoError(t, q.CreateUsageResetWithInterval( - ctx, - v20250703081943.CreateUsageResetWithIntervalParams{ - Namespace: "default", - ID: ent3Ur1Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId3.String(), - Anchor: ent3Ur1Anchor, - ResetTime: ent3Ur1ResetTime, - UsagePeriodInterval: "P1M", - }, - )) - - // Ent 4 - require.NoError(t, q.CreateUsageResetWithInterval( - ctx, - v20250703081943.CreateUsageResetWithIntervalParams{ - Namespace: "default", - ID: ent4Ur1Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId4.String(), - Anchor: ent4Ur1Anchor, - ResetTime: ent4Ur1ResetTime, - UsagePeriodInterval: ent4Ur1Interval, - }, - )) - - // Ent 5 - require.NoError(t, q.CreateUsageResetWithInterval( - ctx, - v20250703081943.CreateUsageResetWithIntervalParams{ - Namespace: "default", - ID: ent5Ur1Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId5.String(), - Anchor: ent5Ur1Anchor, - ResetTime: ent5Ur1ResetTime, - UsagePeriodInterval: ent5Ur1Interval, - }, - )) - - require.NoError(t, q.CreateUsageResetWithInterval( - ctx, - v20250703081943.CreateUsageResetWithIntervalParams{ - Namespace: "default", - ID: ent5Ur2Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId5.String(), - Anchor: ent5Ur2Anchor, - ResetTime: ent5Ur2ResetTime, - UsagePeriodInterval: ent5Ur2Interval, - }, - )) - - // Ent 6 - require.NoError(t, q.CreateUsageResetWithInterval( - ctx, - v20250703081943.CreateUsageResetWithIntervalParams{ - Namespace: "default", - ID: ent6Ur1Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId6.String(), - Anchor: ent6Ur1Anchor, - ResetTime: ent6Ur1ResetTime, - UsagePeriodInterval: ent6Ur1Interval, - }, - )) - - // Ent 7 - require.NoError(t, q.CreateUsageResetWithInterval( - ctx, - v20250703081943.CreateUsageResetWithIntervalParams{ - Namespace: "default", - ID: ent7Ur1Id.String(), - CreatedAt: now, - UpdatedAt: now, - EntitlementID: entId7.String(), - Anchor: ent7Ur1Anchor, - ResetTime: ent7Ur1ResetTime, - UsagePeriodInterval: ent7Ur1Interval, - }, - )) - }, - }, - { - version: 20250807075408, - direction: directionUp, - // Let's do assertions - action: func(t *testing.T, db *sql.DB) { - q := v20250703081943.New(db) - ctx := context.Background() - - // NOTE: the now used here can be slightly off from the NOW() used in the migration - // which can theoretically make the test flaky - now := time.Now() - - // Entitlement 1 with no resets - { - ent1, err := q.GetEntitlementByID(ctx, entId1.String()) - require.NoError(t, err) - - usageResets, err := q.GetUsageResetsByEntitlementID(ctx, ent1.ID) - require.NoError(t, err) - - // As the purpose of this migration is to fix the go date normalization behavior in the dataset - // we'll use go date primitives to calculate periods - - // Let's start with how many resets there should be - start := ent1MeasureUsageFrom - monthlyIterCount := 0 - for iT := start; iT.Before(now); iT = iT.AddDate(0, 1, 0) { - monthlyIterCount++ - } - - expectedResetCount := monthlyIterCount + - 0 // For the ones already present - - rstsJSON, err := json.MarshalIndent(usageResets, "", " ") - require.NoError(t, err) - - assert.Equal(t, expectedResetCount, len(usageResets), "Should have the correct number of usage resets, got %s", rstsJSON) - - // Let's check the first and second resets, for good measure - firstReset := usageResets[0] - secondReset := usageResets[1] - - // Let's assert that annotations were added - for _, reset := range usageResets { - assert.True(t, reset.Annotations.Valid, "Should have annotations, got %+v", reset) - var ann map[string]string - - assert.NoError(t, json.Unmarshal(reset.Annotations.RawMessage, &ann)) - - assert.Equal(t, "period_migration", ann["source"], "Should have the correct annotations, got %+v", reset) - } - - // Let's assert the period info - assert.Equal(t, time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC), firstReset.ResetTime.UTC(), "Should have the correct reset time, got %+v", firstReset) - assert.Equal(t, "P31D", firstReset.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", firstReset) - assert.Equal(t, time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC), firstReset.Anchor.UTC(), "Should have the correct anchor, got %+v", firstReset) - - assert.Equal(t, time.Date(2025, 3, 3, 0, 0, 0, 0, time.UTC), secondReset.ResetTime.UTC(), "Should have the correct reset time, got %+v", secondReset) - assert.Equal(t, "P31D", secondReset.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", secondReset) - assert.Equal(t, time.Date(2025, 3, 3, 0, 0, 0, 0, time.UTC), secondReset.Anchor.UTC(), "Should have the correct anchor, got %+v", secondReset) - - lastReset := usageResets[len(usageResets)-1] - - // The last reset should have the original interval string - assert.Equal(t, "P1M", lastReset.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", lastReset) - // The last reset should have the original anchor - // This is so we're consistent with how billing handles the period change! - assert.Equal(t, ent1MeasureUsageFrom, lastReset.Anchor.UTC(), "Should have the correct anchor, got %+v", lastReset) - } - - // Entitlement 2 with a single reset (misaligned but NOT reanchoring) - { - ent2, err := q.GetEntitlementByID(ctx, entId2.String()) - require.NoError(t, err) - - usageResets, err := q.GetUsageResetsByEntitlementID(ctx, ent2.ID) - require.NoError(t, err) - - // As the purpose of this migration is to fix the go date normalization behavior in the dataset - // we'll use go date primitives to calculate periods - - // Let's start with how many resets there should be - start := ent2MeasureUsageFrom - - // Note that this algo is the same as our single reset doesn't change the anchor - monthlyIterCount := 0 - for iT := start; iT.Before(now); iT = iT.AddDate(0, 1, 0) { - monthlyIterCount++ - } - - expectedResetCount := monthlyIterCount + - 1 // For the ones already present - - rstsJSON, err := json.MarshalIndent(usageResets, "", " ") - require.NoError(t, err) - - assert.Equal(t, expectedResetCount, len(usageResets), "Should have the correct number of usage resets, got %s", rstsJSON) - - // Let's check that our resets around the preexisting reset are correct - justBefore := usageResets[1] - updatedPreExisting := usageResets[2] - justAfter := usageResets[3] - - // Normal, as with any other iteration - assert.Equal(t, time.Date(2025, 3, 3, 0, 0, 0, 0, time.UTC), justBefore.ResetTime.UTC(), "Should have the correct reset time, got %+v", justBefore) - assert.Equal(t, "P31D", justBefore.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", justBefore) - - // Let's assert it's the right one - assert.Equal(t, time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC), updatedPreExisting.ResetTime.UTC(), "Should have the correct anchor, got %+v", updatedPreExisting) - // The pre-existing has to be updated - // in its ANCHOR TIME, which has to be normalized to the closest one-before iteration using - // the old normalizing algo - assert.Equal(t, time.Date(2025, 3, 3, 0, 0, 0, 0, time.UTC), updatedPreExisting.Anchor.UTC(), "Should have the correct anchor, got %+v", updatedPreExisting) - assert.Equal(t, "P31D", updatedPreExisting.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", updatedPreExisting) - - // Normal, as with any other iteration, still using the same old anchor - assert.Equal(t, time.Date(2025, 4, 3, 0, 0, 0, 0, time.UTC), justAfter.ResetTime.UTC(), "Should have the correct reset time, got %+v", justAfter) - assert.Equal(t, "P30D", justAfter.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", justAfter) - } - - // Entitlement 3 with a single reset (misaligned and reanchors) - { - ent3, err := q.GetEntitlementByID(ctx, entId3.String()) - require.NoError(t, err) - - usageResets, err := q.GetUsageResetsByEntitlementID(ctx, ent3.ID) - require.NoError(t, err) - - // Let's just test that we behave correctly after the reanchoring reset - updatedPreExisting := usageResets[2] - justAfter := usageResets[3] - - // The pre-existing has to be updated - assert.Equal(t, time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC), updatedPreExisting.ResetTime.UTC(), "Should have the correct reset time, got %+v", updatedPreExisting) - assert.Equal(t, time.Date(2025, 3, 11, 0, 0, 0, 0, time.UTC), updatedPreExisting.Anchor.UTC(), "Should have the correct anchor, got %+v", updatedPreExisting) - assert.Equal(t, "P31D", updatedPreExisting.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", updatedPreExisting) - - // The next one has to again be aligned with the new anchor - assert.Equal(t, time.Date(2025, 4, 11, 0, 0, 0, 0, time.UTC), justAfter.ResetTime.UTC(), "Should have the correct reset time, got %+v", justAfter) - assert.Equal(t, time.Date(2025, 4, 11, 0, 0, 0, 0, time.UTC), justAfter.Anchor.UTC(), "Should have the correct anchor, got %+v", justAfter) - assert.Equal(t, "P30D", justAfter.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", justAfter) - } - - // Entitlement 4 with a single reset (misaligned, reanchors and changes interval) - { - ent4, err := q.GetEntitlementByID(ctx, entId4.String()) - require.NoError(t, err) - - usageResets, err := q.GetUsageResetsByEntitlementID(ctx, ent4.ID) - require.NoError(t, err) - - // Let's just test that we behave correctly after the reanchoring reset - updatedPreExisting := usageResets[2] - justAfter := usageResets[3] - twoAfter := usageResets[4] - - // The pre-existing has to be updated - assert.Equal(t, time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC), updatedPreExisting.ResetTime.UTC(), "Should have the correct reset time, got %+v", updatedPreExisting) - assert.Equal(t, time.Date(2025, 3, 11, 0, 0, 0, 0, time.UTC), updatedPreExisting.Anchor.UTC(), "Should have the correct anchor, got %+v", updatedPreExisting) - assert.Equal(t, "P7D", updatedPreExisting.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", updatedPreExisting) - - // The next one has to again be aligned with the new anchor - assert.Equal(t, time.Date(2025, 3, 18, 0, 0, 0, 0, time.UTC), justAfter.ResetTime.UTC(), "Should have the correct reset time, got %+v", justAfter) - assert.Equal(t, time.Date(2025, 3, 18, 0, 0, 0, 0, time.UTC), justAfter.Anchor.UTC(), "Should have the correct anchor, got %+v", justAfter) - assert.Equal(t, "P7D", justAfter.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", justAfter) - - // The next one has to again be aligned with the new anchor - assert.Equal(t, time.Date(2025, 3, 25, 0, 0, 0, 0, time.UTC), twoAfter.ResetTime.UTC(), "Should have the correct reset time, got %+v", twoAfter) - assert.Equal(t, time.Date(2025, 3, 25, 0, 0, 0, 0, time.UTC), twoAfter.Anchor.UTC(), "Should have the correct anchor, got %+v", twoAfter) - assert.Equal(t, "P7D", twoAfter.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", twoAfter) - - // The last one has to be the original interval - lastReset := usageResets[len(usageResets)-1] - // Note that due to PG reasons, P1W is translated to P7D but they are functionally identical - assert.Equal(t, "P7D", lastReset.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", lastReset) - assert.Equal(t, ent4Ur1Anchor, lastReset.Anchor.UTC(), "Should have the correct anchor, got %+v", lastReset) - } - - // Entitlement 5, complex scenario - { - ent5, err := q.GetEntitlementByID(ctx, entId5.String()) - require.NoError(t, err) - - usageResets, err := q.GetUsageResetsByEntitlementID(ctx, ent5.ID) - require.NoError(t, err) - - // Let's test for the first reset - { - // Let's just test that we behave correctly after the reanchoring reset - updatedPreExisting := usageResets[2] - justAfter := usageResets[3] - - // The pre-existing has to be updated - assert.Equal(t, time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC), updatedPreExisting.ResetTime.UTC(), "Should have the correct reset time, got %+v", updatedPreExisting) - assert.Equal(t, time.Date(2025, 3, 11, 0, 0, 0, 0, time.UTC), updatedPreExisting.Anchor.UTC(), "Should have the correct anchor, got %+v", updatedPreExisting) - assert.Equal(t, "P7D", updatedPreExisting.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", updatedPreExisting) - - // The next one has to again be aligned with the new anchor - assert.Equal(t, time.Date(2025, 3, 18, 0, 0, 0, 0, time.UTC), justAfter.ResetTime.UTC(), "Should have the correct reset time, got %+v", justAfter) - assert.Equal(t, time.Date(2025, 3, 18, 0, 0, 0, 0, time.UTC), justAfter.Anchor.UTC(), "Should have the correct anchor, got %+v", justAfter) - assert.Equal(t, "P7D", justAfter.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", justAfter) - } - - // Let's test for the second reset - { - // Let's just test that we behave correctly after the reanchoring reset - updatedPreExisting := usageResets[4] - justAfter := usageResets[5] - - // The pre-existing has to be updated - assert.Equal(t, time.Date(2025, 3, 23, 0, 0, 0, 0, time.UTC), updatedPreExisting.ResetTime.UTC(), "Should have the correct reset time, got %+v", updatedPreExisting) - assert.Equal(t, time.Date(2025, 3, 23, 0, 0, 0, 0, time.UTC), updatedPreExisting.Anchor.UTC(), "Should have the correct anchor, got %+v", updatedPreExisting) - assert.Equal(t, "P31D", updatedPreExisting.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", updatedPreExisting) - - // The next one has to again be aligned with the new anchor - assert.Equal(t, time.Date(2025, 4, 23, 0, 0, 0, 0, time.UTC), justAfter.ResetTime.UTC(), "Should have the correct reset time, got %+v", justAfter) - assert.Equal(t, time.Date(2025, 4, 23, 0, 0, 0, 0, time.UTC), justAfter.Anchor.UTC(), "Should have the correct anchor, got %+v", justAfter) - assert.Equal(t, "P30D", justAfter.UsagePeriodInterval, "Should have the correct usage period interval, got %+v", justAfter) - } - } - - // Entitlement 6, time-only interval - { - ent6, err := q.GetEntitlementByID(ctx, entId6.String()) - require.NoError(t, err) - - usageResets, err := q.GetUsageResetsByEntitlementID(ctx, ent6.ID) - require.NoError(t, err) - - ursJSON, err := json.MarshalIndent(usageResets, "", " ") - require.NoError(t, err) - - require.Len(t, usageResets, 5, "Should have the correct number of usage resets, got %s", ursJSON) - - nowMinus5HoursTruncated := now.Truncate(time.Hour).Add(-time.Hour * 5).UTC() - - // Let's make assertions for all expected items - assert.Equal(t, nowMinus5HoursTruncated, usageResets[0].Anchor.UTC(), "Should have the correct anchor, got %+v", usageResets[0]) - assert.Equal(t, nowMinus5HoursTruncated, usageResets[0].ResetTime.UTC(), "Should have the correct reset time, got %+v", usageResets[0]) - - assert.Equal(t, nowMinus5HoursTruncated.Add(time.Hour*2), usageResets[1].Anchor.UTC(), "Should have the correct anchor, got %+v", usageResets[1]) - assert.Equal(t, nowMinus5HoursTruncated.Add(time.Hour*2+time.Minute*30), usageResets[1].ResetTime.UTC(), "Should have the correct reset time, got %+v", usageResets[1]) - - // Now it will realign itself to the anchor - assert.Equal(t, nowMinus5HoursTruncated.Add(time.Hour*3), usageResets[2].Anchor.UTC(), "Should have the correct anchor, got %+v", usageResets[2]) - assert.Equal(t, nowMinus5HoursTruncated.Add(time.Hour*3), usageResets[2].ResetTime.UTC(), "Should have the correct reset time, got %+v", usageResets[2]) - - assert.Equal(t, nowMinus5HoursTruncated.Add(time.Hour*4), usageResets[3].Anchor.UTC(), "Should have the correct anchor, got %+v", usageResets[3]) - assert.Equal(t, nowMinus5HoursTruncated.Add(time.Hour*4), usageResets[3].ResetTime.UTC(), "Should have the correct reset time, got %+v", usageResets[3]) - - // And the last item will restore to the original anchor - assert.Equal(t, nowMinus5HoursTruncated, usageResets[4].Anchor.UTC(), "Should have the correct anchor, got %+v", usageResets[4]) - assert.Equal(t, nowMinus5HoursTruncated.Add(time.Hour*5), usageResets[4].ResetTime.UTC(), "Should have the correct reset time, got %+v", usageResets[4]) - } - - // Entitlement 7, date+time interval - { - ent7, err := q.GetEntitlementByID(ctx, entId7.String()) - require.NoError(t, err) - - usageResets, err := q.GetUsageResetsByEntitlementID(ctx, ent7.ID) - require.NoError(t, err) - - // Let's test we have the normalized interval - assert.Equal(t, "P31DT2H", usageResets[0].UsagePeriodInterval, "Should have the correct usage period interval, got %+v", usageResets[0]) - assert.Equal(t, time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC), usageResets[0].Anchor.UTC(), "Should have the correct anchor, got %+v", usageResets[0]) - assert.Equal(t, time.Date(2025, 1, 31, 0, 0, 0, 0, time.UTC), usageResets[0].ResetTime.UTC(), "Should have the correct reset time, got %+v", usageResets[0]) - - // Let's assert the usage reset update - assert.Equal(t, time.Date(2025, 3, 12, 0, 0, 0, 0, time.UTC), usageResets[2].ResetTime.UTC(), "Should have the correct reset time, got %+v", usageResets[2]) - assert.Equal(t, time.Date(2025, 3, 11, 0, 0, 0, 0, time.UTC), usageResets[2].Anchor.UTC(), "Should have the correct anchor, got %+v", usageResets[2]) - assert.Equal(t, "P31DT1H", usageResets[2].UsagePeriodInterval, "Should have the correct usage period interval, got %+v", usageResets[2]) - - // Let's assert it realigns correctly - assert.Equal(t, time.Date(2025, 4, 11, 1, 0, 0, 0, time.UTC), usageResets[3].ResetTime.UTC(), "Should have the correct reset time, got %+v", usageResets[3]) - assert.Equal(t, time.Date(2025, 4, 11, 1, 0, 0, 0, time.UTC), usageResets[3].Anchor.UTC(), "Should have the correct anchor, got %+v", usageResets[3]) - assert.Equal(t, "P30DT1H", usageResets[3].UsagePeriodInterval, "Should have the correct usage period interval, got %+v", usageResets[3]) - } - }, - }, - }, - }.Test(t) - }) - - t.Run("Should work on failing lines of dev dataset", func(t *testing.T) { - runner{ - stops: stops{ - // Let's start with setup - { - // before version: 20250807075408, - version: 20250731160524, - direction: directionUp, - // Let's do setup - action: func(t *testing.T, db *sql.DB) { - q := v20250703081943.New(db) - ctx := context.Background() - - // 1. Create (some) Feature so it will work - require.NoError(t, q.CreateFeature( - ctx, - v20250703081943.CreateFeatureParams{ - Namespace: "org_2l3uuzkgTdvCyom82y11jeZO2u5", - ID: "01J5ZSQF319B1M61GNH9ZBG23D", - Key: "total_api_usage", - Name: "total_api_usage", - CreatedAt: testutils.GetRFC3339Time(t, "2024-11-06T19:29:00Z"), - UpdatedAt: testutils.GetRFC3339Time(t, "2024-11-06T19:29:00Z"), - }, - )) - - // 2. Create the entitlement - require.NoError(t, q.CreateEntitlement( - ctx, - v20250703081943.CreateEntitlementParams{ - ID: "01JC1F7J8FXTX0YGVNB5Y4CH11", - Namespace: "org_2l3uuzkgTdvCyom82y11jeZO2u5", - CreatedAt: testutils.GetRFC3339Time(t, "2024-11-06T19:29:11Z"), - UpdatedAt: testutils.GetRFC3339Time(t, "2024-11-06T19:32:04Z"), - FeatureID: "01J5ZSQF319B1M61GNH9ZBG23D", - SubjectKey: "lol", - EntitlementType: "metered", - FeatureKey: "total_api_usage", - MeasureUsageFrom: sql.NullTime{ - Time: testutils.GetRFC3339Time(t, "2024-11-06T19:29:00Z"), - Valid: true, - }, - UsagePeriodInterval: sql.NullString{ - String: "P1W", - Valid: true, - }, - UsagePeriodAnchor: sql.NullTime{ - Time: testutils.GetRFC3339Time(t, "2024-11-06T19:30:00Z"), - Valid: true, - }, - }, - )) - - // 3. Let's create the usage resets - require.NoError(t, q.CreateUsageResetWithInterval( - ctx, - v20250703081943.CreateUsageResetWithIntervalParams{ - ID: "01JC1FAW6XTAGF9BDRSMC79VQC", - Namespace: "org_2l3uuzkgTdvCyom82y11jeZO2u5", - CreatedAt: testutils.GetRFC3339Time(t, "2024-11-06T19:30:59Z"), - UpdatedAt: testutils.GetRFC3339Time(t, "2024-11-06T19:30:59Z"), - ResetTime: testutils.GetRFC3339Time(t, "2024-11-06T19:30:00Z"), - EntitlementID: "01JC1F7J8FXTX0YGVNB5Y4CH11", - Anchor: testutils.GetRFC3339Time(t, "2024-11-06T19:30:00Z"), - UsagePeriodInterval: "P1W", - }, - )) - }, - }, - // And now do assertions - // { - // version: 20250807075408, - // direction: directionUp, - // // Let's do assertions - // action: func(t *testing.T, db *sql.DB) { - // }, - // }, - }, - }.Test(t) - }) -} - -func TestEntitlementSubjectIdMigration(t *testing.T) { - // Create ULIDs for all entities we'll need - featId := ulid.Make() - - // Happy path - single subject per entitlement - entId1 := ulid.Make() - subId1 := ulid.Make() - - entId2 := ulid.Make() - subId2 := ulid.Make() - - // Third entitlement for more comprehensive testing - entId3 := ulid.Make() - subId3 := ulid.Make() - - runner{ - stops: stops{ - { - // Before our migration - version: 20250807075408, // Just before our migration - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // 1. Create a feature - _, err := db.Exec(` - INSERT INTO features ( - namespace, - id, - key, - name, - created_at, - updated_at - ) - VALUES ( - 'default', - $1, - 'feat_1', - 'Feature 1', - NOW(), - NOW() - )`, - featId.String(), - ) - require.NoError(t, err) - - // 2. Create subjects - // Happy path subjects - _, err = db.Exec(` - INSERT INTO subjects ( - namespace, - id, - key, - created_at, - updated_at - ) - VALUES ( - 'default', - $1, - 'subject_1', - '2024-01-01 00:00:00', - NOW() - )`, - subId1.String(), - ) - require.NoError(t, err) - - _, err = db.Exec(` - INSERT INTO subjects ( - namespace, - id, - key, - created_at, - updated_at - ) - VALUES ( - 'default', - $1, - 'subject_2', - '2024-01-01 00:00:00', - NOW() - )`, - subId2.String(), - ) - require.NoError(t, err) - - // Third subject for comprehensive testing - _, err = db.Exec(` - INSERT INTO subjects ( - namespace, - id, - key, - created_at, - updated_at - ) - VALUES ( - 'default', - $1, - 'subject_3', - '2024-01-01 00:00:00', - NOW() - )`, - subId3.String(), - ) - require.NoError(t, err) - - // 3. Create entitlements (without subject_id column yet) - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'METERED', - 'feat_1', - $2, - 'subject_1' - )`, - entId1.String(), - featId.String(), - ) - require.NoError(t, err) - - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'BOOLEAN', - 'feat_1', - $2, - 'subject_2' - )`, - entId2.String(), - featId.String(), - ) - require.NoError(t, err) - - // Third entitlement - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'METERED', - 'feat_1', - $2, - 'subject_3' - )`, - entId3.String(), - featId.String(), - ) - require.NoError(t, err) - - // 4. Verify subject_id column doesn't exist yet - _, err = db.Exec(`SELECT subject_id FROM entitlements LIMIT 1`) - require.Error(t, err, "subject_id column should not exist before migration") - }, - }, - { - // After our migration - version: 20250818093933, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // 1. Verify subject_id column was added and populated - var subjectId1 string - err := db.QueryRow(` - SELECT subject_id - FROM entitlements - WHERE id = $1 - `, entId1.String()).Scan(&subjectId1) - require.NoError(t, err) - require.Equal(t, subId1.String(), subjectId1, "First entitlement should have correct subject_id") - - var subjectId2 string - err = db.QueryRow(` - SELECT subject_id - FROM entitlements - WHERE id = $1 - `, entId2.String()).Scan(&subjectId2) - require.NoError(t, err) - require.Equal(t, subId2.String(), subjectId2, "Second entitlement should have correct subject_id") - - // 2. Verify third entitlement - var subjectId3 string - err = db.QueryRow(` - SELECT subject_id - FROM entitlements - WHERE id = $1 - `, entId3.String()).Scan(&subjectId3) - require.NoError(t, err) - require.Equal(t, subId3.String(), subjectId3, "Third entitlement should have correct subject_id") - - // 3. Verify subject_id column is NOT NULL - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - subject_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'METERED', - 'feat_1', - $2, - 'subject_1', - NULL - )`, - ulid.Make().String(), - featId.String(), - ) - require.Error(t, err, "should not allow NULL values in subject_id column") - - // 4. Verify foreign key constraint exists and works - // Try to insert entitlement with non-existent subject_id - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - subject_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'METERED', - 'feat_1', - $2, - 'subject_1', - $3 - )`, - ulid.Make().String(), - featId.String(), - ulid.Make().String(), // Non-existent subject_id - ) - require.Error(t, err, "should enforce foreign key constraint") - require.Contains(t, err.Error(), "foreign key", "error should mention foreign key constraint") - - // 5. Verify we can insert valid entitlements - validSubjectId := ulid.Make() - _, err = db.Exec(` - INSERT INTO subjects ( - namespace, - id, - key, - created_at, - updated_at - ) - VALUES ( - 'default', - $1, - 'valid_subject', - NOW(), - NOW() - )`, - validSubjectId.String(), - ) - require.NoError(t, err) - - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - subject_id - ) - VALUES ( - 'default', - $1, - NOW(), - NOW(), - 'METERED', - 'feat_1', - $2, - 'valid_subject', - $3 - )`, - ulid.Make().String(), - featId.String(), - validSubjectId.String(), - ) - require.NoError(t, err, "should allow valid entitlement with proper subject_id") - }, - }, - }, - }.Test(t) -} - -func TestEntitlementCustomerLinkMigration(t *testing.T) { - featId := ulid.Make() - custId := ulid.Make() - entId := ulid.Make() - subjectId := ulid.Make() - - runner{ - stops: stops{ - { - // Before our migration that adds and backfills customer_id - version: 20250818093933, // right before 20250821121421 - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // 1. Create feature - _, err := db.Exec(` - INSERT INTO features (namespace, id, key, name, created_at, updated_at) - VALUES ('default', $1, 'feat_1', 'Feature 1', NOW(), NOW()) - `, featId.String()) - require.NoError(t, err) - - // 1b. Create subject referenced by subject_key 'subject_1' - _, err = db.Exec(` - INSERT INTO subjects (namespace, id, key, created_at, updated_at) - VALUES ('default', $1, 'subject_1', NOW(), NOW()) - `, subjectId.String()) - require.NoError(t, err) - - // 2. Create customer - _, err = db.Exec(` - INSERT INTO customers (namespace, id, created_at, updated_at, key, name) - VALUES ('default', $1, NOW(), NOW(), 'cust_key', 'Customer 1') - `, custId.String()) - require.NoError(t, err) - - // 3. Map subject key to customer via customer_subjects (usage attribution) - _, err = db.Exec(` - INSERT INTO customer_subjects (namespace, customer_id, subject_key, created_at) - VALUES ('default', $1, 'subject_1', NOW()) - `, custId.String()) - require.NoError(t, err) - - // 4. Create entitlement with subject_key and subject_id (no customer_id yet) - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, id, created_at, updated_at, entitlement_type, feature_key, feature_id, subject_key, subject_id - ) VALUES ( - 'default', $1, NOW(), NOW(), 'METERED', 'feat_1', $2, 'subject_1', $3 - )`, - entId.String(), - featId.String(), - subjectId.String(), - ) - require.NoError(t, err) - }, - }, - { - // After migration 20250821121421_entitlement-customer-link.up.sql - version: 20250821121421, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // customer_id must be backfilled and NOT NULL - var backfilledCustomerID string - err := db.QueryRow(`SELECT customer_id FROM entitlements WHERE id = $1`, entId.String()).Scan(&backfilledCustomerID) - require.NoError(t, err) - require.Equal(t, custId.String(), backfilledCustomerID) - - // Enforce NOT NULL: inserting a new entitlement with NULL customer_id should fail - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, id, created_at, updated_at, entitlement_type, feature_key, feature_id, subject_key, customer_id - ) VALUES ( - 'default', $1, NOW(), NOW(), 'METERED', 'feat_1', $2, 'subject_2', NULL - ) - `, ulid.Make().String(), featId.String()) - require.Error(t, err) - - // Enforce FK: inserting with random customer_id should fail - _, err = db.Exec(` - INSERT INTO entitlements ( - namespace, id, created_at, updated_at, entitlement_type, feature_key, feature_id, subject_key, customer_id - ) VALUES ( - 'default', $1, NOW(), NOW(), 'METERED', 'feat_1', $2, 'subject_3', $3 - ) - `, ulid.Make().String(), featId.String(), ulid.Make().String()) - require.Error(t, err) - }, - }, - }, - }.Test(t) -} diff --git a/tools/migrate/productcatalog_test.go b/tools/migrate/productcatalog_test.go index 2114be92d9..0b7560df35 100644 --- a/tools/migrate/productcatalog_test.go +++ b/tools/migrate/productcatalog_test.go @@ -60,123 +60,6 @@ func TestStartAfterChange(t *testing.T) { }.Test(t) } -func TestEntitlementISO(t *testing.T) { - keptEntId := ulid.Make() - lostEntId := ulid.Make() - - keptGrantId := ulid.Make() - lostGrantId := ulid.Make() - - runner{ - stops: stops{ - { - // before: 20250108103427_billing-profile-progressive-billing-flag.up.sql - // after: 20250109231835_entitlements-usage-period-iso.up.sql - version: 20250108103427, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // We need to set up a feature - featId := ulid.Make() - _, err := db.Exec(` - INSERT INTO features (namespace, id, key, name, created_at, updated_at) - VALUES ('default', $1, 'feat_1', 'feat 1', NOW(), NOW())`, - featId.String(), - ) - require.NoError(t, err) - - // Kept - // We're chancing the duration format in entitlements and credits - _, err = db.Exec(` - INSERT INTO entitlements (namespace, id, created_at, updated_at, entitlement_type, feature_key, feature_id, subject_key, usage_period_interval) - VALUES ('default', $1, '2025-01-08 23:18:35', NOW(), 'BOOL', 'feature_1', $2, 'subject_1', 'MONTH')`, - keptEntId.String(), - featId.String(), - ) - require.NoError(t, err) - - _, err = db.Exec(` - INSERT INTO grants (namespace, id, owner_id, created_at, updated_at, recurrence_period, amount, effective_at, expiration, expires_at, reset_max_rollover, reset_min_rollover) - VALUES ('default', $1, $2, NOW(), NOW(), 'MONTH', 0, NOW(), '{}'::jsonb, NOW(), 0, 0)`, - keptGrantId.String(), keptEntId.String(), - ) - require.NoError(t, err) - - // Lost - // We're changing the duration format in entitlements and credits - _, err = db.Exec(` - INSERT INTO entitlements (namespace, id, created_at, updated_at, entitlement_type, feature_key, feature_id, subject_key, usage_period_interval) - VALUES ('default', $1, '2025-02-12 23:18:35', NOW(), 'BOOL', 'feature_1', $2, 'subject_1', 'P2W')`, - lostEntId.String(), - featId.String(), - ) - require.NoError(t, err) - - _, err = db.Exec(` - INSERT INTO grants (namespace, id, owner_id, created_at, updated_at, recurrence_period, amount, effective_at, expiration, expires_at, reset_max_rollover, reset_min_rollover) - VALUES ('default', $1, $2, NOW(), NOW(), 'P2W', 0, NOW(), '{}'::jsonb, NOW(), 0, 0)`, - lostGrantId.String(), lostEntId.String(), - ) - require.NoError(t, err) - }, - }, - { - // 20250109231835_entitlements-usage-period-iso.up.sql - version: 20250109231835, - direction: directionUp, - action: func(t *testing.T, db *sql.DB) { - // Let's validate that the usage_period_interval has been changed to iso format - var usagePeriodInterval string - - res := db.QueryRow(`SELECT usage_period_interval FROM entitlements WHERE id = $1`, keptEntId.String()) - require.NoError(t, res.Scan(&usagePeriodInterval)) - - require.Equal(t, "P1M", usagePeriodInterval) - - // Let's validate that the grants table has been updated as well - var recurrencePeriod string - - res = db.QueryRow(`SELECT recurrence_period FROM grants WHERE id = $1`, keptGrantId.String()) - require.NoError(t, res.Scan(&recurrencePeriod)) - - require.Equal(t, "P1M", recurrencePeriod) - }, - }, - { - // after 20250109231835_entitlements-usage-period-iso.up.sql - version: 20250108103427, - direction: directionDown, - action: func(t *testing.T, db *sql.DB) { - // Let's check that deleted_at is set for both the entitlements and grants table - - var deletedAt sql.NullString - - // Let's check it was kept - res := db.QueryRow(`SELECT deleted_at FROM entitlements WHERE id = $1`, keptEntId.String()) - require.NoError(t, res.Scan(&deletedAt)) - - require.Empty(t, deletedAt) - - res = db.QueryRow(`SELECT deleted_at FROM grants WHERE id = $1`, keptGrantId.String()) - require.NoError(t, res.Scan(&deletedAt)) - - require.Empty(t, deletedAt) - - // Let's check it was lost - res = db.QueryRow(`SELECT deleted_at FROM entitlements WHERE id = $1`, lostEntId.String()) - require.NoError(t, res.Scan(&deletedAt)) - - require.NotEmpty(t, deletedAt) - - res = db.QueryRow(`SELECT deleted_at FROM grants WHERE id = $1`, lostGrantId.String()) - require.NoError(t, res.Scan(&deletedAt)) - - require.NotEmpty(t, deletedAt) - }, - }, - }, - }.Test(t) -} - func TestPlanBillingCadenceProRatingMigration(t *testing.T) { // Plan with multiple rate cards in last phase - should pick shortest billing cadence plan1Id := ulid.Make() diff --git a/tools/migrate/testdata/sqlcgen/20250605102416/db/db.go b/tools/migrate/testdata/sqlcgen/20250605102416/db/db.go deleted file mode 100644 index 0c56c2b4e8..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250605102416/db/db.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 - -package db - -import ( - "context" - "database/sql" -) - -type DBTX interface { - ExecContext(context.Context, string, ...interface{}) (sql.Result, error) - PrepareContext(context.Context, string) (*sql.Stmt, error) - QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) - QueryRowContext(context.Context, string, ...interface{}) *sql.Row -} - -func New(db DBTX) *Queries { - return &Queries{db: db} -} - -type Queries struct { - db DBTX -} - -func (q *Queries) WithTx(tx *sql.Tx) *Queries { - return &Queries{ - db: tx, - } -} diff --git a/tools/migrate/testdata/sqlcgen/20250605102416/db/helpers.go b/tools/migrate/testdata/sqlcgen/20250605102416/db/helpers.go deleted file mode 100644 index c82836d032..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250605102416/db/helpers.go +++ /dev/null @@ -1,41 +0,0 @@ -package db - -import ( - "context" - "fmt" -) - -type LineHierarchy struct { - Line GetUsageBasedLineByIDRow - DetailedLines []GetFlatFeeLinesByParentIDRow -} - -func (q *Queries) GetLineHierarchyByDetailedLineID(ctx context.Context, detailedLineID string) (LineHierarchy, error) { - lineParent, err := q.GetParentID(ctx, detailedLineID) - if err != nil { - return LineHierarchy{}, err - } - - if !lineParent.Valid { - return LineHierarchy{}, fmt.Errorf("line parent not found") - } - - ubpLine, err := q.GetUsageBasedLineByID(ctx, lineParent.String) - if err != nil { - return LineHierarchy{}, err - } - - if ubpLine.ID != lineParent.String { - return LineHierarchy{}, fmt.Errorf("ubp line id does not match line parent id") - } - - detailedLines, err := q.GetFlatFeeLinesByParentID(ctx, lineParent.String) - if err != nil { - return LineHierarchy{}, err - } - - return LineHierarchy{ - Line: ubpLine, - DetailedLines: detailedLines, - }, nil -} diff --git a/tools/migrate/testdata/sqlcgen/20250605102416/db/models.go b/tools/migrate/testdata/sqlcgen/20250605102416/db/models.go deleted file mode 100644 index a0871d3f1b..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250605102416/db/models.go +++ /dev/null @@ -1,5 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 - -package db diff --git a/tools/migrate/testdata/sqlcgen/20250605102416/db/queries.sql.go b/tools/migrate/testdata/sqlcgen/20250605102416/db/queries.sql.go deleted file mode 100644 index 536f87430b..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250605102416/db/queries.sql.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 -// source: queries.sql - -package db - -import ( - "context" - "database/sql" - "encoding/json" - "time" - - "github.com/sqlc-dev/pqtype" -) - -const getFlatFeeLinesByParentID = `-- name: GetFlatFeeLinesByParentID :many - -SELECT l.id, l.namespace, l.metadata, l.created_at, l.updated_at, l.deleted_at, l.name, l.description, l.period_start, l.period_end, l.invoice_at, l.type, l.status, l.currency, l.quantity, l.tax_config, l.invoice_id, l.fee_line_config_id, l.usage_based_line_config_id, l.parent_line_id, l.child_unique_reference_id, l.amount, l.taxes_total, l.taxes_inclusive_total, l.taxes_exclusive_total, l.charges_total, l.discounts_total, l.total, l.invoicing_app_external_id, l.subscription_id, l.subscription_item_id, l.subscription_phase_id, l.line_ids, l.managed_by, l.ratecard_discounts, c.per_unit_amount, c.category, c.payment_term, c.index -FROM public.billing_invoice_lines l JOIN public.billing_invoice_flat_fee_line_configs c ON (l.fee_line_config_id = c.id) -WHERE type = 'flat_fee' AND status = 'detailed' AND l.parent_line_id = $1::varchar -` - -type GetFlatFeeLinesByParentIDRow struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - PeriodStart time.Time - PeriodEnd time.Time - InvoiceAt time.Time - Type string - Status string - Currency string - Quantity sql.NullString - TaxConfig pqtype.NullRawMessage - InvoiceID string - FeeLineConfigID sql.NullString - UsageBasedLineConfigID sql.NullString - ParentLineID sql.NullString - ChildUniqueReferenceID sql.NullString - Amount string - TaxesTotal string - TaxesInclusiveTotal string - TaxesExclusiveTotal string - ChargesTotal string - DiscountsTotal string - Total string - InvoicingAppExternalID sql.NullString - SubscriptionID sql.NullString - SubscriptionItemID sql.NullString - SubscriptionPhaseID sql.NullString - LineIds sql.NullString - ManagedBy string - RatecardDiscounts pqtype.NullRawMessage - PerUnitAmount string - Category string - PaymentTerm string - Index sql.NullInt64 -} - -func (q *Queries) GetFlatFeeLinesByParentID(ctx context.Context, parentLineID string) ([]GetFlatFeeLinesByParentIDRow, error) { - rows, err := q.db.QueryContext(ctx, getFlatFeeLinesByParentID, parentLineID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []GetFlatFeeLinesByParentIDRow - for rows.Next() { - var i GetFlatFeeLinesByParentIDRow - if err := rows.Scan( - &i.ID, - &i.Namespace, - &i.Metadata, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.Name, - &i.Description, - &i.PeriodStart, - &i.PeriodEnd, - &i.InvoiceAt, - &i.Type, - &i.Status, - &i.Currency, - &i.Quantity, - &i.TaxConfig, - &i.InvoiceID, - &i.FeeLineConfigID, - &i.UsageBasedLineConfigID, - &i.ParentLineID, - &i.ChildUniqueReferenceID, - &i.Amount, - &i.TaxesTotal, - &i.TaxesInclusiveTotal, - &i.TaxesExclusiveTotal, - &i.ChargesTotal, - &i.DiscountsTotal, - &i.Total, - &i.InvoicingAppExternalID, - &i.SubscriptionID, - &i.SubscriptionItemID, - &i.SubscriptionPhaseID, - &i.LineIds, - &i.ManagedBy, - &i.RatecardDiscounts, - &i.PerUnitAmount, - &i.Category, - &i.PaymentTerm, - &i.Index, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Close(); err != nil { - return nil, err - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const getParentID = `-- name: GetParentID :one -SELECT l.parent_line_id FROM public.billing_invoice_lines l WHERE l.id = $1::varchar -` - -func (q *Queries) GetParentID(ctx context.Context, lineID string) (sql.NullString, error) { - row := q.db.QueryRowContext(ctx, getParentID, lineID) - var parent_line_id sql.NullString - err := row.Scan(&parent_line_id) - return parent_line_id, err -} - -const getUsageBasedLineByID = `-- name: GetUsageBasedLineByID :one - -SELECT l.id, l.namespace, l.metadata, l.created_at, l.updated_at, l.deleted_at, l.name, l.description, l.period_start, l.period_end, l.invoice_at, l.type, l.status, l.currency, l.quantity, l.tax_config, l.invoice_id, l.fee_line_config_id, l.usage_based_line_config_id, l.parent_line_id, l.child_unique_reference_id, l.amount, l.taxes_total, l.taxes_inclusive_total, l.taxes_exclusive_total, l.charges_total, l.discounts_total, l.total, l.invoicing_app_external_id, l.subscription_id, l.subscription_item_id, l.subscription_phase_id, l.line_ids, l.managed_by, l.ratecard_discounts, c.price_type, c.feature_key, c.price, c.pre_line_period_quantity, c.metered_quantity, c.metered_pre_line_period_quantity -FROM public.billing_invoice_lines l JOIN public.billing_invoice_usage_based_line_configs c ON (l.usage_based_line_config_id = c.id) -WHERE type = 'usage_based' AND status = 'valid' AND l.id = $1::varchar -` - -type GetUsageBasedLineByIDRow struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - PeriodStart time.Time - PeriodEnd time.Time - InvoiceAt time.Time - Type string - Status string - Currency string - Quantity sql.NullString - TaxConfig pqtype.NullRawMessage - InvoiceID string - FeeLineConfigID sql.NullString - UsageBasedLineConfigID sql.NullString - ParentLineID sql.NullString - ChildUniqueReferenceID sql.NullString - Amount string - TaxesTotal string - TaxesInclusiveTotal string - TaxesExclusiveTotal string - ChargesTotal string - DiscountsTotal string - Total string - InvoicingAppExternalID sql.NullString - SubscriptionID sql.NullString - SubscriptionItemID sql.NullString - SubscriptionPhaseID sql.NullString - LineIds sql.NullString - ManagedBy string - RatecardDiscounts pqtype.NullRawMessage - PriceType string - FeatureKey sql.NullString - Price json.RawMessage - PreLinePeriodQuantity sql.NullString - MeteredQuantity sql.NullString - MeteredPreLinePeriodQuantity sql.NullString -} - -func (q *Queries) GetUsageBasedLineByID(ctx context.Context, lineID string) (GetUsageBasedLineByIDRow, error) { - row := q.db.QueryRowContext(ctx, getUsageBasedLineByID, lineID) - var i GetUsageBasedLineByIDRow - err := row.Scan( - &i.ID, - &i.Namespace, - &i.Metadata, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.Name, - &i.Description, - &i.PeriodStart, - &i.PeriodEnd, - &i.InvoiceAt, - &i.Type, - &i.Status, - &i.Currency, - &i.Quantity, - &i.TaxConfig, - &i.InvoiceID, - &i.FeeLineConfigID, - &i.UsageBasedLineConfigID, - &i.ParentLineID, - &i.ChildUniqueReferenceID, - &i.Amount, - &i.TaxesTotal, - &i.TaxesInclusiveTotal, - &i.TaxesExclusiveTotal, - &i.ChargesTotal, - &i.DiscountsTotal, - &i.Total, - &i.InvoicingAppExternalID, - &i.SubscriptionID, - &i.SubscriptionItemID, - &i.SubscriptionPhaseID, - &i.LineIds, - &i.ManagedBy, - &i.RatecardDiscounts, - &i.PriceType, - &i.FeatureKey, - &i.Price, - &i.PreLinePeriodQuantity, - &i.MeteredQuantity, - &i.MeteredPreLinePeriodQuantity, - ) - return i, err -} diff --git a/tools/migrate/testdata/sqlcgen/20250605102416/fixture.sql b/tools/migrate/testdata/sqlcgen/20250605102416/fixture.sql deleted file mode 100644 index 548bd9203e..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250605102416/fixture.sql +++ /dev/null @@ -1,350 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 14.17 --- Dumped by pg_dump version 15.13 (Homebrew) - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- Data for Name: addons; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: features; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.features (id, created_at, updated_at, deleted_at, metadata, namespace, name, key, meter_slug, meter_group_by_filters, archived_at) VALUES ('01JWB2ND12J6DMTS4T0RCFSQH3', '2025-05-28 09:13:06.850727+00', '2025-05-28 09:13:06.850727+00', NULL, 'null', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 'api-requests-total', 'api-requests-total', 'api-requests-total', NULL, NULL); - - --- --- Data for Name: addon_rate_cards; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: apps; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.apps (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, type, status, is_default) VALUES ('01JWB2ND0MDGNC6WZBBW8ZQCAC', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', NULL, '2025-05-28 09:13:06.836674+00', '2025-05-28 09:13:06.836675+00', NULL, 'Sandbox', 'Sandbox app', 'sandbox', 'ready', true); - - --- --- Data for Name: app_custom_invoicings; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: customers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.customers (id, namespace, metadata, created_at, updated_at, deleted_at, name, currency, primary_email, billing_address_country, billing_address_postal_code, billing_address_state, billing_address_city, billing_address_line1, billing_address_line2, billing_address_phone_number, description, key) VALUES ('01JWB2ND14ZQ65N9N083RXTGZJ', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', NULL, '2025-05-28 09:13:06.85223+00', '2025-05-28 09:13:06.85223+00', NULL, 'Test Customer', 'USD', 'test@test.com', 'US', '12345', NULL, NULL, NULL, NULL, NULL, NULL, NULL); - - --- --- Data for Name: app_custom_invoicing_customers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: app_customers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: app_stripes; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: app_stripe_customers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: entitlements; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: balance_snapshots; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_backup_migrated_flat_fees; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_customer_locks; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_customer_locks (id, namespace, customer_id) VALUES ('01JWB2ND393N8C2ZSB4BHZWCXS', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', '01JWB2ND14ZQ65N9N083RXTGZJ'); - - --- --- Data for Name: billing_workflow_configs; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_workflow_configs (id, namespace, created_at, updated_at, deleted_at, collection_alignment, invoice_auto_advance, invoice_collection_method, line_collection_period, invoice_draft_period, invoice_due_after, invoice_progressive_billing, invoice_default_tax_settings, tax_enabled, tax_enforced) VALUES ('01JWB2ND0XSPE60CM2GEE0PK4C', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', '2025-05-28 09:13:06.84535+00', '2025-05-28 09:13:06.845351+00', NULL, 'subscription', true, 'charge_automatically', 'P0D', 'P1D', 'P1W', false, NULL, true, false); -INSERT INTO public.billing_workflow_configs (id, namespace, created_at, updated_at, deleted_at, collection_alignment, invoice_auto_advance, invoice_collection_method, line_collection_period, invoice_draft_period, invoice_due_after, invoice_progressive_billing, invoice_default_tax_settings, tax_enabled, tax_enforced) VALUES ('01JWB2ND40XHQTDXBBNZA6JQ0J', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', '2024-01-03 00:00:00+00', '2024-01-03 00:00:00+00', NULL, 'subscription', true, 'charge_automatically', 'P0D', 'P1D', 'P1W', false, NULL, true, false); - - --- --- Data for Name: billing_profiles; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_profiles (id, namespace, created_at, updated_at, deleted_at, "default", workflow_config_id, metadata, supplier_address_country, supplier_address_postal_code, supplier_address_state, supplier_address_city, supplier_address_line1, supplier_address_line2, supplier_address_phone_number, supplier_name, name, description, supplier_tax_code, tax_app_id, invoicing_app_id, payment_app_id) VALUES ('01JWB2ND0YXXWNWYCPVNZQWB46', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', '2025-05-28 09:13:06.846356+00', '2025-05-28 09:13:06.846356+00', NULL, true, '01JWB2ND0XSPE60CM2GEE0PK4C', 'null', 'US', NULL, NULL, NULL, NULL, NULL, NULL, 'Awesome Supplier', 'Awesome Profile', NULL, NULL, '01JWB2ND0MDGNC6WZBBW8ZQCAC', '01JWB2ND0MDGNC6WZBBW8ZQCAC', '01JWB2ND0MDGNC6WZBBW8ZQCAC'); - - --- --- Data for Name: billing_customer_overrides; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoice_flat_fee_line_configs; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_invoice_flat_fee_line_configs (id, namespace, per_unit_amount, category, payment_term, index) VALUES ('01JWB2ND42F01QM0GVC37N6M1S', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 6, 'regular', 'in_advance', NULL); -INSERT INTO public.billing_invoice_flat_fee_line_configs (id, namespace, per_unit_amount, category, payment_term, index) VALUES ('01JWB2ND42F01QM0GVC3RY1SSC', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 6, 'regular', 'in_advance', NULL); -INSERT INTO public.billing_invoice_flat_fee_line_configs (id, namespace, per_unit_amount, category, payment_term, index) VALUES ('01JWB2ND42F01QM0GVC554XAE8', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 6, 'regular', 'in_advance', NULL); - - --- --- Data for Name: billing_invoice_usage_based_line_configs; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoices; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_invoices (id, namespace, created_at, updated_at, deleted_at, metadata, customer_id, voided_at, currency, status, period_start, period_end, source_billing_profile_id, workflow_config_id, number, supplier_address_country, supplier_address_postal_code, supplier_address_state, supplier_address_city, supplier_address_line1, supplier_address_line2, supplier_address_phone_number, customer_address_country, customer_address_postal_code, customer_address_state, customer_address_city, customer_address_line1, customer_address_line2, customer_address_phone_number, supplier_name, supplier_tax_code, customer_name, type, description, issued_at, due_at, tax_app_id, invoicing_app_id, payment_app_id, draft_until, customer_usage_attribution, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, payment_app_external_id, collection_at, sent_to_customer_at, tax_app_external_id, status_details_cache, quantity_snapshoted_at) VALUES ('01JWB2ND40XHQTDXBBP18J9QJ0', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', '2024-01-03 00:00:00+00', '2024-01-03 00:00:00+00', NULL, 'null', '01JWB2ND14ZQ65N9N083RXTGZJ', NULL, 'USD', 'gathering', '2024-01-01 00:00:00+00', '2024-01-04 00:00:00+00', '01JWB2ND0YXXWNWYCPVNZQWB46', '01JWB2ND40XHQTDXBBNZA6JQ0J', 'GATHER-TECU-USD-1', 'US', NULL, NULL, NULL, NULL, NULL, NULL, 'US', '12345', NULL, NULL, NULL, NULL, NULL, 'Awesome Supplier', NULL, 'Test Customer', 'standard', NULL, NULL, NULL, '01JWB2ND0MDGNC6WZBBW8ZQCAC', '01JWB2ND0MDGNC6WZBBW8ZQCAC', '01JWB2ND0MDGNC6WZBBW8ZQCAC', NULL, '{"type": "customer_usage_attribution.v1", "subjectKeys": ["test"]}', 0, 0, 0, 0, 0, 0, 0, NULL, NULL, '2024-01-01 00:00:00+00', NULL, NULL, NULL, NULL); - - --- --- Data for Name: plans; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.plans (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, key, version, currency, effective_from, effective_to, billables_must_align) VALUES ('01JWB2ND1T6MJ5KXTS0YQ9TD0Y', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 'null', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00', NULL, 'Test Plan', NULL, 'test-plan', 1, 'USD', NULL, NULL, false); - - --- --- Data for Name: subscriptions; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.subscriptions (id, namespace, created_at, updated_at, deleted_at, metadata, active_from, active_to, currency, customer_id, name, description, plan_id, billables_must_align) VALUES ('01JWB2ND2A1JM4YN054JSSNGVP', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00', NULL, 'null', '2024-01-01 00:00:00+00', NULL, 'USD', '01JWB2ND14ZQ65N9N083RXTGZJ', 'subs-1', NULL, '01JWB2ND1T6MJ5KXTS0YQ9TD0Y', false); - - --- --- Data for Name: subscription_phases; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.subscription_phases (id, namespace, created_at, updated_at, deleted_at, metadata, key, name, description, active_from, subscription_id) VALUES ('01JWB2ND2C2JHF9ZNA8QFATT74', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00', NULL, 'null', 'first-phase', 'first-phase', NULL, '2024-01-01 00:00:00+00', '01JWB2ND2A1JM4YN054JSSNGVP'); - - --- --- Data for Name: subscription_items; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.subscription_items (id, namespace, created_at, updated_at, deleted_at, metadata, active_from, active_to, key, active_from_override_relative_to_phase_start, active_to_override_relative_to_phase_start, name, description, feature_key, entitlement_template, tax_config, billing_cadence, price, entitlement_id, phase_id, restarts_billing_period, discounts, annotations) VALUES ('01JWB2ND2EG2B716S8W6NKRRJK', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00', NULL, NULL, '2024-01-01 00:00:00+00', NULL, 'in-advance', NULL, NULL, 'in-advance', NULL, NULL, NULL, NULL, 'P1D', '{"type": "flat", "amount": "6", "paymentTerm": "in_advance"}', NULL, '01JWB2ND2C2JHF9ZNA8QFATT74', NULL, NULL, '{"subscription.owner": ["subscription"]}'); - - --- --- Data for Name: billing_invoice_lines; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts) VALUES ('01JWB2ND43KPCHMXHKD0KETF5M', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 'null', '2024-01-03 00:00:00+00', '2024-01-03 00:00:00+00', NULL, 'in-advance', NULL, '2024-01-03 00:00:00+00', '2024-01-04 00:00:00+00', '2024-01-03 00:00:00+00', 'flat_fee', 'valid', 'USD', 1, NULL, '01JWB2ND40XHQTDXBBP18J9QJ0', '01JWB2ND42F01QM0GVC554XAE8', NULL, NULL, '01JWB2ND2A1JM4YN054JSSNGVP/first-phase/in-advance/v[0]/period[2]', 6, 0, 0, 0, 0, 0, 6, NULL, '01JWB2ND2A1JM4YN054JSSNGVP', '01JWB2ND2EG2B716S8W6NKRRJK', '01JWB2ND2C2JHF9ZNA8QFATT74', NULL, 'subscription', NULL); -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts) VALUES ('01JWB2ND43KPCHMXHKCW3PFW6W', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 'null', '2024-01-03 00:00:00+00', '2024-01-03 00:00:00+00', '2024-01-03 00:00:00+00', 'in-advance', NULL, '2024-01-01 00:00:00+00', '2024-01-02 00:00:00+00', '2024-01-01 00:00:00+00', 'flat_fee', 'valid', 'USD', 1, NULL, '01JWB2ND40XHQTDXBBP18J9QJ0', '01JWB2ND42F01QM0GVC37N6M1S', NULL, NULL, '01JWB2ND2A1JM4YN054JSSNGVP/first-phase/in-advance/v[0]/period[0]', 6, 0, 0, 0, 0, 0, 6, NULL, '01JWB2ND2A1JM4YN054JSSNGVP', '01JWB2ND2EG2B716S8W6NKRRJK', '01JWB2ND2C2JHF9ZNA8QFATT74', NULL, 'subscription', NULL); -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts) VALUES ('01JWB2ND43KPCHMXHKCYEQ13WY', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 'null', '2024-01-03 00:00:00+00', '2024-01-03 00:00:00+00', NULL, 'in-advance', NULL, '2024-01-02 00:00:00+00', '2024-01-03 00:00:00+00', '2024-01-02 00:00:00+00', 'flat_fee', 'valid', 'USD', 1, NULL, '01JWB2ND40XHQTDXBBP18J9QJ0', '01JWB2ND42F01QM0GVC3RY1SSC', NULL, NULL, '01JWB2ND2A1JM4YN054JSSNGVP/first-phase/in-advance/v[0]/period[1]', 6, 0, 0, 0, 0, 0, 6, 'invoicing-external-id', '01JWB2ND2A1JM4YN054JSSNGVP', '01JWB2ND2EG2B716S8W6NKRRJK', '01JWB2ND2C2JHF9ZNA8QFATT74', NULL, 'subscription', NULL); - - --- --- Data for Name: billing_invoice_line_discounts; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoice_line_usage_discounts; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoice_validation_issues; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_sequence_numbers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_sequence_numbers (id, namespace, scope, last) VALUES (1, 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 'invoices/gathering', 1); - - --- --- Data for Name: customer_subjects; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.customer_subjects (id, subject_key, created_at, customer_id, namespace, deleted_at) VALUES (1, 'test', '2025-05-28 09:13:06.856315+00', '01JWB2ND14ZQ65N9N083RXTGZJ', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', NULL); - - --- --- Data for Name: grants; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: meters; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_channels; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_rules; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_channel_rules; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_event_delivery_status; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_events; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_event_delivery_status_events; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: plan_addons; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: plan_phases; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.plan_phases (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, key, plan_id, index, duration) VALUES ('01JWB2ND1WGAXGZZ31XMHGQNF0', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 'null', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00', NULL, 'first-phase', NULL, 'first-phase', '01JWB2ND1T6MJ5KXTS0YQ9TD0Y', 0, NULL); - - --- --- Data for Name: plan_rate_cards; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.plan_rate_cards (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, key, type, feature_key, entitlement_template, tax_config, billing_cadence, price, feature_id, phase_id, discounts) VALUES ('01JWB2ND1YJT84V9PRV4QVHFVT', 'test-subs-update-01JWB2ND0EBJWE1FX8EN9AVVJP', 'null', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00', NULL, 'in-advance', NULL, 'in-advance', 'usage_based', NULL, 'null', NULL, 'P1D', '{"type": "flat", "amount": "6", "paymentTerm": "in_advance"}', NULL, '01JWB2ND1WGAXGZZ31XMHGQNF0', 'null'); - - --- --- Data for Name: subscription_addons; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: subscription_addon_quantities; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: usage_resets; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Name: app_custom_invoicing_customers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.app_custom_invoicing_customers_id_seq', 1, false); - - --- --- Name: app_customers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.app_customers_id_seq', 1, false); - - --- --- Name: app_stripe_customers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.app_stripe_customers_id_seq', 1, false); - - --- --- Name: balance_snapshots_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.balance_snapshots_id_seq', 1, false); - - --- --- Name: billing_sequence_numbers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.billing_sequence_numbers_id_seq', 1, true); - - --- --- Name: customer_subjects_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.customer_subjects_id_seq', 1, true); - - --- --- PostgreSQL database dump complete --- - diff --git a/tools/migrate/testdata/sqlcgen/20250605102416/sqlc.yaml b/tools/migrate/testdata/sqlcgen/20250605102416/sqlc.yaml deleted file mode 100644 index 9e6954cd21..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250605102416/sqlc.yaml +++ /dev/null @@ -1,10 +0,0 @@ -version: "2" -sql: - - engine: "postgresql" - queries: "sqlc/queries.sql" - schema: "sqlc/db-schema.sql" - gen: - go: - package: "db" - out: "db" - omit_unused_structs: true diff --git a/tools/migrate/testdata/sqlcgen/20250605102416/sqlc/db-schema.sql b/tools/migrate/testdata/sqlcgen/20250605102416/sqlc/db-schema.sql deleted file mode 100644 index 7521a9281a..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250605102416/sqlc/db-schema.sql +++ /dev/null @@ -1,3182 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 14.17 --- Dumped by pg_dump version 15.13 (Homebrew) - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- Name: public; Type: SCHEMA; Schema: -; Owner: postgres --- - --- *not* creating schema, since initdb creates it - - -ALTER SCHEMA public OWNER TO postgres; - --- --- Name: pgcrypto; Type: EXTENSION; Schema: -; Owner: - --- - -CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; - - --- --- Name: EXTENSION pgcrypto; Type: COMMENT; Schema: -; Owner: --- - -COMMENT ON EXTENSION pgcrypto IS 'cryptographic functions'; - - -SET default_tablespace = ''; - -SET default_table_access_method = heap; - --- --- Name: addon_rate_cards; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.addon_rate_cards ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - type character varying NOT NULL, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - discounts jsonb, - addon_id character(26) NOT NULL, - feature_id character(26) -); - - -ALTER TABLE public.addon_rate_cards OWNER TO pgtdbuser; - --- --- Name: addons; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - version bigint NOT NULL, - currency character varying DEFAULT 'USD'::character varying NOT NULL, - effective_from timestamp with time zone, - effective_to timestamp with time zone, - annotations jsonb, - instance_type character varying DEFAULT 'single'::character varying NOT NULL -); - - -ALTER TABLE public.addons OWNER TO pgtdbuser; - --- --- Name: app_custom_invoicing_customers; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.app_custom_invoicing_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - -ALTER TABLE public.app_custom_invoicing_customers OWNER TO pgtdbuser; - --- --- Name: app_custom_invoicing_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE public.app_custom_invoicing_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_custom_invoicing_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_custom_invoicings; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.app_custom_invoicings ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - enable_draft_sync_hook boolean DEFAULT false NOT NULL, - enable_issuing_sync_hook boolean DEFAULT false NOT NULL -); - - -ALTER TABLE public.app_custom_invoicings OWNER TO pgtdbuser; - --- --- Name: app_customers; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.app_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - -ALTER TABLE public.app_customers OWNER TO pgtdbuser; - --- --- Name: app_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE public.app_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_stripe_customers; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.app_stripe_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - stripe_customer_id character varying NOT NULL, - stripe_default_payment_method_id character varying, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - -ALTER TABLE public.app_stripe_customers OWNER TO pgtdbuser; - --- --- Name: app_stripe_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE public.app_stripe_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_stripe_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_stripes; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.app_stripes ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - stripe_account_id character varying NOT NULL, - stripe_livemode boolean NOT NULL, - api_key character varying NOT NULL, - stripe_webhook_id character varying NOT NULL, - webhook_secret character varying NOT NULL, - masked_api_key character varying NOT NULL -); - - -ALTER TABLE public.app_stripes OWNER TO pgtdbuser; - --- --- Name: apps; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.apps ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - type character varying NOT NULL, - status character varying NOT NULL, - is_default boolean DEFAULT false NOT NULL -); - - -ALTER TABLE public.apps OWNER TO pgtdbuser; - --- --- Name: balance_snapshots; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.balance_snapshots ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - grant_balances jsonb NOT NULL, - balance numeric NOT NULL, - overage numeric NOT NULL, - at timestamp with time zone NOT NULL, - owner_id character(26) NOT NULL, - usage jsonb -); - - -ALTER TABLE public.balance_snapshots OWNER TO pgtdbuser; - --- --- Name: balance_snapshots_id_seq; Type: SEQUENCE; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE public.balance_snapshots ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.balance_snapshots_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: billing_backup_migrated_flat_fees; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_backup_migrated_flat_fees ( - id character(26), - namespace character varying, - metadata jsonb, - created_at timestamp with time zone, - updated_at timestamp with time zone, - deleted_at timestamp with time zone, - name character varying, - description character varying, - period_start timestamp with time zone, - period_end timestamp with time zone, - invoice_at timestamp with time zone, - type character varying, - status character varying, - currency character varying(3), - quantity numeric, - tax_config jsonb, - invoice_id character(26), - fee_line_config_id character(26), - usage_based_line_config_id character(26), - parent_line_id character(26), - child_unique_reference_id character varying, - amount numeric, - taxes_total numeric, - taxes_inclusive_total numeric, - taxes_exclusive_total numeric, - charges_total numeric, - discounts_total numeric, - total numeric, - invoicing_app_external_id character varying, - subscription_id character(26), - subscription_item_id character(26), - subscription_phase_id character(26), - line_ids character(26), - managed_by character varying, - ratecard_discounts jsonb, - per_unit_amount numeric, - category character varying, - payment_term character varying, - index bigint -); - - -ALTER TABLE public.billing_backup_migrated_flat_fees OWNER TO pgtdbuser; - --- --- Name: billing_customer_locks; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_customer_locks ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - customer_id character(26) NOT NULL -); - - -ALTER TABLE public.billing_customer_locks OWNER TO pgtdbuser; - --- --- Name: billing_customer_overrides; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_customer_overrides ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - collection_alignment character varying, - invoice_auto_advance boolean, - invoice_collection_method character varying, - billing_profile_id character(26), - customer_id character(26) NOT NULL, - line_collection_period character varying, - invoice_draft_period character varying, - invoice_due_after character varying, - invoice_progressive_billing boolean, - invoice_default_tax_config jsonb -); - - -ALTER TABLE public.billing_customer_overrides OWNER TO pgtdbuser; - --- --- Name: billing_invoice_flat_fee_line_configs; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_invoice_flat_fee_line_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - per_unit_amount numeric NOT NULL, - category character varying DEFAULT 'regular'::character varying NOT NULL, - payment_term character varying DEFAULT 'in_advance'::character varying NOT NULL, - index bigint -); - - -ALTER TABLE public.billing_invoice_flat_fee_line_configs OWNER TO pgtdbuser; - --- --- Name: billing_invoice_line_discounts; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_invoice_line_discounts ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - child_unique_reference_id character varying, - description character varying, - amount numeric NOT NULL, - line_id character(26) NOT NULL, - invoicing_app_external_id character varying, - reason character varying NOT NULL, - type character varying, - rounding_amount numeric, - quantity numeric, - pre_line_period_quantity numeric, - source_discount jsonb -); - - -ALTER TABLE public.billing_invoice_line_discounts OWNER TO pgtdbuser; - --- --- Name: billing_invoice_line_usage_discounts; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_invoice_line_usage_discounts ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - child_unique_reference_id character varying, - description character varying, - reason character varying NOT NULL, - invoicing_app_external_id character varying, - quantity numeric NOT NULL, - pre_line_period_quantity numeric, - reason_details jsonb, - line_id character(26) NOT NULL -); - - -ALTER TABLE public.billing_invoice_line_usage_discounts OWNER TO pgtdbuser; - --- --- Name: billing_invoice_lines; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_invoice_lines ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - period_start timestamp with time zone NOT NULL, - period_end timestamp with time zone NOT NULL, - invoice_at timestamp with time zone NOT NULL, - type character varying NOT NULL, - status character varying NOT NULL, - currency character varying(3) NOT NULL, - quantity numeric, - tax_config jsonb, - invoice_id character(26) NOT NULL, - fee_line_config_id character(26), - usage_based_line_config_id character(26), - parent_line_id character(26), - child_unique_reference_id character varying, - amount numeric NOT NULL, - taxes_total numeric NOT NULL, - taxes_inclusive_total numeric NOT NULL, - taxes_exclusive_total numeric NOT NULL, - charges_total numeric NOT NULL, - discounts_total numeric NOT NULL, - total numeric NOT NULL, - invoicing_app_external_id character varying, - subscription_id character(26), - subscription_item_id character(26), - subscription_phase_id character(26), - line_ids character(26), - managed_by character varying NOT NULL, - ratecard_discounts jsonb -); - - -ALTER TABLE public.billing_invoice_lines OWNER TO pgtdbuser; - --- --- Name: billing_invoice_usage_based_line_configs; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_invoice_usage_based_line_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - price_type character varying NOT NULL, - feature_key character varying, - price jsonb NOT NULL, - pre_line_period_quantity numeric, - metered_quantity numeric, - metered_pre_line_period_quantity numeric -); - - -ALTER TABLE public.billing_invoice_usage_based_line_configs OWNER TO pgtdbuser; - --- --- Name: billing_invoice_validation_issues; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_invoice_validation_issues ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - severity character varying NOT NULL, - code character varying, - message character varying NOT NULL, - path character varying, - component character varying NOT NULL, - dedupe_hash bytea NOT NULL, - invoice_id character(26) NOT NULL -); - - -ALTER TABLE public.billing_invoice_validation_issues OWNER TO pgtdbuser; - --- --- Name: billing_invoices; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_invoices ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - customer_id character(26) NOT NULL, - voided_at timestamp with time zone, - currency character varying(3) NOT NULL, - status character varying NOT NULL, - period_start timestamp with time zone, - period_end timestamp with time zone, - source_billing_profile_id character(26) NOT NULL, - workflow_config_id character(26) NOT NULL, - number character varying NOT NULL, - supplier_address_country character varying, - supplier_address_postal_code character varying, - supplier_address_state character varying, - supplier_address_city character varying, - supplier_address_line1 character varying, - supplier_address_line2 character varying, - supplier_address_phone_number character varying, - customer_address_country character varying, - customer_address_postal_code character varying, - customer_address_state character varying, - customer_address_city character varying, - customer_address_line1 character varying, - customer_address_line2 character varying, - customer_address_phone_number character varying, - supplier_name character varying NOT NULL, - supplier_tax_code character varying, - customer_name character varying NOT NULL, - type character varying NOT NULL, - description character varying, - issued_at timestamp with time zone, - due_at timestamp with time zone, - tax_app_id character(26) NOT NULL, - invoicing_app_id character(26) NOT NULL, - payment_app_id character(26) NOT NULL, - draft_until timestamp with time zone, - customer_usage_attribution jsonb NOT NULL, - amount numeric NOT NULL, - taxes_total numeric NOT NULL, - taxes_inclusive_total numeric NOT NULL, - taxes_exclusive_total numeric NOT NULL, - charges_total numeric NOT NULL, - discounts_total numeric NOT NULL, - total numeric NOT NULL, - invoicing_app_external_id character varying, - payment_app_external_id character varying, - collection_at timestamp with time zone, - sent_to_customer_at timestamp with time zone, - tax_app_external_id character varying, - status_details_cache jsonb, - quantity_snapshoted_at timestamp with time zone -); - - -ALTER TABLE public.billing_invoices OWNER TO pgtdbuser; - --- --- Name: billing_profiles; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_profiles ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - "default" boolean DEFAULT false NOT NULL, - workflow_config_id character(26) NOT NULL, - metadata jsonb, - supplier_address_country character varying, - supplier_address_postal_code character varying, - supplier_address_state character varying, - supplier_address_city character varying, - supplier_address_line1 character varying, - supplier_address_line2 character varying, - supplier_address_phone_number character varying, - supplier_name character varying NOT NULL, - name character varying NOT NULL, - description character varying, - supplier_tax_code character varying, - tax_app_id character(26) NOT NULL, - invoicing_app_id character(26) NOT NULL, - payment_app_id character(26) NOT NULL -); - - -ALTER TABLE public.billing_profiles OWNER TO pgtdbuser; - --- --- Name: billing_sequence_numbers; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_sequence_numbers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - scope character varying NOT NULL, - last numeric NOT NULL -); - - -ALTER TABLE public.billing_sequence_numbers OWNER TO pgtdbuser; - --- --- Name: billing_sequence_numbers_id_seq; Type: SEQUENCE; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE public.billing_sequence_numbers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.billing_sequence_numbers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: billing_workflow_configs; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.billing_workflow_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - collection_alignment character varying NOT NULL, - invoice_auto_advance boolean NOT NULL, - invoice_collection_method character varying NOT NULL, - line_collection_period character varying NOT NULL, - invoice_draft_period character varying NOT NULL, - invoice_due_after character varying NOT NULL, - invoice_progressive_billing boolean NOT NULL, - invoice_default_tax_settings jsonb, - tax_enabled boolean DEFAULT true NOT NULL, - tax_enforced boolean DEFAULT false NOT NULL -); - - -ALTER TABLE public.billing_workflow_configs OWNER TO pgtdbuser; - --- --- Name: customer_subjects; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.customer_subjects ( - id bigint NOT NULL, - subject_key character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - customer_id character(26) NOT NULL, - namespace character varying NOT NULL, - deleted_at timestamp with time zone -); - - -ALTER TABLE public.customer_subjects OWNER TO pgtdbuser; - --- --- Name: customer_subjects_id_seq; Type: SEQUENCE; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE public.customer_subjects ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.customer_subjects_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: customers; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.customers ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - currency character varying, - primary_email character varying, - billing_address_country character varying, - billing_address_postal_code character varying, - billing_address_state character varying, - billing_address_city character varying, - billing_address_line1 character varying, - billing_address_line2 character varying, - billing_address_phone_number character varying, - description character varying, - key character varying -); - - -ALTER TABLE public.customers OWNER TO pgtdbuser; - --- --- Name: entitlements; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.entitlements ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - entitlement_type character varying NOT NULL, - feature_key character varying NOT NULL, - subject_key character varying NOT NULL, - measure_usage_from timestamp with time zone, - issue_after_reset double precision, - issue_after_reset_priority smallint, - is_soft_limit boolean, - preserve_overage_at_reset boolean, - config jsonb, - usage_period_interval character varying, - usage_period_anchor timestamp with time zone, - current_usage_period_start timestamp with time zone, - current_usage_period_end timestamp with time zone, - feature_id character(26) NOT NULL, - active_from timestamp with time zone, - active_to timestamp with time zone, - annotations jsonb -); - - -ALTER TABLE public.entitlements OWNER TO pgtdbuser; - --- --- Name: features; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.features ( - id character(26) NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - namespace character varying NOT NULL, - name character varying NOT NULL, - key character varying NOT NULL, - meter_slug character varying, - meter_group_by_filters jsonb, - archived_at timestamp with time zone -); - - -ALTER TABLE public.features OWNER TO pgtdbuser; - --- --- Name: grants; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.grants ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - amount numeric NOT NULL, - priority smallint DEFAULT 0 NOT NULL, - effective_at timestamp with time zone NOT NULL, - expiration jsonb NOT NULL, - expires_at timestamp with time zone NOT NULL, - voided_at timestamp with time zone, - reset_max_rollover numeric NOT NULL, - reset_min_rollover numeric NOT NULL, - recurrence_period character varying, - recurrence_anchor timestamp with time zone, - owner_id character(26) NOT NULL -); - - -ALTER TABLE public.grants OWNER TO pgtdbuser; - --- --- Name: meters; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.meters ( - id character(26) NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - key character varying NOT NULL, - description character varying, - event_type character varying NOT NULL, - value_property character varying, - group_by jsonb, - aggregation character varying NOT NULL, - namespace character varying NOT NULL, - name character varying NOT NULL, - event_from timestamp with time zone, - metadata jsonb, - deleted_at timestamp with time zone -); - - -ALTER TABLE public.meters OWNER TO pgtdbuser; - --- --- Name: notification_channel_rules; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.notification_channel_rules ( - notification_channel_id character(26) NOT NULL, - notification_rule_id character(26) NOT NULL -); - - -ALTER TABLE public.notification_channel_rules OWNER TO pgtdbuser; - --- --- Name: notification_channels; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.notification_channels ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - type character varying NOT NULL, - name character varying NOT NULL, - disabled boolean DEFAULT false, - config jsonb NOT NULL -); - - -ALTER TABLE public.notification_channels OWNER TO pgtdbuser; - --- --- Name: notification_event_delivery_status; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.notification_event_delivery_status ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - event_id character varying NOT NULL, - channel_id character varying NOT NULL, - state character varying DEFAULT 'PENDING'::character varying NOT NULL, - reason character varying -); - - -ALTER TABLE public.notification_event_delivery_status OWNER TO pgtdbuser; - --- --- Name: notification_event_delivery_status_events; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.notification_event_delivery_status_events ( - notification_event_delivery_status_id character(26) NOT NULL, - notification_event_id character(26) NOT NULL -); - - -ALTER TABLE public.notification_event_delivery_status_events OWNER TO pgtdbuser; - --- --- Name: notification_events; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.notification_events ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - type character varying NOT NULL, - payload jsonb NOT NULL, - annotations jsonb, - rule_id character(26) NOT NULL -); - - -ALTER TABLE public.notification_events OWNER TO pgtdbuser; - --- --- Name: notification_rules; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.notification_rules ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - type character varying NOT NULL, - name character varying NOT NULL, - disabled boolean DEFAULT false, - config jsonb NOT NULL -); - - -ALTER TABLE public.notification_rules OWNER TO pgtdbuser; - --- --- Name: plan_addons; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.plan_addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - annotations jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - from_plan_phase character varying NOT NULL, - max_quantity bigint, - addon_id character(26) NOT NULL, - plan_id character(26) NOT NULL -); - - -ALTER TABLE public.plan_addons OWNER TO pgtdbuser; - --- --- Name: plan_phases; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.plan_phases ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - plan_id character(26) NOT NULL, - index smallint NOT NULL, - duration character varying -); - - -ALTER TABLE public.plan_phases OWNER TO pgtdbuser; - --- --- Name: plan_rate_cards; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.plan_rate_cards ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - type character varying NOT NULL, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - feature_id character(26), - phase_id character(26) NOT NULL, - discounts jsonb -); - - -ALTER TABLE public.plan_rate_cards OWNER TO pgtdbuser; - --- --- Name: plans; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.plans ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - version bigint NOT NULL, - currency character varying DEFAULT 'USD'::character varying NOT NULL, - effective_from timestamp with time zone, - effective_to timestamp with time zone, - billables_must_align boolean DEFAULT false NOT NULL -); - - -ALTER TABLE public.plans OWNER TO pgtdbuser; - --- --- Name: schema_om; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.schema_om ( - version bigint NOT NULL, - dirty boolean NOT NULL -); - - -ALTER TABLE public.schema_om OWNER TO pgtdbuser; - --- --- Name: subscription_addon_quantities; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.subscription_addon_quantities ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - active_from timestamp with time zone NOT NULL, - quantity bigint DEFAULT 1 NOT NULL, - subscription_addon_id character(26) NOT NULL -); - - -ALTER TABLE public.subscription_addon_quantities OWNER TO pgtdbuser; - --- --- Name: subscription_addons; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.subscription_addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - addon_id character(26) NOT NULL, - subscription_id character(26) NOT NULL -); - - -ALTER TABLE public.subscription_addons OWNER TO pgtdbuser; - --- --- Name: subscription_items; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.subscription_items ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - active_from timestamp with time zone NOT NULL, - active_to timestamp with time zone, - key character varying NOT NULL, - active_from_override_relative_to_phase_start character varying, - active_to_override_relative_to_phase_start character varying, - name character varying NOT NULL, - description character varying, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - entitlement_id character(26), - phase_id character(26) NOT NULL, - restarts_billing_period boolean, - discounts jsonb, - annotations jsonb -); - - -ALTER TABLE public.subscription_items OWNER TO pgtdbuser; - --- --- Name: subscription_phases; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.subscription_phases ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - key character varying NOT NULL, - name character varying NOT NULL, - description character varying, - active_from timestamp with time zone NOT NULL, - subscription_id character(26) NOT NULL -); - - -ALTER TABLE public.subscription_phases OWNER TO pgtdbuser; - --- --- Name: subscriptions; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.subscriptions ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - active_from timestamp with time zone NOT NULL, - active_to timestamp with time zone, - currency character varying NOT NULL, - customer_id character(26) NOT NULL, - name character varying DEFAULT 'Subscription'::character varying NOT NULL, - description character varying, - plan_id character(26), - billables_must_align boolean DEFAULT false NOT NULL -); - - -ALTER TABLE public.subscriptions OWNER TO pgtdbuser; - --- --- Name: usage_resets; Type: TABLE; Schema: public; Owner: pgtdbuser --- - -CREATE TABLE public.usage_resets ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - reset_time timestamp with time zone NOT NULL, - entitlement_id character(26) NOT NULL, - anchor timestamp with time zone NOT NULL -); - - -ALTER TABLE public.usage_resets OWNER TO pgtdbuser; - --- --- Name: addon_rate_cards addon_rate_cards_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_pkey PRIMARY KEY (id); - - --- --- Name: addons addons_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.addons - ADD CONSTRAINT addons_pkey PRIMARY KEY (id); - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_custom_invoicings app_custom_invoicings_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_custom_invoicings - ADD CONSTRAINT app_custom_invoicings_pkey PRIMARY KEY (id); - - --- --- Name: app_customers app_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_stripe_customers app_stripe_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_stripes app_stripes_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_stripes - ADD CONSTRAINT app_stripes_pkey PRIMARY KEY (id); - - --- --- Name: apps apps_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.apps - ADD CONSTRAINT apps_pkey PRIMARY KEY (id); - - --- --- Name: balance_snapshots balance_snapshots_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.balance_snapshots - ADD CONSTRAINT balance_snapshots_pkey PRIMARY KEY (id); - - --- --- Name: billing_customer_locks billing_customer_locks_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_customer_locks - ADD CONSTRAINT billing_customer_locks_pkey PRIMARY KEY (id); - - --- --- Name: billing_customer_overrides billing_customer_overrides_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_flat_fee_line_configs billing_invoice_flat_fee_line_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_flat_fee_line_configs - ADD CONSTRAINT billing_invoice_flat_fee_line_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_line_discounts billing_invoice_line_discounts_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_line_discounts - ADD CONSTRAINT billing_invoice_line_discounts_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_line_usage_discounts billing_invoice_line_usage_discounts_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_line_usage_discounts - ADD CONSTRAINT billing_invoice_line_usage_discounts_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_lines billing_invoice_lines_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_usage_based_line_configs billing_invoice_usage_based_line_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_usage_based_line_configs - ADD CONSTRAINT billing_invoice_usage_based_line_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_validation_issues billing_invoice_validation_issues_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_validation_issues - ADD CONSTRAINT billing_invoice_validation_issues_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoices billing_invoices_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_pkey PRIMARY KEY (id); - - --- --- Name: billing_profiles billing_profiles_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_pkey PRIMARY KEY (id); - - --- --- Name: billing_sequence_numbers billing_sequence_numbers_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_sequence_numbers - ADD CONSTRAINT billing_sequence_numbers_pkey PRIMARY KEY (id); - - --- --- Name: billing_workflow_configs billing_workflow_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_workflow_configs - ADD CONSTRAINT billing_workflow_configs_pkey PRIMARY KEY (id); - - --- --- Name: customer_subjects customer_subjects_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.customer_subjects - ADD CONSTRAINT customer_subjects_pkey PRIMARY KEY (id); - - --- --- Name: customers customers_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.customers - ADD CONSTRAINT customers_pkey PRIMARY KEY (id); - - --- --- Name: entitlements entitlements_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.entitlements - ADD CONSTRAINT entitlements_pkey PRIMARY KEY (id); - - --- --- Name: features features_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.features - ADD CONSTRAINT features_pkey PRIMARY KEY (id); - - --- --- Name: grants grants_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.grants - ADD CONSTRAINT grants_pkey PRIMARY KEY (id); - - --- --- Name: meters meters_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.meters - ADD CONSTRAINT meters_pkey PRIMARY KEY (id); - - --- --- Name: notification_channel_rules notification_channel_rules_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_pkey PRIMARY KEY (notification_channel_id, notification_rule_id); - - --- --- Name: notification_channels notification_channels_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_channels - ADD CONSTRAINT notification_channels_pkey PRIMARY KEY (id); - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_pkey PRIMARY KEY (notification_event_delivery_status_id, notification_event_id); - - --- --- Name: notification_event_delivery_status notification_event_delivery_status_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_event_delivery_status - ADD CONSTRAINT notification_event_delivery_status_pkey PRIMARY KEY (id); - - --- --- Name: notification_events notification_events_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_events - ADD CONSTRAINT notification_events_pkey PRIMARY KEY (id); - - --- --- Name: notification_rules notification_rules_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_rules - ADD CONSTRAINT notification_rules_pkey PRIMARY KEY (id); - - --- --- Name: plan_addons plan_addons_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_pkey PRIMARY KEY (id); - - --- --- Name: plan_phases plan_phases_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plan_phases - ADD CONSTRAINT plan_phases_pkey PRIMARY KEY (id); - - --- --- Name: plan_rate_cards plan_rate_cards_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_pkey PRIMARY KEY (id); - - --- --- Name: plans plans_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plans - ADD CONSTRAINT plans_pkey PRIMARY KEY (id); - - --- --- Name: schema_om schema_om_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.schema_om - ADD CONSTRAINT schema_om_pkey PRIMARY KEY (version); - - --- --- Name: subscription_addon_quantities subscription_addon_quantities_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_addon_quantities - ADD CONSTRAINT subscription_addon_quantities_pkey PRIMARY KEY (id); - - --- --- Name: subscription_addons subscription_addons_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_pkey PRIMARY KEY (id); - - --- --- Name: subscription_items subscription_items_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_pkey PRIMARY KEY (id); - - --- --- Name: subscription_phases subscription_phases_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_phases - ADD CONSTRAINT subscription_phases_pkey PRIMARY KEY (id); - - --- --- Name: subscriptions subscriptions_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_pkey PRIMARY KEY (id); - - --- --- Name: usage_resets usage_resets_pkey; Type: CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.usage_resets - ADD CONSTRAINT usage_resets_pkey PRIMARY KEY (id); - - --- --- Name: addon_annotations; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX addon_annotations ON public.addons USING gin (annotations); - - --- --- Name: addon_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addon_id ON public.addons USING btree (id); - - --- --- Name: addon_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX addon_namespace ON public.addons USING btree (namespace); - - --- --- Name: addon_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addon_namespace_id ON public.addons USING btree (namespace, id); - - --- --- Name: addon_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addon_namespace_key_deleted_at ON public.addons USING btree (namespace, key, deleted_at); - - --- --- Name: addon_namespace_key_version; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addon_namespace_key_version ON public.addons USING btree (namespace, key, version) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_addon_id_feature_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addonratecard_addon_id_feature_key ON public.addon_rate_cards USING btree (addon_id, feature_key) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_addon_id_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addonratecard_addon_id_key ON public.addon_rate_cards USING btree (addon_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addonratecard_id ON public.addon_rate_cards USING btree (id); - - --- --- Name: addonratecard_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX addonratecard_namespace ON public.addon_rate_cards USING btree (namespace); - - --- --- Name: addonratecard_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addonratecard_namespace_id ON public.addon_rate_cards USING btree (namespace, id); - - --- --- Name: addonratecard_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX addonratecard_namespace_key_deleted_at ON public.addon_rate_cards USING btree (namespace, key, deleted_at); - - --- --- Name: app_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX app_id ON public.apps USING btree (id); - - --- --- Name: app_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX app_namespace ON public.apps USING btree (namespace); - - --- --- Name: app_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX app_namespace_id ON public.apps USING btree (namespace, id); - - --- --- Name: app_namespace_type; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX app_namespace_type ON public.apps USING btree (namespace, type); - - --- --- Name: app_namespace_type_is_default; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX app_namespace_type_is_default ON public.apps USING btree (namespace, type, is_default) WHERE ((is_default = true) AND (deleted_at IS NULL)); - - --- --- Name: appcustomer_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX appcustomer_namespace ON public.app_customers USING btree (namespace); - - --- --- Name: appcustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX appcustomer_namespace_app_id_customer_id ON public.app_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: appcustominvoicing_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX appcustominvoicing_id ON public.app_custom_invoicings USING btree (id); - - --- --- Name: appcustominvoicing_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX appcustominvoicing_namespace ON public.app_custom_invoicings USING btree (namespace); - - --- --- Name: appcustominvoicing_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX appcustominvoicing_namespace_id ON public.app_custom_invoicings USING btree (namespace, id); - - --- --- Name: appcustominvoicingcustomer_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX appcustominvoicingcustomer_namespace ON public.app_custom_invoicing_customers USING btree (namespace); - - --- --- Name: appcustominvoicingcustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX appcustominvoicingcustomer_namespace_app_id_customer_id ON public.app_custom_invoicing_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: appstripe_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX appstripe_id ON public.app_stripes USING btree (id); - - --- --- Name: appstripe_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX appstripe_namespace ON public.app_stripes USING btree (namespace); - - --- --- Name: appstripe_namespace_stripe_account_id_stripe_livemode; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX appstripe_namespace_stripe_account_id_stripe_livemode ON public.app_stripes USING btree (namespace, stripe_account_id, stripe_livemode) WHERE (deleted_at IS NULL); - - --- --- Name: appstripecustomer_app_id_stripe_customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX appstripecustomer_app_id_stripe_customer_id ON public.app_stripe_customers USING btree (app_id, stripe_customer_id); - - --- --- Name: appstripecustomer_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX appstripecustomer_namespace ON public.app_stripe_customers USING btree (namespace); - - --- --- Name: appstripecustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX appstripecustomer_namespace_app_id_customer_id ON public.app_stripe_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: balancesnapshot_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX balancesnapshot_namespace ON public.balance_snapshots USING btree (namespace); - - --- --- Name: balancesnapshot_namespace_owner_id_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX balancesnapshot_namespace_owner_id_at ON public.balance_snapshots USING btree (namespace, owner_id, at) WHERE (deleted_at IS NULL); - - --- --- Name: billing_customer_overrides_customer_id_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billing_customer_overrides_customer_id_key ON public.billing_customer_overrides USING btree (customer_id); - - --- --- Name: billing_invoices_workflow_config_id_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billing_invoices_workflow_config_id_key ON public.billing_invoices USING btree (workflow_config_id); - - --- --- Name: billing_profiles_workflow_config_id_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billing_profiles_workflow_config_id_key ON public.billing_profiles USING btree (workflow_config_id); - - --- --- Name: billingcustomerlock_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingcustomerlock_id ON public.billing_customer_locks USING btree (id); - - --- --- Name: billingcustomerlock_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billingcustomerlock_namespace ON public.billing_customer_locks USING btree (namespace); - - --- --- Name: billingcustomerlock_namespace_customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingcustomerlock_namespace_customer_id ON public.billing_customer_locks USING btree (namespace, customer_id); - - --- --- Name: billingcustomeroverride_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingcustomeroverride_id ON public.billing_customer_overrides USING btree (id); - - --- --- Name: billingcustomeroverride_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billingcustomeroverride_namespace ON public.billing_customer_overrides USING btree (namespace); - - --- --- Name: billingcustomeroverride_namespace_customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingcustomeroverride_namespace_customer_id ON public.billing_customer_overrides USING btree (namespace, customer_id); - - --- --- Name: billingcustomeroverride_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingcustomeroverride_namespace_id ON public.billing_customer_overrides USING btree (namespace, id); - - --- --- Name: billinginvoice_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoice_id ON public.billing_invoices USING btree (id); - - --- --- Name: billinginvoice_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoice_namespace ON public.billing_invoices USING btree (namespace); - - --- --- Name: billinginvoice_namespace_customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoice_namespace_customer_id ON public.billing_invoices USING btree (namespace, customer_id); - - --- --- Name: billinginvoice_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoice_namespace_id ON public.billing_invoices USING btree (namespace, id); - - --- --- Name: billinginvoice_namespace_status; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoice_namespace_status ON public.billing_invoices USING btree (namespace, status); - - --- --- Name: billinginvoice_status_details_cache; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoice_status_details_cache ON public.billing_invoices USING gin (status_details_cache); - - --- --- Name: billinginvoiceflatfeelineconfig_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoiceflatfeelineconfig_id ON public.billing_invoice_flat_fee_line_configs USING btree (id); - - --- --- Name: billinginvoiceflatfeelineconfig_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoiceflatfeelineconfig_namespace ON public.billing_invoice_flat_fee_line_configs USING btree (namespace); - - --- --- Name: billinginvoiceline_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoiceline_id ON public.billing_invoice_lines USING btree (id); - - --- --- Name: billinginvoiceline_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoiceline_namespace ON public.billing_invoice_lines USING btree (namespace); - - --- --- Name: billinginvoiceline_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoiceline_namespace_id ON public.billing_invoice_lines USING btree (namespace, id); - - --- --- Name: billinginvoiceline_namespace_invoice_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoiceline_namespace_invoice_id ON public.billing_invoice_lines USING btree (namespace, invoice_id); - - --- --- Name: billinginvoiceline_namespace_parent_line_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoiceline_namespace_parent_line_id ON public.billing_invoice_lines USING btree (namespace, parent_line_id); - - --- --- Name: billinginvoiceline_namespace_parent_line_id_child_unique_refere; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoiceline_namespace_parent_line_id_child_unique_refere ON public.billing_invoice_lines USING btree (namespace, parent_line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoiceline_namespace_subscription_id_subscription_phase; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoiceline_namespace_subscription_id_subscription_phase ON public.billing_invoice_lines USING btree (namespace, subscription_id, subscription_phase_id, subscription_item_id); - - --- --- Name: billinginvoicelinediscount_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoicelinediscount_id ON public.billing_invoice_line_discounts USING btree (id); - - --- --- Name: billinginvoicelinediscount_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoicelinediscount_namespace ON public.billing_invoice_line_discounts USING btree (namespace); - - --- --- Name: billinginvoicelinediscount_namespace_line_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoicelinediscount_namespace_line_id ON public.billing_invoice_line_discounts USING btree (namespace, line_id); - - --- --- Name: billinginvoicelinediscount_namespace_line_id_child_unique_refer; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoicelinediscount_namespace_line_id_child_unique_refer ON public.billing_invoice_line_discounts USING btree (namespace, line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoicelineusagediscount_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoicelineusagediscount_id ON public.billing_invoice_line_usage_discounts USING btree (id); - - --- --- Name: billinginvoicelineusagediscount_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoicelineusagediscount_namespace ON public.billing_invoice_line_usage_discounts USING btree (namespace); - - --- --- Name: billinginvoicelineusagediscount_namespace_line_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoicelineusagediscount_namespace_line_id ON public.billing_invoice_line_usage_discounts USING btree (namespace, line_id); - - --- --- Name: billinginvoicelineusagediscount_namespace_line_id_child_unique_; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoicelineusagediscount_namespace_line_id_child_unique_ ON public.billing_invoice_line_usage_discounts USING btree (namespace, line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoiceusagebasedlineconfig_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoiceusagebasedlineconfig_id ON public.billing_invoice_usage_based_line_configs USING btree (id); - - --- --- Name: billinginvoiceusagebasedlineconfig_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoiceusagebasedlineconfig_namespace ON public.billing_invoice_usage_based_line_configs USING btree (namespace); - - --- --- Name: billinginvoicevalidationissue_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoicevalidationissue_id ON public.billing_invoice_validation_issues USING btree (id); - - --- --- Name: billinginvoicevalidationissue_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billinginvoicevalidationissue_namespace ON public.billing_invoice_validation_issues USING btree (namespace); - - --- --- Name: billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash ON public.billing_invoice_validation_issues USING btree (namespace, invoice_id, dedupe_hash); - - --- --- Name: billingprofile_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingprofile_id ON public.billing_profiles USING btree (id); - - --- --- Name: billingprofile_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billingprofile_namespace ON public.billing_profiles USING btree (namespace); - - --- --- Name: billingprofile_namespace_default; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingprofile_namespace_default ON public.billing_profiles USING btree (namespace, "default") WHERE ("default" AND (deleted_at IS NULL)); - - --- --- Name: billingprofile_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingprofile_namespace_id ON public.billing_profiles USING btree (namespace, id); - - --- --- Name: billingsequencenumbers_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billingsequencenumbers_namespace ON public.billing_sequence_numbers USING btree (namespace); - - --- --- Name: billingsequencenumbers_namespace_scope; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingsequencenumbers_namespace_scope ON public.billing_sequence_numbers USING btree (namespace, scope); - - --- --- Name: billingworkflowconfig_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX billingworkflowconfig_id ON public.billing_workflow_configs USING btree (id); - - --- --- Name: billingworkflowconfig_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billingworkflowconfig_namespace ON public.billing_workflow_configs USING btree (namespace); - - --- --- Name: billingworkflowconfig_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX billingworkflowconfig_namespace_id ON public.billing_workflow_configs USING btree (namespace, id); - - --- --- Name: customer_created_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX customer_created_at ON public.customers USING btree (created_at); - - --- --- Name: customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX customer_id ON public.customers USING btree (id); - - --- --- Name: customer_name; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX customer_name ON public.customers USING btree (name); - - --- --- Name: customer_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX customer_namespace ON public.customers USING btree (namespace); - - --- --- Name: customer_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX customer_namespace_id ON public.customers USING btree (namespace, id); - - --- --- Name: customer_namespace_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX customer_namespace_key ON public.customers USING btree (namespace, key) WHERE (deleted_at IS NULL); - - --- --- Name: customer_primary_email; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX customer_primary_email ON public.customers USING btree (primary_email); - - --- --- Name: customersubjects_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX customersubjects_namespace ON public.customer_subjects USING btree (namespace); - - --- --- Name: customersubjects_namespace_customer_id_deleted_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX customersubjects_namespace_customer_id_deleted_at ON public.customer_subjects USING btree (namespace, customer_id, deleted_at); - - --- --- Name: customersubjects_namespace_subject_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX customersubjects_namespace_subject_key ON public.customer_subjects USING btree (namespace, subject_key) WHERE (deleted_at IS NULL); - - --- --- Name: entitlement_created_at_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX entitlement_created_at_id ON public.entitlements USING btree (created_at, id); - - --- --- Name: entitlement_current_usage_period_end_deleted_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX entitlement_current_usage_period_end_deleted_at ON public.entitlements USING btree (current_usage_period_end, deleted_at); - - --- --- Name: entitlement_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX entitlement_id ON public.entitlements USING btree (id); - - --- --- Name: entitlement_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX entitlement_namespace ON public.entitlements USING btree (namespace); - - --- --- Name: entitlement_namespace_current_usage_period_end; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX entitlement_namespace_current_usage_period_end ON public.entitlements USING btree (namespace, current_usage_period_end); - - --- --- Name: entitlement_namespace_feature_id_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX entitlement_namespace_feature_id_id ON public.entitlements USING btree (namespace, feature_id, id); - - --- --- Name: entitlement_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX entitlement_namespace_id ON public.entitlements USING btree (namespace, id); - - --- --- Name: entitlement_namespace_id_subject_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX entitlement_namespace_id_subject_key ON public.entitlements USING btree (namespace, id, subject_key); - - --- --- Name: entitlement_namespace_subject_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX entitlement_namespace_subject_key ON public.entitlements USING btree (namespace, subject_key); - - --- --- Name: feature_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX feature_id ON public.features USING btree (id); - - --- --- Name: feature_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX feature_namespace_id ON public.features USING btree (namespace, id); - - --- --- Name: feature_namespace_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX feature_namespace_key ON public.features USING btree (namespace, key) WHERE (archived_at IS NULL); - - --- --- Name: grant_effective_at_expires_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX grant_effective_at_expires_at ON public.grants USING btree (effective_at, expires_at); - - --- --- Name: grant_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX grant_id ON public.grants USING btree (id); - - --- --- Name: grant_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX grant_namespace ON public.grants USING btree (namespace); - - --- --- Name: grant_namespace_owner_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX grant_namespace_owner_id ON public.grants USING btree (namespace, owner_id); - - --- --- Name: meter_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX meter_id ON public.meters USING btree (id); - - --- --- Name: meter_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX meter_namespace ON public.meters USING btree (namespace); - - --- --- Name: meter_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX meter_namespace_id ON public.meters USING btree (namespace, id); - - --- --- Name: meter_namespace_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX meter_namespace_key ON public.meters USING btree (namespace, key) WHERE (deleted_at IS NULL); - - --- --- Name: meter_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX meter_namespace_key_deleted_at ON public.meters USING btree (namespace, key, deleted_at); - - --- --- Name: notificationchannel_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX notificationchannel_id ON public.notification_channels USING btree (id); - - --- --- Name: notificationchannel_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationchannel_namespace ON public.notification_channels USING btree (namespace); - - --- --- Name: notificationchannel_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationchannel_namespace_id ON public.notification_channels USING btree (namespace, id); - - --- --- Name: notificationchannel_namespace_type; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationchannel_namespace_type ON public.notification_channels USING btree (namespace, type); - - --- --- Name: notificationevent_annotations; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationevent_annotations ON public.notification_events USING gin (annotations); - - --- --- Name: notificationevent_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX notificationevent_id ON public.notification_events USING btree (id); - - --- --- Name: notificationevent_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationevent_namespace ON public.notification_events USING btree (namespace); - - --- --- Name: notificationevent_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationevent_namespace_id ON public.notification_events USING btree (namespace, id); - - --- --- Name: notificationevent_namespace_type; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationevent_namespace_type ON public.notification_events USING btree (namespace, type); - - --- --- Name: notificationeventdeliverystatus_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX notificationeventdeliverystatus_id ON public.notification_event_delivery_status USING btree (id); - - --- --- Name: notificationeventdeliverystatus_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationeventdeliverystatus_namespace ON public.notification_event_delivery_status USING btree (namespace); - - --- --- Name: notificationeventdeliverystatus_namespace_event_id_channel_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationeventdeliverystatus_namespace_event_id_channel_id ON public.notification_event_delivery_status USING btree (namespace, event_id, channel_id); - - --- --- Name: notificationeventdeliverystatus_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationeventdeliverystatus_namespace_id ON public.notification_event_delivery_status USING btree (namespace, id); - - --- --- Name: notificationeventdeliverystatus_namespace_state; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationeventdeliverystatus_namespace_state ON public.notification_event_delivery_status USING btree (namespace, state); - - --- --- Name: notificationrule_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX notificationrule_id ON public.notification_rules USING btree (id); - - --- --- Name: notificationrule_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationrule_namespace ON public.notification_rules USING btree (namespace); - - --- --- Name: notificationrule_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationrule_namespace_id ON public.notification_rules USING btree (namespace, id); - - --- --- Name: notificationrule_namespace_type; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX notificationrule_namespace_type ON public.notification_rules USING btree (namespace, type); - - --- --- Name: plan_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX plan_id ON public.plans USING btree (id); - - --- --- Name: plan_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX plan_namespace ON public.plans USING btree (namespace); - - --- --- Name: plan_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX plan_namespace_id ON public.plans USING btree (namespace, id); - - --- --- Name: plan_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX plan_namespace_key_deleted_at ON public.plans USING btree (namespace, key, deleted_at); - - --- --- Name: plan_namespace_key_version; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX plan_namespace_key_version ON public.plans USING btree (namespace, key, version) WHERE (deleted_at IS NULL); - - --- --- Name: planaddon_annotations; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX planaddon_annotations ON public.plan_addons USING gin (annotations); - - --- --- Name: planaddon_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planaddon_id ON public.plan_addons USING btree (id); - - --- --- Name: planaddon_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX planaddon_namespace ON public.plan_addons USING btree (namespace); - - --- --- Name: planaddon_namespace_plan_id_addon_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planaddon_namespace_plan_id_addon_id ON public.plan_addons USING btree (namespace, plan_id, addon_id) WHERE (deleted_at IS NULL); - - --- --- Name: planphase_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planphase_id ON public.plan_phases USING btree (id); - - --- --- Name: planphase_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX planphase_namespace ON public.plan_phases USING btree (namespace); - - --- --- Name: planphase_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planphase_namespace_id ON public.plan_phases USING btree (namespace, id); - - --- --- Name: planphase_namespace_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX planphase_namespace_key ON public.plan_phases USING btree (namespace, key); - - --- --- Name: planphase_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planphase_namespace_key_deleted_at ON public.plan_phases USING btree (namespace, key, deleted_at); - - --- --- Name: planphase_plan_id_index; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planphase_plan_id_index ON public.plan_phases USING btree (plan_id, index) WHERE (deleted_at IS NULL); - - --- --- Name: planphase_plan_id_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planphase_plan_id_key ON public.plan_phases USING btree (plan_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: planratecard_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planratecard_id ON public.plan_rate_cards USING btree (id); - - --- --- Name: planratecard_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX planratecard_namespace ON public.plan_rate_cards USING btree (namespace); - - --- --- Name: planratecard_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planratecard_namespace_id ON public.plan_rate_cards USING btree (namespace, id); - - --- --- Name: planratecard_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planratecard_namespace_key_deleted_at ON public.plan_rate_cards USING btree (namespace, key, deleted_at); - - --- --- Name: planratecard_phase_id_feature_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planratecard_phase_id_feature_key ON public.plan_rate_cards USING btree (phase_id, feature_key) WHERE (deleted_at IS NULL); - - --- --- Name: planratecard_phase_id_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX planratecard_phase_id_key ON public.plan_rate_cards USING btree (phase_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: subscription_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX subscription_id ON public.subscriptions USING btree (id); - - --- --- Name: subscription_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscription_namespace ON public.subscriptions USING btree (namespace); - - --- --- Name: subscription_namespace_customer_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscription_namespace_customer_id ON public.subscriptions USING btree (namespace, customer_id); - - --- --- Name: subscription_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscription_namespace_id ON public.subscriptions USING btree (namespace, id); - - --- --- Name: subscriptionaddon_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX subscriptionaddon_id ON public.subscription_addons USING btree (id); - - --- --- Name: subscriptionaddon_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionaddon_namespace ON public.subscription_addons USING btree (namespace); - - --- --- Name: subscriptionaddonquantity_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX subscriptionaddonquantity_id ON public.subscription_addon_quantities USING btree (id); - - --- --- Name: subscriptionaddonquantity_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionaddonquantity_namespace ON public.subscription_addon_quantities USING btree (namespace); - - --- --- Name: subscriptionaddonquantity_subscription_addon_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionaddonquantity_subscription_addon_id ON public.subscription_addon_quantities USING btree (subscription_addon_id); - - --- --- Name: subscriptionitem_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX subscriptionitem_id ON public.subscription_items USING btree (id); - - --- --- Name: subscriptionitem_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionitem_namespace ON public.subscription_items USING btree (namespace); - - --- --- Name: subscriptionitem_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionitem_namespace_id ON public.subscription_items USING btree (namespace, id); - - --- --- Name: subscriptionitem_namespace_phase_id_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionitem_namespace_phase_id_key ON public.subscription_items USING btree (namespace, phase_id, key); - - --- --- Name: subscriptionphase_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX subscriptionphase_id ON public.subscription_phases USING btree (id); - - --- --- Name: subscriptionphase_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionphase_namespace ON public.subscription_phases USING btree (namespace); - - --- --- Name: subscriptionphase_namespace_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionphase_namespace_id ON public.subscription_phases USING btree (namespace, id); - - --- --- Name: subscriptionphase_namespace_subscription_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionphase_namespace_subscription_id ON public.subscription_phases USING btree (namespace, subscription_id); - - --- --- Name: subscriptionphase_namespace_subscription_id_key; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX subscriptionphase_namespace_subscription_id_key ON public.subscription_phases USING btree (namespace, subscription_id, key); - - --- --- Name: usagereset_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE UNIQUE INDEX usagereset_id ON public.usage_resets USING btree (id); - - --- --- Name: usagereset_namespace; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX usagereset_namespace ON public.usage_resets USING btree (namespace); - - --- --- Name: usagereset_namespace_entitlement_id; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX usagereset_namespace_entitlement_id ON public.usage_resets USING btree (namespace, entitlement_id); - - --- --- Name: usagereset_namespace_entitlement_id_reset_time; Type: INDEX; Schema: public; Owner: pgtdbuser --- - -CREATE INDEX usagereset_namespace_entitlement_id_reset_time ON public.usage_resets USING btree (namespace, entitlement_id, reset_time); - - --- --- Name: addon_rate_cards addon_rate_cards_addons_ratecards; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_addons_ratecards FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: addon_rate_cards addon_rate_cards_features_addon_ratecard; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_features_addon_ratecard FOREIGN KEY (feature_id) REFERENCES public.features(id) ON DELETE SET NULL; - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_app_custom_invoicings_customer_a; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_app_custom_invoicings_customer_a FOREIGN KEY (app_id) REFERENCES public.app_custom_invoicings(id) ON DELETE CASCADE; - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_customers_customer; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_customers_customer FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_custom_invoicings app_custom_invoicings_apps_app; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_custom_invoicings - ADD CONSTRAINT app_custom_invoicings_apps_app FOREIGN KEY (id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: app_customers app_customers_apps_customer_apps; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_apps_customer_apps FOREIGN KEY (app_id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: app_customers app_customers_customers_apps; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_customers_apps FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_stripe_customers app_stripe_customers_app_stripes_customer_apps; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_app_stripes_customer_apps FOREIGN KEY (app_id) REFERENCES public.app_stripes(id) ON DELETE CASCADE; - - --- --- Name: app_stripe_customers app_stripe_customers_customers_customer; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_customers_customer FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_stripes app_stripes_apps_app; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.app_stripes - ADD CONSTRAINT app_stripes_apps_app FOREIGN KEY (id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: balance_snapshots balance_snapshots_entitlements_balance_snapshot; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.balance_snapshots - ADD CONSTRAINT balance_snapshots_entitlements_balance_snapshot FOREIGN KEY (owner_id) REFERENCES public.entitlements(id); - - --- --- Name: billing_customer_overrides billing_customer_overrides_billing_profiles_billing_customer_ov; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_billing_profiles_billing_customer_ov FOREIGN KEY (billing_profile_id) REFERENCES public.billing_profiles(id) ON DELETE SET NULL; - - --- --- Name: billing_customer_overrides billing_customer_overrides_customers_billing_customer_override; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_customers_billing_customer_override FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_line_discounts billing_invoice_line_discounts_billing_invoice_lines_line_amoun; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_line_discounts - ADD CONSTRAINT billing_invoice_line_discounts_billing_invoice_lines_line_amoun FOREIGN KEY (line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_line_usage_discounts billing_invoice_line_usage_discounts_billing_invoice_lines_line; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_line_usage_discounts - ADD CONSTRAINT billing_invoice_line_usage_discounts_billing_invoice_lines_line FOREIGN KEY (line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_flat_fee_line_configs_fla; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_flat_fee_line_configs_fla FOREIGN KEY (fee_line_config_id) REFERENCES public.billing_invoice_flat_fee_line_configs(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_lines_detailed_lines; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_lines_detailed_lines FOREIGN KEY (parent_line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_usage_based_line_configs_; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_usage_based_line_configs_ FOREIGN KEY (usage_based_line_config_id) REFERENCES public.billing_invoice_usage_based_line_configs(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoices_billing_invoice_lines; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoices_billing_invoice_lines FOREIGN KEY (invoice_id) REFERENCES public.billing_invoices(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscription_items_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscription_items_billing_lines FOREIGN KEY (subscription_item_id) REFERENCES public.subscription_items(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscription_phases_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscription_phases_billing_lines FOREIGN KEY (subscription_phase_id) REFERENCES public.subscription_phases(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscriptions_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscriptions_billing_lines FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_validation_issues billing_invoice_validation_issues_billing_invoices_billing_invo; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoice_validation_issues - ADD CONSTRAINT billing_invoice_validation_issues_billing_invoices_billing_invo FOREIGN KEY (invoice_id) REFERENCES public.billing_invoices(id) ON DELETE CASCADE; - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_invoicing_app; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_invoicing_app FOREIGN KEY (invoicing_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_payment_app; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_payment_app FOREIGN KEY (payment_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_tax_app; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_tax_app FOREIGN KEY (tax_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_billing_profiles_billing_invoices; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_billing_profiles_billing_invoices FOREIGN KEY (source_billing_profile_id) REFERENCES public.billing_profiles(id); - - --- --- Name: billing_invoices billing_invoices_billing_workflow_configs_billing_invoices; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_billing_workflow_configs_billing_invoices FOREIGN KEY (workflow_config_id) REFERENCES public.billing_workflow_configs(id); - - --- --- Name: billing_invoices billing_invoices_customers_billing_invoice; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_customers_billing_invoice FOREIGN KEY (customer_id) REFERENCES public.customers(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_invoicing_app; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_invoicing_app FOREIGN KEY (invoicing_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_payment_app; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_payment_app FOREIGN KEY (payment_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_tax_app; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_tax_app FOREIGN KEY (tax_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_billing_workflow_configs_billing_profile; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_billing_workflow_configs_billing_profile FOREIGN KEY (workflow_config_id) REFERENCES public.billing_workflow_configs(id); - - --- --- Name: customer_subjects customer_subjects_customers_subjects; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.customer_subjects - ADD CONSTRAINT customer_subjects_customers_subjects FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: entitlements entitlements_features_entitlement; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.entitlements - ADD CONSTRAINT entitlements_features_entitlement FOREIGN KEY (feature_id) REFERENCES public.features(id); - - --- --- Name: grants grants_entitlements_grant; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.grants - ADD CONSTRAINT grants_entitlements_grant FOREIGN KEY (owner_id) REFERENCES public.entitlements(id); - - --- --- Name: notification_channel_rules notification_channel_rules_notification_channel_id; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_notification_channel_id FOREIGN KEY (notification_channel_id) REFERENCES public.notification_channels(id) ON DELETE CASCADE; - - --- --- Name: notification_channel_rules notification_channel_rules_notification_rule_id; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_notification_rule_id FOREIGN KEY (notification_rule_id) REFERENCES public.notification_rules(id) ON DELETE CASCADE; - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_notification_event_de; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_notification_event_de FOREIGN KEY (notification_event_delivery_status_id) REFERENCES public.notification_event_delivery_status(id) ON DELETE CASCADE; - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_notification_event_id; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_notification_event_id FOREIGN KEY (notification_event_id) REFERENCES public.notification_events(id) ON DELETE CASCADE; - - --- --- Name: notification_events notification_events_notification_rules_events; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.notification_events - ADD CONSTRAINT notification_events_notification_rules_events FOREIGN KEY (rule_id) REFERENCES public.notification_rules(id); - - --- --- Name: plan_addons plan_addons_addons_plans; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_addons_plans FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: plan_addons plan_addons_plans_addons; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_plans_addons FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE CASCADE; - - --- --- Name: plan_phases plan_phases_plans_phases; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plan_phases - ADD CONSTRAINT plan_phases_plans_phases FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE CASCADE; - - --- --- Name: plan_rate_cards plan_rate_cards_features_ratecard; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_features_ratecard FOREIGN KEY (feature_id) REFERENCES public.features(id) ON DELETE SET NULL; - - --- --- Name: plan_rate_cards plan_rate_cards_plan_phases_ratecards; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_plan_phases_ratecards FOREIGN KEY (phase_id) REFERENCES public.plan_phases(id) ON DELETE CASCADE; - - --- --- Name: subscription_addon_quantities subscription_addon_quantities_subscription_addons_quantities; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_addon_quantities - ADD CONSTRAINT subscription_addon_quantities_subscription_addons_quantities FOREIGN KEY (subscription_addon_id) REFERENCES public.subscription_addons(id) ON DELETE CASCADE; - - --- --- Name: subscription_addons subscription_addons_addons_subscription_addons; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_addons_subscription_addons FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: subscription_addons subscription_addons_subscriptions_addons; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_subscriptions_addons FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE CASCADE; - - --- --- Name: subscription_items subscription_items_entitlements_subscription_item; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_entitlements_subscription_item FOREIGN KEY (entitlement_id) REFERENCES public.entitlements(id) ON DELETE SET NULL; - - --- --- Name: subscription_items subscription_items_subscription_phases_items; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_subscription_phases_items FOREIGN KEY (phase_id) REFERENCES public.subscription_phases(id); - - --- --- Name: subscription_phases subscription_phases_subscriptions_phases; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscription_phases - ADD CONSTRAINT subscription_phases_subscriptions_phases FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id); - - --- --- Name: subscriptions subscriptions_customers_subscription; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_customers_subscription FOREIGN KEY (customer_id) REFERENCES public.customers(id); - - --- --- Name: subscriptions subscriptions_plans_subscriptions; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_plans_subscriptions FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE SET NULL; - - --- --- Name: usage_resets usage_resets_entitlements_usage_reset; Type: FK CONSTRAINT; Schema: public; Owner: pgtdbuser --- - -ALTER TABLE ONLY public.usage_resets - ADD CONSTRAINT usage_resets_entitlements_usage_reset FOREIGN KEY (entitlement_id) REFERENCES public.entitlements(id); - - --- --- Name: SCHEMA public; Type: ACL; Schema: -; Owner: postgres --- - -REVOKE USAGE ON SCHEMA public FROM PUBLIC; -GRANT ALL ON SCHEMA public TO PUBLIC; - - --- --- PostgreSQL database dump complete --- - diff --git a/tools/migrate/testdata/sqlcgen/20250605102416/sqlc/queries.sql b/tools/migrate/testdata/sqlcgen/20250605102416/sqlc/queries.sql deleted file mode 100644 index 755def4315..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250605102416/sqlc/queries.sql +++ /dev/null @@ -1,14 +0,0 @@ --- name: GetParentID :one -SELECT l.parent_line_id FROM public.billing_invoice_lines l WHERE l.id = sqlc.arg(line_id)::varchar; - --- name: GetFlatFeeLinesByParentID :many - -SELECT l.*, c.per_unit_amount, c.category, c.payment_term, c.index -FROM public.billing_invoice_lines l JOIN public.billing_invoice_flat_fee_line_configs c ON (l.fee_line_config_id = c.id) -WHERE type = 'flat_fee' AND status = 'detailed' AND l.parent_line_id = sqlc.arg(parent_line_id)::varchar; - --- name: GetUsageBasedLineByID :one - -SELECT l.*, c.price_type, c.feature_key, c.price, c.pre_line_period_quantity, c.metered_quantity, c.metered_pre_line_period_quantity -FROM public.billing_invoice_lines l JOIN public.billing_invoice_usage_based_line_configs c ON (l.usage_based_line_config_id = c.id) -WHERE type = 'usage_based' AND status = 'valid' AND l.id = sqlc.arg(line_id)::varchar; diff --git a/tools/migrate/testdata/sqlcgen/20250609172811/db/db.go b/tools/migrate/testdata/sqlcgen/20250609172811/db/db.go deleted file mode 100644 index 0c56c2b4e8..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250609172811/db/db.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 - -package db - -import ( - "context" - "database/sql" -) - -type DBTX interface { - ExecContext(context.Context, string, ...interface{}) (sql.Result, error) - PrepareContext(context.Context, string) (*sql.Stmt, error) - QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) - QueryRowContext(context.Context, string, ...interface{}) *sql.Row -} - -func New(db DBTX) *Queries { - return &Queries{db: db} -} - -type Queries struct { - db DBTX -} - -func (q *Queries) WithTx(tx *sql.Tx) *Queries { - return &Queries{ - db: tx, - } -} diff --git a/tools/migrate/testdata/sqlcgen/20250609172811/db/models.go b/tools/migrate/testdata/sqlcgen/20250609172811/db/models.go deleted file mode 100644 index 655070c8bc..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250609172811/db/models.go +++ /dev/null @@ -1,35 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 - -package db - -import ( - "database/sql" - "encoding/json" - "time" - - "github.com/sqlc-dev/pqtype" -) - -type BillingInvoiceSplitLineGroup struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - ServicePeriodStart time.Time - ServicePeriodEnd time.Time - Currency string - TaxConfig pqtype.NullRawMessage - UniqueReferenceID sql.NullString - RatecardDiscounts pqtype.NullRawMessage - FeatureKey sql.NullString - Price json.RawMessage - SubscriptionID sql.NullString - SubscriptionItemID sql.NullString - SubscriptionPhaseID sql.NullString -} diff --git a/tools/migrate/testdata/sqlcgen/20250609172811/db/queries.sql.go b/tools/migrate/testdata/sqlcgen/20250609172811/db/queries.sql.go deleted file mode 100644 index e22574fb2b..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250609172811/db/queries.sql.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 -// source: queries.sql - -package db - -import ( - "context" - "database/sql" - "encoding/json" - "time" - - "github.com/sqlc-dev/pqtype" -) - -const countLinesByStatusType = `-- name: CountLinesByStatusType :many -SELECT status, type, count(*) - FROM public.billing_invoice_lines - GROUP BY status, type -` - -type CountLinesByStatusTypeRow struct { - Status string - Type string - Count int64 -} - -func (q *Queries) CountLinesByStatusType(ctx context.Context) ([]CountLinesByStatusTypeRow, error) { - rows, err := q.db.QueryContext(ctx, countLinesByStatusType) - if err != nil { - return nil, err - } - defer rows.Close() - var items []CountLinesByStatusTypeRow - for rows.Next() { - var i CountLinesByStatusTypeRow - if err := rows.Scan(&i.Status, &i.Type, &i.Count); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Close(); err != nil { - return nil, err - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const getSplitLineGroup = `-- name: GetSplitLineGroup :one -SELECT id, namespace, metadata, created_at, updated_at, deleted_at, name, description, service_period_start, service_period_end, currency, tax_config, unique_reference_id, ratecard_discounts, feature_key, price, subscription_id, subscription_item_id, subscription_phase_id - FROM public.billing_invoice_split_line_groups - WHERE id = $1 -` - -func (q *Queries) GetSplitLineGroup(ctx context.Context, id string) (BillingInvoiceSplitLineGroup, error) { - row := q.db.QueryRowContext(ctx, getSplitLineGroup, id) - var i BillingInvoiceSplitLineGroup - err := row.Scan( - &i.ID, - &i.Namespace, - &i.Metadata, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.Name, - &i.Description, - &i.ServicePeriodStart, - &i.ServicePeriodEnd, - &i.Currency, - &i.TaxConfig, - &i.UniqueReferenceID, - &i.RatecardDiscounts, - &i.FeatureKey, - &i.Price, - &i.SubscriptionID, - &i.SubscriptionItemID, - &i.SubscriptionPhaseID, - ) - return i, err -} - -const getUsageBasedLinesBySplitLineGroup = `-- name: GetUsageBasedLinesBySplitLineGroup :many -SELECT l.id, l.namespace, l.metadata, l.created_at, l.updated_at, l.deleted_at, l.name, l.description, l.period_start, l.period_end, l.invoice_at, l.type, l.status, l.currency, l.quantity, l.tax_config, l.invoice_id, l.fee_line_config_id, l.usage_based_line_config_id, l.parent_line_id, l.child_unique_reference_id, l.amount, l.taxes_total, l.taxes_inclusive_total, l.taxes_exclusive_total, l.charges_total, l.discounts_total, l.total, l.invoicing_app_external_id, l.subscription_id, l.subscription_item_id, l.subscription_phase_id, l.line_ids, l.managed_by, l.ratecard_discounts, l.split_line_group_id, c.price, c.feature_key - FROM public.billing_invoice_lines l JOIN public.billing_invoice_usage_based_line_configs c ON (l.usage_based_line_config_id = c.id) - WHERE type = 'usage_based' AND status = 'valid' AND split_line_group_id = $1 -` - -type GetUsageBasedLinesBySplitLineGroupRow struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - PeriodStart time.Time - PeriodEnd time.Time - InvoiceAt time.Time - Type string - Status string - Currency string - Quantity sql.NullString - TaxConfig pqtype.NullRawMessage - InvoiceID string - FeeLineConfigID sql.NullString - UsageBasedLineConfigID sql.NullString - ParentLineID sql.NullString - ChildUniqueReferenceID sql.NullString - Amount string - TaxesTotal string - TaxesInclusiveTotal string - TaxesExclusiveTotal string - ChargesTotal string - DiscountsTotal string - Total string - InvoicingAppExternalID sql.NullString - SubscriptionID sql.NullString - SubscriptionItemID sql.NullString - SubscriptionPhaseID sql.NullString - LineIds sql.NullString - ManagedBy string - RatecardDiscounts pqtype.NullRawMessage - SplitLineGroupID sql.NullString - Price json.RawMessage - FeatureKey sql.NullString -} - -func (q *Queries) GetUsageBasedLinesBySplitLineGroup(ctx context.Context, splitLineGroupID sql.NullString) ([]GetUsageBasedLinesBySplitLineGroupRow, error) { - rows, err := q.db.QueryContext(ctx, getUsageBasedLinesBySplitLineGroup, splitLineGroupID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []GetUsageBasedLinesBySplitLineGroupRow - for rows.Next() { - var i GetUsageBasedLinesBySplitLineGroupRow - if err := rows.Scan( - &i.ID, - &i.Namespace, - &i.Metadata, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.Name, - &i.Description, - &i.PeriodStart, - &i.PeriodEnd, - &i.InvoiceAt, - &i.Type, - &i.Status, - &i.Currency, - &i.Quantity, - &i.TaxConfig, - &i.InvoiceID, - &i.FeeLineConfigID, - &i.UsageBasedLineConfigID, - &i.ParentLineID, - &i.ChildUniqueReferenceID, - &i.Amount, - &i.TaxesTotal, - &i.TaxesInclusiveTotal, - &i.TaxesExclusiveTotal, - &i.ChargesTotal, - &i.DiscountsTotal, - &i.Total, - &i.InvoicingAppExternalID, - &i.SubscriptionID, - &i.SubscriptionItemID, - &i.SubscriptionPhaseID, - &i.LineIds, - &i.ManagedBy, - &i.RatecardDiscounts, - &i.SplitLineGroupID, - &i.Price, - &i.FeatureKey, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Close(); err != nil { - return nil, err - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} diff --git a/tools/migrate/testdata/sqlcgen/20250609172811/fixture.sql b/tools/migrate/testdata/sqlcgen/20250609172811/fixture.sql deleted file mode 100644 index 64060826a7..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250609172811/fixture.sql +++ /dev/null @@ -1,360 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 14.17 --- Dumped by pg_dump version 15.13 (Homebrew) - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- Data for Name: addons; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: features; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.features (id, created_at, updated_at, deleted_at, metadata, namespace, name, key, meter_slug, meter_group_by_filters, archived_at) VALUES ('01JXA7Y5BEX8SBN22BT367VVZ4', '2025-06-09 11:41:44.174624+00', '2025-06-09 11:41:44.174624+00', NULL, 'null', 'ns-ubp-invoicing-progressive', 'flat-per-unit', 'flat-per-unit', 'flat-per-unit', NULL, NULL); - - --- --- Data for Name: addon_rate_cards; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: apps; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.apps (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, type, status, is_default) VALUES ('01JXA7Y5BBM0M8D504ZNQ6WX8X', 'ns-ubp-invoicing-progressive', NULL, '2025-06-09 11:41:44.171041+00', '2025-06-09 11:41:44.171042+00', NULL, 'Sandbox', 'Sandbox app', 'sandbox', 'ready', true); - - --- --- Data for Name: app_custom_invoicings; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: customers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.customers (id, namespace, metadata, created_at, updated_at, deleted_at, name, currency, primary_email, billing_address_country, billing_address_postal_code, billing_address_state, billing_address_city, billing_address_line1, billing_address_line2, billing_address_phone_number, description, key) VALUES ('01JXA7Y5BFE60CQ5EJZ1QYQQ5G', 'ns-ubp-invoicing-progressive', NULL, '2025-06-09 11:41:44.17593+00', '2025-06-09 11:41:44.17593+00', NULL, 'Test Customer', 'USD', 'test@test.com', 'US', '12345', NULL, NULL, NULL, NULL, NULL, NULL, NULL); - - --- --- Data for Name: app_custom_invoicing_customers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: app_customers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: app_stripes; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: app_stripe_customers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: entitlements; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: balance_snapshots; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_customer_locks; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_customer_locks (id, namespace, customer_id) VALUES ('01JXA7Y5BZH1DTFFFWR8GDPE23', 'ns-ubp-invoicing-progressive', '01JXA7Y5BFE60CQ5EJZ1QYQQ5G'); - - --- --- Data for Name: billing_workflow_configs; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_workflow_configs (id, namespace, created_at, updated_at, deleted_at, collection_alignment, invoice_auto_advance, invoice_collection_method, line_collection_period, invoice_draft_period, invoice_due_after, invoice_progressive_billing, invoice_default_tax_settings, tax_enabled, tax_enforced) VALUES ('01JXA7Y5BSZPMR8ZKM42H6HENZ', 'ns-ubp-invoicing-progressive', '2025-06-09 11:41:44.185068+00', '2025-06-09 11:41:44.185068+00', NULL, 'subscription', true, 'charge_automatically', 'P0D', 'P1D', 'P1W', true, NULL, true, false); -INSERT INTO public.billing_workflow_configs (id, namespace, created_at, updated_at, deleted_at, collection_alignment, invoice_auto_advance, invoice_collection_method, line_collection_period, invoice_draft_period, invoice_due_after, invoice_progressive_billing, invoice_default_tax_settings, tax_enabled, tax_enforced) VALUES ('01JXA7Y5CM63E7618SFEJPTQ3S', 'ns-ubp-invoicing-progressive', '2025-06-09 11:41:44.212724+00', '2024-09-02 13:13:14.067284+00', NULL, 'subscription', true, 'charge_automatically', 'P0D', 'P1D', 'P1W', true, NULL, true, false); -INSERT INTO public.billing_workflow_configs (id, namespace, created_at, updated_at, deleted_at, collection_alignment, invoice_auto_advance, invoice_collection_method, line_collection_period, invoice_draft_period, invoice_due_after, invoice_progressive_billing, invoice_default_tax_settings, tax_enabled, tax_enforced) VALUES ('01JXA7Y5DTY3GPA1VNMP84JBJB', 'ns-ubp-invoicing-progressive', '2024-09-02 13:13:14.010524+00', '2024-09-02 13:13:14.095593+00', NULL, 'subscription', true, 'charge_automatically', 'P0D', 'P1D', 'P1W', true, NULL, true, false); - - --- --- Data for Name: billing_profiles; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_profiles (id, namespace, created_at, updated_at, deleted_at, "default", workflow_config_id, metadata, supplier_address_country, supplier_address_postal_code, supplier_address_state, supplier_address_city, supplier_address_line1, supplier_address_line2, supplier_address_phone_number, supplier_name, name, description, supplier_tax_code, tax_app_id, invoicing_app_id, payment_app_id) VALUES ('01JXA7Y5BSZPMR8ZKM45C10E6T', 'ns-ubp-invoicing-progressive', '2025-06-09 11:41:44.185994+00', '2025-06-09 11:41:44.185995+00', NULL, true, '01JXA7Y5BSZPMR8ZKM42H6HENZ', 'null', 'US', NULL, NULL, NULL, NULL, NULL, NULL, 'Awesome Supplier', 'Awesome Profile', NULL, NULL, '01JXA7Y5BBM0M8D504ZNQ6WX8X', '01JXA7Y5BBM0M8D504ZNQ6WX8X', '01JXA7Y5BBM0M8D504ZNQ6WX8X'); - - --- --- Data for Name: billing_customer_overrides; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoice_flat_fee_line_configs; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_invoice_flat_fee_line_configs (id, namespace, per_unit_amount, category, payment_term, index) VALUES ('01JXA7Y5ESSNK0A1D77JHWBN61', 'ns-ubp-invoicing-progressive', 100, 'regular', 'in_arrears', 0); -INSERT INTO public.billing_invoice_flat_fee_line_configs (id, namespace, per_unit_amount, category, payment_term, index) VALUES ('01JXA7Y5FKC57VN3BGZK2VB5B2', 'ns-ubp-invoicing-progressive', 100, 'regular', 'in_arrears', 0); -INSERT INTO public.billing_invoice_flat_fee_line_configs (id, namespace, per_unit_amount, category, payment_term, index) VALUES ('01JXA7Y5GFYA1V39TS5HGXQEC6', 'ns-ubp-invoicing-progressive', 100, 'regular', 'in_arrears', 0); - - --- --- Data for Name: plans; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: subscriptions; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: subscription_phases; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: subscription_items; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoice_split_line_groups; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoice_usage_based_line_configs; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_invoice_usage_based_line_configs (id, namespace, price_type, feature_key, price, pre_line_period_quantity, metered_quantity, metered_pre_line_period_quantity) VALUES ('01JXA7Y5CQ74JPSBM8FZD65QM1', 'ns-ubp-invoicing-progressive', 'unit', 'flat-per-unit', '{"type": "unit", "amount": "100", "maximumAmount": "2000"}', NULL, NULL, NULL); -INSERT INTO public.billing_invoice_usage_based_line_configs (id, namespace, price_type, feature_key, price, pre_line_period_quantity, metered_quantity, metered_pre_line_period_quantity) VALUES ('01JXA7Y5CQ74JPSBM8G1JCA42B', 'ns-ubp-invoicing-progressive', 'flat', '', '{"type": "flat", "amount": "100", "paymentTerm": "in_arrears"}', NULL, NULL, NULL); -INSERT INTO public.billing_invoice_usage_based_line_configs (id, namespace, price_type, feature_key, price, pre_line_period_quantity, metered_quantity, metered_pre_line_period_quantity) VALUES ('01JXA7Y5E765KJ1F43EV0TV3YV', 'ns-ubp-invoicing-progressive', 'unit', 'flat-per-unit', '{"type": "unit", "amount": "100", "maximumAmount": "2000"}', NULL, NULL, NULL); -INSERT INTO public.billing_invoice_usage_based_line_configs (id, namespace, price_type, feature_key, price, pre_line_period_quantity, metered_quantity, metered_pre_line_period_quantity) VALUES ('01JXA7Y5E04HGZT2CHR62S0W72', 'ns-ubp-invoicing-progressive', 'unit', 'flat-per-unit', '{"type": "unit", "amount": "100", "maximumAmount": "2000"}', 0, 10, 0); - - --- --- Data for Name: billing_invoices; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_invoices (id, namespace, created_at, updated_at, deleted_at, metadata, customer_id, voided_at, currency, status, period_start, period_end, source_billing_profile_id, workflow_config_id, number, supplier_address_country, supplier_address_postal_code, supplier_address_state, supplier_address_city, supplier_address_line1, supplier_address_line2, supplier_address_phone_number, customer_address_country, customer_address_postal_code, customer_address_state, customer_address_city, customer_address_line1, customer_address_line2, customer_address_phone_number, supplier_name, supplier_tax_code, customer_name, type, description, issued_at, due_at, tax_app_id, invoicing_app_id, payment_app_id, draft_until, customer_usage_attribution, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, payment_app_external_id, collection_at, sent_to_customer_at, tax_app_external_id, status_details_cache, quantity_snapshoted_at) VALUES ('01JXA7Y5CN0DDF3J98X77PT09W', 'ns-ubp-invoicing-progressive', '2025-06-09 11:41:44.213161+00', '2024-09-02 13:13:14.064335+00', NULL, 'null', '01JXA7Y5BFE60CQ5EJZ1QYQQ5G', NULL, 'USD', 'gathering', '2024-09-02 12:13:14+00', '2024-09-03 12:13:14+00', '01JXA7Y5BSZPMR8ZKM45C10E6T', '01JXA7Y5CM63E7618SFEJPTQ3S', 'GATHER-TECU-USD-1', 'US', NULL, NULL, NULL, NULL, NULL, NULL, 'US', '12345', NULL, NULL, NULL, NULL, NULL, 'Awesome Supplier', NULL, 'Test Customer', 'standard', NULL, NULL, NULL, '01JXA7Y5BBM0M8D504ZNQ6WX8X', '01JXA7Y5BBM0M8D504ZNQ6WX8X', '01JXA7Y5BBM0M8D504ZNQ6WX8X', '2025-06-10 11:41:44.213161+00', '{"type": "customer_usage_attribution.v1", "subjectKeys": ["test"]}', 100, 0, 0, 0, 0, 0, 100, NULL, NULL, '2025-06-09 11:41:44.213161+00', NULL, NULL, NULL, NULL); -INSERT INTO public.billing_invoices (id, namespace, created_at, updated_at, deleted_at, metadata, customer_id, voided_at, currency, status, period_start, period_end, source_billing_profile_id, workflow_config_id, number, supplier_address_country, supplier_address_postal_code, supplier_address_state, supplier_address_city, supplier_address_line1, supplier_address_line2, supplier_address_phone_number, customer_address_country, customer_address_postal_code, customer_address_state, customer_address_city, customer_address_line1, customer_address_line2, customer_address_phone_number, supplier_name, supplier_tax_code, customer_name, type, description, issued_at, due_at, tax_app_id, invoicing_app_id, payment_app_id, draft_until, customer_usage_attribution, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, payment_app_external_id, collection_at, sent_to_customer_at, tax_app_external_id, status_details_cache, quantity_snapshoted_at) VALUES ('01JXA7Y5DTY3GPA1VNMPD649TK', 'ns-ubp-invoicing-progressive', '2024-09-02 13:13:14.010891+00', '2024-09-02 13:13:14.093814+00', NULL, 'null', '01JXA7Y5BFE60CQ5EJZ1QYQQ5G', NULL, 'USD', 'draft.waiting_auto_approval', '2024-09-02 12:13:00+00', '2024-09-02 13:13:00+00', '01JXA7Y5BSZPMR8ZKM45C10E6T', '01JXA7Y5DTY3GPA1VNMP84JBJB', 'DRAFT-AWPR-1', 'US', NULL, NULL, NULL, NULL, NULL, NULL, 'US', '12345', NULL, NULL, NULL, NULL, NULL, 'Awesome Supplier', NULL, 'Test Customer', 'standard', NULL, NULL, '2024-09-09 13:13:14+00', '01JXA7Y5BBM0M8D504ZNQ6WX8X', '01JXA7Y5BBM0M8D504ZNQ6WX8X', '01JXA7Y5BBM0M8D504ZNQ6WX8X', '2024-09-03 13:13:14.010891+00', '{"type": "customer_usage_attribution.v1", "subjectKeys": ["test"]}', 1000, 0, 0, 0, 0, 0, 1000, NULL, NULL, '2024-09-02 13:13:14.010891+00', NULL, NULL, '{"failed": false, "immutable": false, "availableActions": {"delete": {"resultingState": "deleted"}, "approve": {"resultingState": "payment_processing.pending"}}}', '2024-09-02 13:13:14.091153+00'); - - --- --- Data for Name: billing_invoice_lines; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts, split_line_group_id) VALUES ('01JXA7Y5CRJF0NJ5ADKNZVDTGH', 'ns-ubp-invoicing-progressive', 'null', '2025-06-09 11:41:44.216948+00', '2024-09-02 13:13:14.045608+00', NULL, 'UBP - FLAT per unit', NULL, '2024-09-02 12:13:00+00', '2024-09-03 12:13:00+00', '2024-09-03 12:13:14+00', 'usage_based', 'split', 'USD', NULL, NULL, '01JXA7Y5CN0DDF3J98X77PT09W', NULL, '01JXA7Y5CQ74JPSBM8FZD65QM1', NULL, NULL, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, 'manual', NULL, NULL); -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts, split_line_group_id) VALUES ('01JXA7Y5E765KJ1F43EXGHNJTN', 'ns-ubp-invoicing-progressive', 'null', '2024-09-02 13:13:14.024368+00', '2024-09-02 13:13:14.024369+00', NULL, 'UBP - FLAT per unit', NULL, '2024-09-02 13:13:00+00', '2024-09-03 12:13:00+00', '2024-09-03 12:13:14+00', 'usage_based', 'valid', 'USD', NULL, NULL, '01JXA7Y5CN0DDF3J98X77PT09W', NULL, '01JXA7Y5E765KJ1F43EV0TV3YV', '01JXA7Y5CRJF0NJ5ADKNZVDTGH', NULL, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, 'manual', NULL, NULL); -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts, split_line_group_id) VALUES ('01JXA7Y5CRJF0NJ5ADKNZYNCVD', 'ns-ubp-invoicing-progressive', 'null', '2025-06-09 11:41:44.216948+00', '2024-09-02 13:13:14.068374+00', NULL, 'UBP - FLAT per any usage', NULL, '2024-09-02 12:13:14+00', '2024-09-03 12:13:14+00', '2024-09-03 12:13:14+00', 'usage_based', 'valid', 'USD', 1, NULL, '01JXA7Y5CN0DDF3J98X77PT09W', NULL, '01JXA7Y5CQ74JPSBM8G1JCA42B', NULL, NULL, 100, 0, 0, 0, 0, 0, 100, NULL, NULL, NULL, NULL, NULL, 'manual', NULL, NULL); -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts, split_line_group_id) VALUES ('01JXA7Y5E18XC1ZTKZ59B342CM', 'ns-ubp-invoicing-progressive', 'null', '2024-09-02 13:13:14.017513+00', '2024-09-02 13:13:14.097227+00', NULL, 'UBP - FLAT per unit', NULL, '2024-09-02 12:13:00+00', '2024-09-02 13:13:00+00', '2024-09-02 13:13:00+00', 'usage_based', 'valid', 'USD', 10, NULL, '01JXA7Y5DTY3GPA1VNMPD649TK', NULL, '01JXA7Y5E04HGZT2CHR62S0W72', '01JXA7Y5CRJF0NJ5ADKNZVDTGH', NULL, 1000, 0, 0, 0, 0, 0, 1000, NULL, NULL, NULL, NULL, NULL, 'manual', NULL, NULL); -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts, split_line_group_id) VALUES ('01JXA7Y5FMER9E0ZJMFEJ830S4', 'ns-ubp-invoicing-progressive', 'null', '2024-09-02 13:13:14.069163+00', '2024-09-02 13:13:14.069163+00', NULL, 'UBP - FLAT per any usage', NULL, '2024-09-02 12:13:14+00', '2024-09-03 12:13:14+00', '2024-09-03 12:13:14+00', 'flat_fee', 'detailed', 'USD', 1, NULL, '01JXA7Y5CN0DDF3J98X77PT09W', '01JXA7Y5FKC57VN3BGZK2VB5B2', NULL, '01JXA7Y5CRJF0NJ5ADKNZYNCVD', 'flat-price', 100, 0, 0, 0, 0, 0, 100, NULL, NULL, NULL, NULL, NULL, 'system', NULL, NULL); -INSERT INTO public.billing_invoice_lines (id, namespace, metadata, created_at, updated_at, deleted_at, name, description, period_start, period_end, invoice_at, type, status, currency, quantity, tax_config, invoice_id, fee_line_config_id, usage_based_line_config_id, parent_line_id, child_unique_reference_id, amount, taxes_total, taxes_inclusive_total, taxes_exclusive_total, charges_total, discounts_total, total, invoicing_app_external_id, subscription_id, subscription_item_id, subscription_phase_id, line_ids, managed_by, ratecard_discounts, split_line_group_id) VALUES ('01JXA7Y5EWQ5MGXD2W3K8SWBXX', 'ns-ubp-invoicing-progressive', 'null', '2024-09-02 13:13:14.044657+00', '2024-09-02 13:13:14.096672+00', NULL, 'UBP - FLAT per unit: usage in period', NULL, '2024-09-02 12:13:00+00', '2024-09-02 13:13:00+00', '2024-09-02 13:13:00+00', 'flat_fee', 'detailed', 'USD', 10, NULL, '01JXA7Y5DTY3GPA1VNMPD649TK', '01JXA7Y5GFYA1V39TS5HGXQEC6', NULL, '01JXA7Y5E18XC1ZTKZ59B342CM', 'unit-price-usage', 1000, 0, 0, 0, 0, 0, 1000, NULL, NULL, NULL, NULL, NULL, 'system', NULL, NULL); - --- --- Data for Name: billing_invoice_line_discounts; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoice_line_usage_discounts; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: billing_invoice_validation_issues; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_invoice_validation_issues (id, namespace, created_at, updated_at, deleted_at, severity, code, message, path, component, dedupe_hash, invoice_id) VALUES ('01JXA7Y5FHPVB3R6DRPHJV60KS', 'ns-ubp-invoicing-progressive', '2024-09-02 13:13:14.066307+00', '2024-09-02 13:13:14.066308+00', NULL, 'critical', NULL, 'quantity and pre-line period quantity must be set for line[01JXA7Y5E765KJ1F43EXGHNJTN]', '/line[01JXA7Y5E765KJ1F43EXGHNJTN]', 'openmeter', '\x20d9d1af5a95e36c10d436736922e25c3d36b78dbdd5f6f86fa04ab9ddf860d7', '01JXA7Y5CN0DDF3J98X77PT09W'); - - --- --- Data for Name: billing_sequence_numbers; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.billing_sequence_numbers (id, namespace, scope, last) VALUES (1, 'ns-ubp-invoicing-progressive', 'invoices/gathering', 1); -INSERT INTO public.billing_sequence_numbers (id, namespace, scope, last) VALUES (2, 'ns-ubp-invoicing-progressive', 'invoices/draft', 1); - - --- --- Data for Name: customer_subjects; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - -INSERT INTO public.customer_subjects (id, subject_key, created_at, customer_id, namespace, deleted_at) VALUES (1, 'test', '2025-06-09 11:41:44.176953+00', '01JXA7Y5BFE60CQ5EJZ1QYQQ5G', 'ns-ubp-invoicing-progressive', NULL); - - --- --- Data for Name: grants; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: meters; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_channels; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_rules; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_channel_rules; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_event_delivery_status; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_events; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: notification_event_delivery_status_events; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: plan_addons; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: plan_phases; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: plan_rate_cards; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: subjects; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: subscription_addons; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: subscription_addon_quantities; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Data for Name: usage_resets; Type: TABLE DATA; Schema: public; Owner: pgtdbuser --- - - - --- --- Name: app_custom_invoicing_customers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.app_custom_invoicing_customers_id_seq', 1, false); - - --- --- Name: app_customers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.app_customers_id_seq', 1, false); - - --- --- Name: app_stripe_customers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.app_stripe_customers_id_seq', 1, false); - - --- --- Name: balance_snapshots_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.balance_snapshots_id_seq', 1, false); - - --- --- Name: billing_sequence_numbers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.billing_sequence_numbers_id_seq', 2, true); - - --- --- Name: customer_subjects_id_seq; Type: SEQUENCE SET; Schema: public; Owner: pgtdbuser --- - -SELECT pg_catalog.setval('public.customer_subjects_id_seq', 1, true); - - --- --- PostgreSQL database dump complete --- - diff --git a/tools/migrate/testdata/sqlcgen/20250609172811/sqlc.yaml b/tools/migrate/testdata/sqlcgen/20250609172811/sqlc.yaml deleted file mode 100644 index 9e6954cd21..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250609172811/sqlc.yaml +++ /dev/null @@ -1,10 +0,0 @@ -version: "2" -sql: - - engine: "postgresql" - queries: "sqlc/queries.sql" - schema: "sqlc/db-schema.sql" - gen: - go: - package: "db" - out: "db" - omit_unused_structs: true diff --git a/tools/migrate/testdata/sqlcgen/20250609172811/sqlc/db-schema.sql b/tools/migrate/testdata/sqlcgen/20250609172811/sqlc/db-schema.sql deleted file mode 100644 index bbab39844d..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250609172811/sqlc/db-schema.sql +++ /dev/null @@ -1,1037 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 14.17 --- Dumped by pg_dump version 15.13 (Homebrew) - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - -SET default_tablespace = ''; - -SET default_table_access_method = heap; - --- --- Name: billing_customer_locks; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_customer_locks ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: billing_customer_overrides; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_customer_overrides ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - collection_alignment character varying, - invoice_auto_advance boolean, - invoice_collection_method character varying, - billing_profile_id character(26), - customer_id character(26) NOT NULL, - line_collection_period character varying, - invoice_draft_period character varying, - invoice_due_after character varying, - invoice_progressive_billing boolean, - invoice_default_tax_config jsonb -); - - --- --- Name: billing_invoice_flat_fee_line_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_flat_fee_line_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - per_unit_amount numeric NOT NULL, - category character varying DEFAULT 'regular'::character varying NOT NULL, - payment_term character varying DEFAULT 'in_advance'::character varying NOT NULL, - index bigint -); - - --- --- Name: billing_invoice_line_discounts; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_line_discounts ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - child_unique_reference_id character varying, - description character varying, - amount numeric NOT NULL, - line_id character(26) NOT NULL, - invoicing_app_external_id character varying, - reason character varying NOT NULL, - type character varying, - rounding_amount numeric, - quantity numeric, - pre_line_period_quantity numeric, - source_discount jsonb -); - - --- --- Name: billing_invoice_line_usage_discounts; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_line_usage_discounts ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - child_unique_reference_id character varying, - description character varying, - reason character varying NOT NULL, - invoicing_app_external_id character varying, - quantity numeric NOT NULL, - pre_line_period_quantity numeric, - reason_details jsonb, - line_id character(26) NOT NULL -); - - --- --- Name: billing_invoice_lines; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_lines ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - period_start timestamp with time zone NOT NULL, - period_end timestamp with time zone NOT NULL, - invoice_at timestamp with time zone NOT NULL, - type character varying NOT NULL, - status character varying NOT NULL, - currency character varying(3) NOT NULL, - quantity numeric, - tax_config jsonb, - invoice_id character(26) NOT NULL, - fee_line_config_id character(26), - usage_based_line_config_id character(26), - parent_line_id character(26), - child_unique_reference_id character varying, - amount numeric NOT NULL, - taxes_total numeric NOT NULL, - taxes_inclusive_total numeric NOT NULL, - taxes_exclusive_total numeric NOT NULL, - charges_total numeric NOT NULL, - discounts_total numeric NOT NULL, - total numeric NOT NULL, - invoicing_app_external_id character varying, - subscription_id character(26), - subscription_item_id character(26), - subscription_phase_id character(26), - line_ids character(26), - managed_by character varying NOT NULL, - ratecard_discounts jsonb, - split_line_group_id character(26) -); - - --- --- Name: billing_invoice_split_line_groups; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_split_line_groups ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - service_period_start timestamp with time zone NOT NULL, - service_period_end timestamp with time zone NOT NULL, - currency character varying(3) NOT NULL, - tax_config jsonb, - unique_reference_id character varying, - ratecard_discounts jsonb, - feature_key character varying, - price jsonb NOT NULL, - subscription_id character(26), - subscription_item_id character(26), - subscription_phase_id character(26) -); - - --- --- Name: billing_invoice_usage_based_line_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_usage_based_line_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - price_type character varying NOT NULL, - feature_key character varying, - price jsonb NOT NULL, - pre_line_period_quantity numeric, - metered_quantity numeric, - metered_pre_line_period_quantity numeric -); - - --- --- Name: billing_invoice_validation_issues; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_validation_issues ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - severity character varying NOT NULL, - code character varying, - message character varying NOT NULL, - path character varying, - component character varying NOT NULL, - dedupe_hash bytea NOT NULL, - invoice_id character(26) NOT NULL -); - - --- --- Name: billing_invoices; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoices ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - customer_id character(26) NOT NULL, - voided_at timestamp with time zone, - currency character varying(3) NOT NULL, - status character varying NOT NULL, - period_start timestamp with time zone, - period_end timestamp with time zone, - source_billing_profile_id character(26) NOT NULL, - workflow_config_id character(26) NOT NULL, - number character varying NOT NULL, - supplier_address_country character varying, - supplier_address_postal_code character varying, - supplier_address_state character varying, - supplier_address_city character varying, - supplier_address_line1 character varying, - supplier_address_line2 character varying, - supplier_address_phone_number character varying, - customer_address_country character varying, - customer_address_postal_code character varying, - customer_address_state character varying, - customer_address_city character varying, - customer_address_line1 character varying, - customer_address_line2 character varying, - customer_address_phone_number character varying, - supplier_name character varying NOT NULL, - supplier_tax_code character varying, - customer_name character varying NOT NULL, - type character varying NOT NULL, - description character varying, - issued_at timestamp with time zone, - due_at timestamp with time zone, - tax_app_id character(26) NOT NULL, - invoicing_app_id character(26) NOT NULL, - payment_app_id character(26) NOT NULL, - draft_until timestamp with time zone, - customer_usage_attribution jsonb NOT NULL, - amount numeric NOT NULL, - taxes_total numeric NOT NULL, - taxes_inclusive_total numeric NOT NULL, - taxes_exclusive_total numeric NOT NULL, - charges_total numeric NOT NULL, - discounts_total numeric NOT NULL, - total numeric NOT NULL, - invoicing_app_external_id character varying, - payment_app_external_id character varying, - collection_at timestamp with time zone, - sent_to_customer_at timestamp with time zone, - tax_app_external_id character varying, - status_details_cache jsonb, - quantity_snapshoted_at timestamp with time zone -); - - --- --- Name: billing_profiles; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_profiles ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - "default" boolean DEFAULT false NOT NULL, - workflow_config_id character(26) NOT NULL, - metadata jsonb, - supplier_address_country character varying, - supplier_address_postal_code character varying, - supplier_address_state character varying, - supplier_address_city character varying, - supplier_address_line1 character varying, - supplier_address_line2 character varying, - supplier_address_phone_number character varying, - supplier_name character varying NOT NULL, - name character varying NOT NULL, - description character varying, - supplier_tax_code character varying, - tax_app_id character(26) NOT NULL, - invoicing_app_id character(26) NOT NULL, - payment_app_id character(26) NOT NULL -); - - --- --- Name: billing_sequence_numbers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_sequence_numbers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - scope character varying NOT NULL, - last numeric NOT NULL -); - - --- --- Name: billing_sequence_numbers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.billing_sequence_numbers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.billing_sequence_numbers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: billing_workflow_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_workflow_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - collection_alignment character varying NOT NULL, - invoice_auto_advance boolean NOT NULL, - invoice_collection_method character varying NOT NULL, - line_collection_period character varying NOT NULL, - invoice_draft_period character varying NOT NULL, - invoice_due_after character varying NOT NULL, - invoice_progressive_billing boolean NOT NULL, - invoice_default_tax_settings jsonb, - tax_enabled boolean DEFAULT true NOT NULL, - tax_enforced boolean DEFAULT false NOT NULL -); - - --- --- Name: billing_customer_locks billing_customer_locks_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_locks - ADD CONSTRAINT billing_customer_locks_pkey PRIMARY KEY (id); - - --- --- Name: billing_customer_overrides billing_customer_overrides_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_flat_fee_line_configs billing_invoice_flat_fee_line_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_flat_fee_line_configs - ADD CONSTRAINT billing_invoice_flat_fee_line_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_line_discounts billing_invoice_line_discounts_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_discounts - ADD CONSTRAINT billing_invoice_line_discounts_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_line_usage_discounts billing_invoice_line_usage_discounts_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_usage_discounts - ADD CONSTRAINT billing_invoice_line_usage_discounts_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_lines billing_invoice_lines_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_usage_based_line_configs billing_invoice_usage_based_line_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_usage_based_line_configs - ADD CONSTRAINT billing_invoice_usage_based_line_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_validation_issues billing_invoice_validation_issues_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_validation_issues - ADD CONSTRAINT billing_invoice_validation_issues_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoices billing_invoices_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_pkey PRIMARY KEY (id); - - --- --- Name: billing_profiles billing_profiles_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_pkey PRIMARY KEY (id); - - --- --- Name: billing_sequence_numbers billing_sequence_numbers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_sequence_numbers - ADD CONSTRAINT billing_sequence_numbers_pkey PRIMARY KEY (id); - - --- --- Name: billing_workflow_configs billing_workflow_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_workflow_configs - ADD CONSTRAINT billing_workflow_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_customer_overrides_customer_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_customer_overrides_customer_id_key ON public.billing_customer_overrides USING btree (customer_id); - - --- --- Name: billing_invoices_workflow_config_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_invoices_workflow_config_id_key ON public.billing_invoices USING btree (workflow_config_id); - - --- --- Name: billing_profiles_workflow_config_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_profiles_workflow_config_id_key ON public.billing_profiles USING btree (workflow_config_id); - - --- --- Name: billingcustomerlock_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomerlock_id ON public.billing_customer_locks USING btree (id); - - --- --- Name: billingcustomerlock_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingcustomerlock_namespace ON public.billing_customer_locks USING btree (namespace); - - --- --- Name: billingcustomerlock_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomerlock_namespace_customer_id ON public.billing_customer_locks USING btree (namespace, customer_id); - - --- --- Name: billingcustomeroverride_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_id ON public.billing_customer_overrides USING btree (id); - - --- --- Name: billingcustomeroverride_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingcustomeroverride_namespace ON public.billing_customer_overrides USING btree (namespace); - - --- --- Name: billingcustomeroverride_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_namespace_customer_id ON public.billing_customer_overrides USING btree (namespace, customer_id); - - --- --- Name: billingcustomeroverride_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_namespace_id ON public.billing_customer_overrides USING btree (namespace, id); - - --- --- Name: billinginvoice_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoice_id ON public.billing_invoices USING btree (id); - - --- --- Name: billinginvoice_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace ON public.billing_invoices USING btree (namespace); - - --- --- Name: billinginvoice_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_customer_id ON public.billing_invoices USING btree (namespace, customer_id); - - --- --- Name: billinginvoice_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_id ON public.billing_invoices USING btree (namespace, id); - - --- --- Name: billinginvoice_namespace_status; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_status ON public.billing_invoices USING btree (namespace, status); - - --- --- Name: billinginvoice_status_details_cache; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_status_details_cache ON public.billing_invoices USING gin (status_details_cache); - - --- --- Name: billinginvoiceflatfeelineconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceflatfeelineconfig_id ON public.billing_invoice_flat_fee_line_configs USING btree (id); - - --- --- Name: billinginvoiceflatfeelineconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceflatfeelineconfig_namespace ON public.billing_invoice_flat_fee_line_configs USING btree (namespace); - - --- --- Name: billinginvoiceline_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_id ON public.billing_invoice_lines USING btree (id); - - --- --- Name: billinginvoiceline_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace ON public.billing_invoice_lines USING btree (namespace); - - --- --- Name: billinginvoiceline_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_namespace_id ON public.billing_invoice_lines USING btree (namespace, id); - - --- --- Name: billinginvoiceline_namespace_invoice_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_invoice_id ON public.billing_invoice_lines USING btree (namespace, invoice_id); - - --- --- Name: billinginvoiceline_namespace_parent_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_parent_line_id ON public.billing_invoice_lines USING btree (namespace, parent_line_id); - - --- --- Name: billinginvoiceline_namespace_parent_line_id_child_unique_refere; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_namespace_parent_line_id_child_unique_refere ON public.billing_invoice_lines USING btree (namespace, parent_line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoiceline_namespace_subscription_id_subscription_phase; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_subscription_id_subscription_phase ON public.billing_invoice_lines USING btree (namespace, subscription_id, subscription_phase_id, subscription_item_id); - - --- --- Name: billinginvoicelinediscount_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelinediscount_id ON public.billing_invoice_line_discounts USING btree (id); - - --- --- Name: billinginvoicelinediscount_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelinediscount_namespace ON public.billing_invoice_line_discounts USING btree (namespace); - - --- --- Name: billinginvoicelinediscount_namespace_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelinediscount_namespace_line_id ON public.billing_invoice_line_discounts USING btree (namespace, line_id); - - --- --- Name: billinginvoicelinediscount_namespace_line_id_child_unique_refer; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelinediscount_namespace_line_id_child_unique_refer ON public.billing_invoice_line_discounts USING btree (namespace, line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoicelineusagediscount_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelineusagediscount_id ON public.billing_invoice_line_usage_discounts USING btree (id); - - --- --- Name: billinginvoicelineusagediscount_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelineusagediscount_namespace ON public.billing_invoice_line_usage_discounts USING btree (namespace); - - --- --- Name: billinginvoicelineusagediscount_namespace_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelineusagediscount_namespace_line_id ON public.billing_invoice_line_usage_discounts USING btree (namespace, line_id); - - --- --- Name: billinginvoicelineusagediscount_namespace_line_id_child_unique_; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelineusagediscount_namespace_line_id_child_unique_ ON public.billing_invoice_line_usage_discounts USING btree (namespace, line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoicesplitlinegroup_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_id ON public.billing_invoice_split_line_groups USING btree (id); - - --- --- Name: billinginvoicesplitlinegroup_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicesplitlinegroup_namespace ON public.billing_invoice_split_line_groups USING btree (namespace); - - --- --- Name: billinginvoicesplitlinegroup_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_namespace_id ON public.billing_invoice_split_line_groups USING btree (namespace, id); - - --- --- Name: billinginvoicesplitlinegroup_namespace_unique_reference_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_namespace_unique_reference_id ON public.billing_invoice_split_line_groups USING btree (namespace, unique_reference_id) WHERE ((unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoiceusagebasedlineconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceusagebasedlineconfig_id ON public.billing_invoice_usage_based_line_configs USING btree (id); - - --- --- Name: billinginvoiceusagebasedlineconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceusagebasedlineconfig_namespace ON public.billing_invoice_usage_based_line_configs USING btree (namespace); - - --- --- Name: billinginvoicevalidationissue_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicevalidationissue_id ON public.billing_invoice_validation_issues USING btree (id); - - --- --- Name: billinginvoicevalidationissue_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicevalidationissue_namespace ON public.billing_invoice_validation_issues USING btree (namespace); - - --- --- Name: billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash ON public.billing_invoice_validation_issues USING btree (namespace, invoice_id, dedupe_hash); - - --- --- Name: billingprofile_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_id ON public.billing_profiles USING btree (id); - - --- --- Name: billingprofile_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingprofile_namespace ON public.billing_profiles USING btree (namespace); - - --- --- Name: billingprofile_namespace_default; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_namespace_default ON public.billing_profiles USING btree (namespace, "default") WHERE ("default" AND (deleted_at IS NULL)); - - --- --- Name: billingprofile_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_namespace_id ON public.billing_profiles USING btree (namespace, id); - - --- --- Name: billingsequencenumbers_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingsequencenumbers_namespace ON public.billing_sequence_numbers USING btree (namespace); - - --- --- Name: billingsequencenumbers_namespace_scope; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingsequencenumbers_namespace_scope ON public.billing_sequence_numbers USING btree (namespace, scope); - - --- --- Name: billingworkflowconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingworkflowconfig_id ON public.billing_workflow_configs USING btree (id); - - --- --- Name: billingworkflowconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingworkflowconfig_namespace ON public.billing_workflow_configs USING btree (namespace); - - --- --- Name: billingworkflowconfig_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingworkflowconfig_namespace_id ON public.billing_workflow_configs USING btree (namespace, id); - - --- --- Name: billing_customer_overrides billing_customer_overrides_billing_profiles_billing_customer_ov; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_billing_profiles_billing_customer_ov FOREIGN KEY (billing_profile_id) REFERENCES public.billing_profiles(id) ON DELETE SET NULL; - - --- --- Name: billing_customer_overrides billing_customer_overrides_customers_billing_customer_override; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_customers_billing_customer_override FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_line_discounts billing_invoice_line_discounts_billing_invoice_lines_line_amoun; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_discounts - ADD CONSTRAINT billing_invoice_line_discounts_billing_invoice_lines_line_amoun FOREIGN KEY (line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_line_usage_discounts billing_invoice_line_usage_discounts_billing_invoice_lines_line; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_usage_discounts - ADD CONSTRAINT billing_invoice_line_usage_discounts_billing_invoice_lines_line FOREIGN KEY (line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_flat_fee_line_configs_fla; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_flat_fee_line_configs_fla FOREIGN KEY (fee_line_config_id) REFERENCES public.billing_invoice_flat_fee_line_configs(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_lines_detailed_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_lines_detailed_lines FOREIGN KEY (parent_line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_split_line_groups_billing; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_split_line_groups_billing FOREIGN KEY (split_line_group_id) REFERENCES public.billing_invoice_split_line_groups(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_usage_based_line_configs_; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_usage_based_line_configs_ FOREIGN KEY (usage_based_line_config_id) REFERENCES public.billing_invoice_usage_based_line_configs(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoices_billing_invoice_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoices_billing_invoice_lines FOREIGN KEY (invoice_id) REFERENCES public.billing_invoices(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscription_items_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscription_items_billing_lines FOREIGN KEY (subscription_item_id) REFERENCES public.subscription_items(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscription_phases_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscription_phases_billing_lines FOREIGN KEY (subscription_phase_id) REFERENCES public.subscription_phases(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscriptions_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscriptions_billing_lines FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscription_items_billing_sp; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscription_items_billing_sp FOREIGN KEY (subscription_item_id) REFERENCES public.subscription_items(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscription_phases_billing_s; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscription_phases_billing_s FOREIGN KEY (subscription_phase_id) REFERENCES public.subscription_phases(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscriptions_billing_split_l; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscriptions_billing_split_l FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_validation_issues billing_invoice_validation_issues_billing_invoices_billing_invo; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_validation_issues - ADD CONSTRAINT billing_invoice_validation_issues_billing_invoices_billing_invo FOREIGN KEY (invoice_id) REFERENCES public.billing_invoices(id) ON DELETE CASCADE; - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_invoicing_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_invoicing_app FOREIGN KEY (invoicing_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_payment_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_payment_app FOREIGN KEY (payment_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_tax_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_tax_app FOREIGN KEY (tax_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_billing_profiles_billing_invoices; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_billing_profiles_billing_invoices FOREIGN KEY (source_billing_profile_id) REFERENCES public.billing_profiles(id); - - --- --- Name: billing_invoices billing_invoices_billing_workflow_configs_billing_invoices; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_billing_workflow_configs_billing_invoices FOREIGN KEY (workflow_config_id) REFERENCES public.billing_workflow_configs(id); - - --- --- Name: billing_invoices billing_invoices_customers_billing_invoice; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_customers_billing_invoice FOREIGN KEY (customer_id) REFERENCES public.customers(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_invoicing_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_invoicing_app FOREIGN KEY (invoicing_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_payment_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_payment_app FOREIGN KEY (payment_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_tax_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_tax_app FOREIGN KEY (tax_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_billing_workflow_configs_billing_profile; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_billing_workflow_configs_billing_profile FOREIGN KEY (workflow_config_id) REFERENCES public.billing_workflow_configs(id); - - --- --- PostgreSQL database dump complete --- - diff --git a/tools/migrate/testdata/sqlcgen/20250609172811/sqlc/queries.sql b/tools/migrate/testdata/sqlcgen/20250609172811/sqlc/queries.sql deleted file mode 100644 index 3842a9418c..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250609172811/sqlc/queries.sql +++ /dev/null @@ -1,14 +0,0 @@ --- name: GetSplitLineGroup :one -SELECT * - FROM public.billing_invoice_split_line_groups - WHERE id = $1; - --- name: GetUsageBasedLinesBySplitLineGroup :many -SELECT l.*, c.price, c.feature_key - FROM public.billing_invoice_lines l JOIN public.billing_invoice_usage_based_line_configs c ON (l.usage_based_line_config_id = c.id) - WHERE type = 'usage_based' AND status = 'valid' AND split_line_group_id = $1; - --- name: CountLinesByStatusType :many -SELECT status, type, count(*) - FROM public.billing_invoice_lines - GROUP BY status, type; diff --git a/tools/migrate/testdata/sqlcgen/20250624115812/db/db.go b/tools/migrate/testdata/sqlcgen/20250624115812/db/db.go deleted file mode 100644 index 0c56c2b4e8..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250624115812/db/db.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 - -package db - -import ( - "context" - "database/sql" -) - -type DBTX interface { - ExecContext(context.Context, string, ...interface{}) (sql.Result, error) - PrepareContext(context.Context, string) (*sql.Stmt, error) - QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) - QueryRowContext(context.Context, string, ...interface{}) *sql.Row -} - -func New(db DBTX) *Queries { - return &Queries{db: db} -} - -type Queries struct { - db DBTX -} - -func (q *Queries) WithTx(tx *sql.Tx) *Queries { - return &Queries{ - db: tx, - } -} diff --git a/tools/migrate/testdata/sqlcgen/20250624115812/db/models.go b/tools/migrate/testdata/sqlcgen/20250624115812/db/models.go deleted file mode 100644 index 580be94c8c..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250624115812/db/models.go +++ /dev/null @@ -1,738 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 - -package db - -import ( - "database/sql" - "encoding/json" - "time" - - "github.com/sqlc-dev/pqtype" -) - -type Addon struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - Version int64 - Currency string - EffectiveFrom sql.NullTime - EffectiveTo sql.NullTime - Annotations pqtype.NullRawMessage - InstanceType string -} - -type AddonRateCard struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - Type string - FeatureKey sql.NullString - EntitlementTemplate pqtype.NullRawMessage - TaxConfig pqtype.NullRawMessage - BillingCadence sql.NullString - Price pqtype.NullRawMessage - Discounts pqtype.NullRawMessage - AddonID string - FeatureID sql.NullString -} - -type App struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Type string - Status string -} - -type AppCustomInvoicing struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - EnableDraftSyncHook bool - EnableIssuingSyncHook bool -} - -type AppCustomInvoicingCustomer struct { - ID int64 - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - AppID string - CustomerID string -} - -type AppCustomer struct { - ID int64 - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - AppID string - CustomerID string -} - -type AppStripe struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - StripeAccountID string - StripeLivemode bool - ApiKey string - StripeWebhookID string - WebhookSecret string - MaskedApiKey string -} - -type AppStripeCustomer struct { - ID int64 - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - StripeCustomerID string - StripeDefaultPaymentMethodID sql.NullString - AppID string - CustomerID string -} - -type BalanceSnapshot struct { - ID int64 - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - GrantBalances json.RawMessage - Balance string - Overage string - At time.Time - OwnerID string - Usage pqtype.NullRawMessage -} - -type BillingCustomerLock struct { - ID string - Namespace string - CustomerID string -} - -type BillingCustomerOverride struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - CollectionAlignment sql.NullString - InvoiceAutoAdvance sql.NullBool - InvoiceCollectionMethod sql.NullString - BillingProfileID sql.NullString - CustomerID string - LineCollectionPeriod sql.NullString - InvoiceDraftPeriod sql.NullString - InvoiceDueAfter sql.NullString - InvoiceProgressiveBilling sql.NullBool - InvoiceDefaultTaxConfig pqtype.NullRawMessage -} - -type BillingInvoice struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - CustomerID string - VoidedAt sql.NullTime - Currency string - Status string - PeriodStart sql.NullTime - PeriodEnd sql.NullTime - SourceBillingProfileID string - WorkflowConfigID string - Number string - SupplierAddressCountry sql.NullString - SupplierAddressPostalCode sql.NullString - SupplierAddressState sql.NullString - SupplierAddressCity sql.NullString - SupplierAddressLine1 sql.NullString - SupplierAddressLine2 sql.NullString - SupplierAddressPhoneNumber sql.NullString - CustomerAddressCountry sql.NullString - CustomerAddressPostalCode sql.NullString - CustomerAddressState sql.NullString - CustomerAddressCity sql.NullString - CustomerAddressLine1 sql.NullString - CustomerAddressLine2 sql.NullString - CustomerAddressPhoneNumber sql.NullString - SupplierName string - SupplierTaxCode sql.NullString - CustomerName string - Type string - Description sql.NullString - IssuedAt sql.NullTime - DueAt sql.NullTime - TaxAppID string - InvoicingAppID string - PaymentAppID string - DraftUntil sql.NullTime - CustomerUsageAttribution json.RawMessage - Amount string - TaxesTotal string - TaxesInclusiveTotal string - TaxesExclusiveTotal string - ChargesTotal string - DiscountsTotal string - Total string - InvoicingAppExternalID sql.NullString - PaymentAppExternalID sql.NullString - CollectionAt sql.NullTime - SentToCustomerAt sql.NullTime - TaxAppExternalID sql.NullString - StatusDetailsCache pqtype.NullRawMessage - QuantitySnapshotedAt sql.NullTime -} - -type BillingInvoiceFlatFeeLineConfig struct { - ID string - Namespace string - PerUnitAmount string - Category string - PaymentTerm string - Index sql.NullInt64 -} - -type BillingInvoiceLine struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - PeriodStart time.Time - PeriodEnd time.Time - InvoiceAt time.Time - Type string - Status string - Currency string - Quantity sql.NullString - TaxConfig pqtype.NullRawMessage - InvoiceID string - FeeLineConfigID sql.NullString - UsageBasedLineConfigID sql.NullString - ParentLineID sql.NullString - ChildUniqueReferenceID sql.NullString - Amount string - TaxesTotal string - TaxesInclusiveTotal string - TaxesExclusiveTotal string - ChargesTotal string - DiscountsTotal string - Total string - InvoicingAppExternalID sql.NullString - SubscriptionID sql.NullString - SubscriptionItemID sql.NullString - SubscriptionPhaseID sql.NullString - LineIds sql.NullString - ManagedBy string - RatecardDiscounts pqtype.NullRawMessage - SplitLineGroupID sql.NullString -} - -type BillingInvoiceLineDiscount struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - ChildUniqueReferenceID sql.NullString - Description sql.NullString - Amount string - LineID string - InvoicingAppExternalID sql.NullString - Reason string - Type sql.NullString - RoundingAmount sql.NullString - Quantity sql.NullString - PreLinePeriodQuantity sql.NullString - SourceDiscount pqtype.NullRawMessage -} - -type BillingInvoiceLineUsageDiscount struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - ChildUniqueReferenceID sql.NullString - Description sql.NullString - Reason string - InvoicingAppExternalID sql.NullString - Quantity string - PreLinePeriodQuantity sql.NullString - ReasonDetails pqtype.NullRawMessage - LineID string -} - -type BillingInvoiceSplitLineGroup struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Currency string - TaxConfig pqtype.NullRawMessage - ServicePeriodStart time.Time - ServicePeriodEnd time.Time - UniqueReferenceID sql.NullString - RatecardDiscounts pqtype.NullRawMessage - FeatureKey sql.NullString - Price json.RawMessage - SubscriptionID sql.NullString - SubscriptionItemID sql.NullString - SubscriptionPhaseID sql.NullString -} - -type BillingInvoiceUsageBasedLineConfig struct { - ID string - Namespace string - PriceType string - FeatureKey sql.NullString - Price json.RawMessage - PreLinePeriodQuantity sql.NullString - MeteredQuantity sql.NullString - MeteredPreLinePeriodQuantity sql.NullString -} - -type BillingInvoiceValidationIssue struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Severity string - Code sql.NullString - Message string - Path sql.NullString - Component string - DedupeHash []byte - InvoiceID string -} - -type BillingProfile struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Default bool - WorkflowConfigID string - Metadata pqtype.NullRawMessage - SupplierAddressCountry sql.NullString - SupplierAddressPostalCode sql.NullString - SupplierAddressState sql.NullString - SupplierAddressCity sql.NullString - SupplierAddressLine1 sql.NullString - SupplierAddressLine2 sql.NullString - SupplierAddressPhoneNumber sql.NullString - SupplierName string - Name string - Description sql.NullString - SupplierTaxCode sql.NullString - TaxAppID string - InvoicingAppID string - PaymentAppID string -} - -type BillingSequenceNumber struct { - ID int64 - Namespace string - Scope string - Last string -} - -type BillingWorkflowConfig struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - CollectionAlignment string - InvoiceAutoAdvance bool - InvoiceCollectionMethod string - LineCollectionPeriod string - InvoiceDraftPeriod string - InvoiceDueAfter string - InvoiceProgressiveBilling bool - InvoiceDefaultTaxSettings pqtype.NullRawMessage - TaxEnabled bool - TaxEnforced bool -} - -type Customer struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Currency sql.NullString - PrimaryEmail sql.NullString - BillingAddressCountry sql.NullString - BillingAddressPostalCode sql.NullString - BillingAddressState sql.NullString - BillingAddressCity sql.NullString - BillingAddressLine1 sql.NullString - BillingAddressLine2 sql.NullString - BillingAddressPhoneNumber sql.NullString - Description sql.NullString - Key sql.NullString -} - -type CustomerSubject struct { - ID int64 - SubjectKey string - CreatedAt time.Time - CustomerID string - Namespace string - DeletedAt sql.NullTime -} - -type Entitlement struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - EntitlementType string - FeatureKey string - SubjectKey string - MeasureUsageFrom sql.NullTime - IssueAfterReset sql.NullFloat64 - IssueAfterResetPriority sql.NullInt16 - IsSoftLimit sql.NullBool - PreserveOverageAtReset sql.NullBool - Config pqtype.NullRawMessage - UsagePeriodInterval sql.NullString - UsagePeriodAnchor sql.NullTime - CurrentUsagePeriodStart sql.NullTime - CurrentUsagePeriodEnd sql.NullTime - FeatureID string - ActiveFrom sql.NullTime - ActiveTo sql.NullTime - Annotations pqtype.NullRawMessage -} - -type Feature struct { - ID string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - Namespace string - Name string - Key string - MeterSlug sql.NullString - MeterGroupByFilters pqtype.NullRawMessage - ArchivedAt sql.NullTime -} - -type Grant struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Amount string - Priority int16 - EffectiveAt time.Time - Expiration json.RawMessage - ExpiresAt time.Time - VoidedAt sql.NullTime - ResetMaxRollover string - ResetMinRollover string - RecurrencePeriod sql.NullString - RecurrenceAnchor sql.NullTime - OwnerID string -} - -type Meter struct { - ID string - CreatedAt time.Time - UpdatedAt time.Time - Key string - Description sql.NullString - EventType string - ValueProperty sql.NullString - GroupBy pqtype.NullRawMessage - Aggregation string - Namespace string - Name string - EventFrom sql.NullTime - Metadata pqtype.NullRawMessage - DeletedAt sql.NullTime -} - -type NotificationChannel struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Type string - Name string - Disabled sql.NullBool - Config json.RawMessage -} - -type NotificationChannelRule struct { - NotificationChannelID string - NotificationRuleID string -} - -type NotificationEvent struct { - ID string - Namespace string - CreatedAt time.Time - Type string - Payload json.RawMessage - Annotations pqtype.NullRawMessage - RuleID string -} - -type NotificationEventDeliveryStatus struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - EventID string - ChannelID string - State string - Reason sql.NullString -} - -type NotificationEventDeliveryStatusEvent struct { - NotificationEventDeliveryStatusID string - NotificationEventID string -} - -type NotificationRule struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Type string - Name string - Disabled sql.NullBool - Config json.RawMessage -} - -type Plan struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - Version int64 - Currency string - EffectiveFrom sql.NullTime - EffectiveTo sql.NullTime - BillingCadence string - ProRatingConfig json.RawMessage -} - -type PlanAddon struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - Annotations pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - FromPlanPhase string - MaxQuantity sql.NullInt64 - AddonID string - PlanID string -} - -type PlanPhase struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - PlanID string - Index int16 - Duration sql.NullString -} - -type PlanRateCard struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - Type string - FeatureKey sql.NullString - EntitlementTemplate pqtype.NullRawMessage - TaxConfig pqtype.NullRawMessage - BillingCadence sql.NullString - Price pqtype.NullRawMessage - FeatureID sql.NullString - PhaseID string - Discounts pqtype.NullRawMessage -} - -type SchemaOm struct { - Version int64 - Dirty bool -} - -type Subject struct { - CreatedAt time.Time - UpdatedAt time.Time - ID string - Key string - DisplayName sql.NullString - Metadata pqtype.NullRawMessage - StripeCustomerID sql.NullString - Namespace string -} - -type Subscription struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - ActiveFrom time.Time - ActiveTo sql.NullTime - Currency string - CustomerID string - Name string - Description sql.NullString - PlanID sql.NullString - BillingCadence string - ProRatingConfig json.RawMessage - BillingAnchor time.Time -} - -type SubscriptionAddon struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - AddonID string - SubscriptionID string -} - -type SubscriptionAddonQuantity struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - ActiveFrom time.Time - Quantity int64 - SubscriptionAddonID string -} - -type SubscriptionItem struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - ActiveFrom time.Time - ActiveTo sql.NullTime - Key string - ActiveFromOverrideRelativeToPhaseStart sql.NullString - ActiveToOverrideRelativeToPhaseStart sql.NullString - Name string - Description sql.NullString - FeatureKey sql.NullString - EntitlementTemplate pqtype.NullRawMessage - TaxConfig pqtype.NullRawMessage - BillingCadence sql.NullString - Price pqtype.NullRawMessage - EntitlementID sql.NullString - PhaseID string - RestartsBillingPeriod sql.NullBool - Discounts pqtype.NullRawMessage - Annotations pqtype.NullRawMessage -} - -type SubscriptionPhase struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - Key string - Name string - Description sql.NullString - ActiveFrom time.Time - SubscriptionID string - SortHint sql.NullInt16 -} - -type UsageReset struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - ResetTime time.Time - EntitlementID string - Anchor time.Time -} diff --git a/tools/migrate/testdata/sqlcgen/20250624115812/db/queries.sql.go b/tools/migrate/testdata/sqlcgen/20250624115812/db/queries.sql.go deleted file mode 100644 index 11958ed7a9..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250624115812/db/queries.sql.go +++ /dev/null @@ -1,199 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 -// source: queries.sql - -package db - -import ( - "context" - "database/sql" - "time" -) - -const createEntitlement = `-- name: CreateEntitlement :exec -INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - usage_period_interval, - usage_period_anchor -) VALUES ( - $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 -) -` - -type CreateEntitlementParams struct { - Namespace string - ID string - CreatedAt time.Time - UpdatedAt time.Time - EntitlementType string - FeatureKey string - FeatureID string - SubjectKey string - UsagePeriodInterval sql.NullString - UsagePeriodAnchor sql.NullTime -} - -func (q *Queries) CreateEntitlement(ctx context.Context, arg CreateEntitlementParams) error { - _, err := q.db.ExecContext(ctx, createEntitlement, - arg.Namespace, - arg.ID, - arg.CreatedAt, - arg.UpdatedAt, - arg.EntitlementType, - arg.FeatureKey, - arg.FeatureID, - arg.SubjectKey, - arg.UsagePeriodInterval, - arg.UsagePeriodAnchor, - ) - return err -} - -const createFeature = `-- name: CreateFeature :exec -INSERT INTO features ( - namespace, - id, - key, - name, - created_at, - updated_at -) VALUES ( - $1, $2, $3, $4, $5, $6 -) -` - -type CreateFeatureParams struct { - Namespace string - ID string - Key string - Name string - CreatedAt time.Time - UpdatedAt time.Time -} - -// Insert queries for test setup -func (q *Queries) CreateFeature(ctx context.Context, arg CreateFeatureParams) error { - _, err := q.db.ExecContext(ctx, createFeature, - arg.Namespace, - arg.ID, - arg.Key, - arg.Name, - arg.CreatedAt, - arg.UpdatedAt, - ) - return err -} - -const createUsageReset = `-- name: CreateUsageReset :exec -INSERT INTO usage_resets ( - namespace, - id, - created_at, - updated_at, - entitlement_id, - reset_time, - anchor -) VALUES ( - $1, $2, $3, $4, $5, $6, $7 -) -` - -type CreateUsageResetParams struct { - Namespace string - ID string - CreatedAt time.Time - UpdatedAt time.Time - EntitlementID string - ResetTime time.Time - Anchor time.Time -} - -func (q *Queries) CreateUsageReset(ctx context.Context, arg CreateUsageResetParams) error { - _, err := q.db.ExecContext(ctx, createUsageReset, - arg.Namespace, - arg.ID, - arg.CreatedAt, - arg.UpdatedAt, - arg.EntitlementID, - arg.ResetTime, - arg.Anchor, - ) - return err -} - -const getEntitlementByID = `-- name: GetEntitlementByID :one -SELECT id, namespace, metadata, created_at, updated_at, deleted_at, entitlement_type, feature_key, subject_key, measure_usage_from, issue_after_reset, issue_after_reset_priority, is_soft_limit, preserve_overage_at_reset, config, usage_period_interval, usage_period_anchor, current_usage_period_start, current_usage_period_end, feature_id, active_from, active_to, annotations FROM entitlements WHERE id = $1 -` - -// Query to get entitlement info -func (q *Queries) GetEntitlementByID(ctx context.Context, id string) (Entitlement, error) { - row := q.db.QueryRowContext(ctx, getEntitlementByID, id) - var i Entitlement - err := row.Scan( - &i.ID, - &i.Namespace, - &i.Metadata, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.EntitlementType, - &i.FeatureKey, - &i.SubjectKey, - &i.MeasureUsageFrom, - &i.IssueAfterReset, - &i.IssueAfterResetPriority, - &i.IsSoftLimit, - &i.PreserveOverageAtReset, - &i.Config, - &i.UsagePeriodInterval, - &i.UsagePeriodAnchor, - &i.CurrentUsagePeriodStart, - &i.CurrentUsagePeriodEnd, - &i.FeatureID, - &i.ActiveFrom, - &i.ActiveTo, - &i.Annotations, - ) - return i, err -} - -const getSchemaVersion = `-- name: GetSchemaVersion :one -SELECT version FROM schema_om ORDER BY version DESC LIMIT 1 -` - -// Placeholder query for SQLC validation -func (q *Queries) GetSchemaVersion(ctx context.Context) (int64, error) { - row := q.db.QueryRowContext(ctx, getSchemaVersion) - var version int64 - err := row.Scan(&version) - return version, err -} - -const getUsageResetByID = `-- name: GetUsageResetByID :one -SELECT id, namespace, created_at, updated_at, deleted_at, reset_time, entitlement_id, anchor FROM usage_resets WHERE id = $1 -` - -// Query to verify usage reset data -func (q *Queries) GetUsageResetByID(ctx context.Context, id string) (UsageReset, error) { - row := q.db.QueryRowContext(ctx, getUsageResetByID, id) - var i UsageReset - err := row.Scan( - &i.ID, - &i.Namespace, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.ResetTime, - &i.EntitlementID, - &i.Anchor, - ) - return i, err -} diff --git a/tools/migrate/testdata/sqlcgen/20250624115812/sqlc.yaml b/tools/migrate/testdata/sqlcgen/20250624115812/sqlc.yaml deleted file mode 100644 index b88fc3da87..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250624115812/sqlc.yaml +++ /dev/null @@ -1,9 +0,0 @@ -version: "2" -sql: - - engine: "postgresql" - queries: "sqlc/queries.sql" - schema: "sqlc/db-schema.sql" - gen: - go: - package: "db" - out: "db" diff --git a/tools/migrate/testdata/sqlcgen/20250624115812/sqlc/db-schema.sql b/tools/migrate/testdata/sqlcgen/20250624115812/sqlc/db-schema.sql deleted file mode 100644 index c6a7735989..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250624115812/sqlc/db-schema.sql +++ /dev/null @@ -1,3196 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 14.9 (Debian 14.9-1.pgdg120+1) --- Dumped by pg_dump version 14.9 (Debian 14.9-1.pgdg120+1) - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- Name: pgcrypto; Type: EXTENSION; Schema: -; Owner: - --- - -CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; - - --- --- Name: EXTENSION pgcrypto; Type: COMMENT; Schema: -; Owner: - --- - -COMMENT ON EXTENSION pgcrypto IS 'cryptographic functions'; - - --- --- Name: delete_entitlement_on_subscription_item_delete(); Type: FUNCTION; Schema: public; Owner: - --- - -CREATE FUNCTION public.delete_entitlement_on_subscription_item_delete() RETURNS trigger - LANGUAGE plpgsql - AS $$ -BEGIN - -- Delete the entitlement if it exists and is referenced by the deleted subscription_item - IF OLD.entitlement_id IS NOT NULL THEN - DELETE FROM entitlements WHERE id = OLD.entitlement_id; - END IF; - RETURN OLD; -END; -$$; - - -SET default_tablespace = ''; - -SET default_table_access_method = heap; - --- --- Name: addon_rate_cards; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.addon_rate_cards ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - type character varying NOT NULL, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - discounts jsonb, - addon_id character(26) NOT NULL, - feature_id character(26) -); - - --- --- Name: addons; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - version bigint NOT NULL, - currency character varying DEFAULT 'USD'::character varying NOT NULL, - effective_from timestamp with time zone, - effective_to timestamp with time zone, - annotations jsonb, - instance_type character varying DEFAULT 'single'::character varying NOT NULL -); - - --- --- Name: app_custom_invoicing_customers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_custom_invoicing_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: app_custom_invoicing_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.app_custom_invoicing_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_custom_invoicing_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_custom_invoicings; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_custom_invoicings ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - enable_draft_sync_hook boolean DEFAULT false NOT NULL, - enable_issuing_sync_hook boolean DEFAULT false NOT NULL -); - - --- --- Name: app_customers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: app_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.app_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_stripe_customers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_stripe_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - stripe_customer_id character varying NOT NULL, - stripe_default_payment_method_id character varying, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: app_stripe_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.app_stripe_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_stripe_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_stripes; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_stripes ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - stripe_account_id character varying NOT NULL, - stripe_livemode boolean NOT NULL, - api_key character varying NOT NULL, - stripe_webhook_id character varying NOT NULL, - webhook_secret character varying NOT NULL, - masked_api_key character varying NOT NULL -); - - --- --- Name: apps; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.apps ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - type character varying NOT NULL, - status character varying NOT NULL -); - - --- --- Name: balance_snapshots; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.balance_snapshots ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - grant_balances jsonb NOT NULL, - balance numeric NOT NULL, - overage numeric NOT NULL, - at timestamp with time zone NOT NULL, - owner_id character(26) NOT NULL, - usage jsonb -); - - --- --- Name: balance_snapshots_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.balance_snapshots ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.balance_snapshots_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: billing_customer_locks; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_customer_locks ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: billing_customer_overrides; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_customer_overrides ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - collection_alignment character varying, - invoice_auto_advance boolean, - invoice_collection_method character varying, - billing_profile_id character(26), - customer_id character(26) NOT NULL, - line_collection_period character varying, - invoice_draft_period character varying, - invoice_due_after character varying, - invoice_progressive_billing boolean, - invoice_default_tax_config jsonb -); - - --- --- Name: billing_invoice_flat_fee_line_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_flat_fee_line_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - per_unit_amount numeric NOT NULL, - category character varying DEFAULT 'regular'::character varying NOT NULL, - payment_term character varying DEFAULT 'in_advance'::character varying NOT NULL, - index bigint -); - - --- --- Name: billing_invoice_line_discounts; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_line_discounts ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - child_unique_reference_id character varying, - description character varying, - amount numeric NOT NULL, - line_id character(26) NOT NULL, - invoicing_app_external_id character varying, - reason character varying NOT NULL, - type character varying, - rounding_amount numeric, - quantity numeric, - pre_line_period_quantity numeric, - source_discount jsonb -); - - --- --- Name: billing_invoice_line_usage_discounts; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_line_usage_discounts ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - child_unique_reference_id character varying, - description character varying, - reason character varying NOT NULL, - invoicing_app_external_id character varying, - quantity numeric NOT NULL, - pre_line_period_quantity numeric, - reason_details jsonb, - line_id character(26) NOT NULL -); - - --- --- Name: billing_invoice_lines; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_lines ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - period_start timestamp with time zone NOT NULL, - period_end timestamp with time zone NOT NULL, - invoice_at timestamp with time zone NOT NULL, - type character varying NOT NULL, - status character varying NOT NULL, - currency character varying(3) NOT NULL, - quantity numeric, - tax_config jsonb, - invoice_id character(26) NOT NULL, - fee_line_config_id character(26), - usage_based_line_config_id character(26), - parent_line_id character(26), - child_unique_reference_id character varying, - amount numeric NOT NULL, - taxes_total numeric NOT NULL, - taxes_inclusive_total numeric NOT NULL, - taxes_exclusive_total numeric NOT NULL, - charges_total numeric NOT NULL, - discounts_total numeric NOT NULL, - total numeric NOT NULL, - invoicing_app_external_id character varying, - subscription_id character(26), - subscription_item_id character(26), - subscription_phase_id character(26), - line_ids character(26), - managed_by character varying NOT NULL, - ratecard_discounts jsonb, - split_line_group_id character(26) -); - - --- --- Name: billing_invoice_split_line_groups; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_split_line_groups ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - currency character varying(3) NOT NULL, - tax_config jsonb, - service_period_start timestamp with time zone NOT NULL, - service_period_end timestamp with time zone NOT NULL, - unique_reference_id character varying, - ratecard_discounts jsonb, - feature_key character varying, - price jsonb NOT NULL, - subscription_id character(26), - subscription_item_id character(26), - subscription_phase_id character(26) -); - - --- --- Name: billing_invoice_usage_based_line_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_usage_based_line_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - price_type character varying NOT NULL, - feature_key character varying, - price jsonb NOT NULL, - pre_line_period_quantity numeric, - metered_quantity numeric, - metered_pre_line_period_quantity numeric -); - - --- --- Name: billing_invoice_validation_issues; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_validation_issues ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - severity character varying NOT NULL, - code character varying, - message character varying NOT NULL, - path character varying, - component character varying NOT NULL, - dedupe_hash bytea NOT NULL, - invoice_id character(26) NOT NULL -); - - --- --- Name: billing_invoices; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoices ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - customer_id character(26) NOT NULL, - voided_at timestamp with time zone, - currency character varying(3) NOT NULL, - status character varying NOT NULL, - period_start timestamp with time zone, - period_end timestamp with time zone, - source_billing_profile_id character(26) NOT NULL, - workflow_config_id character(26) NOT NULL, - number character varying NOT NULL, - supplier_address_country character varying, - supplier_address_postal_code character varying, - supplier_address_state character varying, - supplier_address_city character varying, - supplier_address_line1 character varying, - supplier_address_line2 character varying, - supplier_address_phone_number character varying, - customer_address_country character varying, - customer_address_postal_code character varying, - customer_address_state character varying, - customer_address_city character varying, - customer_address_line1 character varying, - customer_address_line2 character varying, - customer_address_phone_number character varying, - supplier_name character varying NOT NULL, - supplier_tax_code character varying, - customer_name character varying NOT NULL, - type character varying NOT NULL, - description character varying, - issued_at timestamp with time zone, - due_at timestamp with time zone, - tax_app_id character(26) NOT NULL, - invoicing_app_id character(26) NOT NULL, - payment_app_id character(26) NOT NULL, - draft_until timestamp with time zone, - customer_usage_attribution jsonb NOT NULL, - amount numeric NOT NULL, - taxes_total numeric NOT NULL, - taxes_inclusive_total numeric NOT NULL, - taxes_exclusive_total numeric NOT NULL, - charges_total numeric NOT NULL, - discounts_total numeric NOT NULL, - total numeric NOT NULL, - invoicing_app_external_id character varying, - payment_app_external_id character varying, - collection_at timestamp with time zone, - sent_to_customer_at timestamp with time zone, - tax_app_external_id character varying, - status_details_cache jsonb, - quantity_snapshoted_at timestamp with time zone -); - - --- --- Name: billing_profiles; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_profiles ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - "default" boolean DEFAULT false NOT NULL, - workflow_config_id character(26) NOT NULL, - metadata jsonb, - supplier_address_country character varying, - supplier_address_postal_code character varying, - supplier_address_state character varying, - supplier_address_city character varying, - supplier_address_line1 character varying, - supplier_address_line2 character varying, - supplier_address_phone_number character varying, - supplier_name character varying NOT NULL, - name character varying NOT NULL, - description character varying, - supplier_tax_code character varying, - tax_app_id character(26) NOT NULL, - invoicing_app_id character(26) NOT NULL, - payment_app_id character(26) NOT NULL -); - - --- --- Name: billing_sequence_numbers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_sequence_numbers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - scope character varying NOT NULL, - last numeric NOT NULL -); - - --- --- Name: billing_sequence_numbers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.billing_sequence_numbers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.billing_sequence_numbers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: billing_workflow_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_workflow_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - collection_alignment character varying NOT NULL, - invoice_auto_advance boolean NOT NULL, - invoice_collection_method character varying NOT NULL, - line_collection_period character varying NOT NULL, - invoice_draft_period character varying NOT NULL, - invoice_due_after character varying NOT NULL, - invoice_progressive_billing boolean NOT NULL, - invoice_default_tax_settings jsonb, - tax_enabled boolean DEFAULT true NOT NULL, - tax_enforced boolean DEFAULT false NOT NULL -); - - --- --- Name: customer_subjects; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.customer_subjects ( - id bigint NOT NULL, - subject_key character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - customer_id character(26) NOT NULL, - namespace character varying NOT NULL, - deleted_at timestamp with time zone -); - - --- --- Name: customer_subjects_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.customer_subjects ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.customer_subjects_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: customers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.customers ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - currency character varying, - primary_email character varying, - billing_address_country character varying, - billing_address_postal_code character varying, - billing_address_state character varying, - billing_address_city character varying, - billing_address_line1 character varying, - billing_address_line2 character varying, - billing_address_phone_number character varying, - description character varying, - key character varying -); - - --- --- Name: entitlements; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.entitlements ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - entitlement_type character varying NOT NULL, - feature_key character varying NOT NULL, - subject_key character varying NOT NULL, - measure_usage_from timestamp with time zone, - issue_after_reset double precision, - issue_after_reset_priority smallint, - is_soft_limit boolean, - preserve_overage_at_reset boolean, - config jsonb, - usage_period_interval character varying, - usage_period_anchor timestamp with time zone, - current_usage_period_start timestamp with time zone, - current_usage_period_end timestamp with time zone, - feature_id character(26) NOT NULL, - active_from timestamp with time zone, - active_to timestamp with time zone, - annotations jsonb -); - - --- --- Name: features; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.features ( - id character(26) NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - namespace character varying NOT NULL, - name character varying NOT NULL, - key character varying NOT NULL, - meter_slug character varying, - meter_group_by_filters jsonb, - archived_at timestamp with time zone -); - - --- --- Name: grants; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.grants ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - amount numeric NOT NULL, - priority smallint DEFAULT 0 NOT NULL, - effective_at timestamp with time zone NOT NULL, - expiration jsonb NOT NULL, - expires_at timestamp with time zone NOT NULL, - voided_at timestamp with time zone, - reset_max_rollover numeric NOT NULL, - reset_min_rollover numeric NOT NULL, - recurrence_period character varying, - recurrence_anchor timestamp with time zone, - owner_id character(26) NOT NULL -); - - --- --- Name: meters; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.meters ( - id character(26) NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - key character varying NOT NULL, - description character varying, - event_type character varying NOT NULL, - value_property character varying, - group_by jsonb, - aggregation character varying NOT NULL, - namespace character varying NOT NULL, - name character varying NOT NULL, - event_from timestamp with time zone, - metadata jsonb, - deleted_at timestamp with time zone -); - - --- --- Name: notification_channel_rules; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_channel_rules ( - notification_channel_id character(26) NOT NULL, - notification_rule_id character(26) NOT NULL -); - - --- --- Name: notification_channels; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_channels ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - type character varying NOT NULL, - name character varying NOT NULL, - disabled boolean DEFAULT false, - config jsonb NOT NULL -); - - --- --- Name: notification_event_delivery_status; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_event_delivery_status ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - event_id character varying NOT NULL, - channel_id character varying NOT NULL, - state character varying DEFAULT 'PENDING'::character varying NOT NULL, - reason character varying -); - - --- --- Name: notification_event_delivery_status_events; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_event_delivery_status_events ( - notification_event_delivery_status_id character(26) NOT NULL, - notification_event_id character(26) NOT NULL -); - - --- --- Name: notification_events; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_events ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - type character varying NOT NULL, - payload jsonb NOT NULL, - annotations jsonb, - rule_id character(26) NOT NULL -); - - --- --- Name: notification_rules; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_rules ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - type character varying NOT NULL, - name character varying NOT NULL, - disabled boolean DEFAULT false, - config jsonb NOT NULL -); - - --- --- Name: plan_addons; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.plan_addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - annotations jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - from_plan_phase character varying NOT NULL, - max_quantity bigint, - addon_id character(26) NOT NULL, - plan_id character(26) NOT NULL -); - - --- --- Name: plan_phases; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.plan_phases ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - plan_id character(26) NOT NULL, - index smallint NOT NULL, - duration character varying -); - - --- --- Name: plan_rate_cards; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.plan_rate_cards ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - type character varying NOT NULL, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - feature_id character(26), - phase_id character(26) NOT NULL, - discounts jsonb -); - - --- --- Name: plans; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.plans ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - version bigint NOT NULL, - currency character varying DEFAULT 'USD'::character varying NOT NULL, - effective_from timestamp with time zone, - effective_to timestamp with time zone, - billing_cadence character varying NOT NULL, - pro_rating_config jsonb NOT NULL -); - - --- --- Name: schema_om; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.schema_om ( - version bigint NOT NULL, - dirty boolean NOT NULL -); - - --- --- Name: subjects; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subjects ( - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - id character(26) NOT NULL, - key character varying NOT NULL, - display_name character varying, - metadata jsonb, - stripe_customer_id character varying, - namespace character varying NOT NULL -); - - --- --- Name: subscription_addon_quantities; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscription_addon_quantities ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - active_from timestamp with time zone NOT NULL, - quantity bigint DEFAULT 1 NOT NULL, - subscription_addon_id character(26) NOT NULL -); - - --- --- Name: subscription_addons; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscription_addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - addon_id character(26) NOT NULL, - subscription_id character(26) NOT NULL -); - - --- --- Name: subscription_items; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscription_items ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - active_from timestamp with time zone NOT NULL, - active_to timestamp with time zone, - key character varying NOT NULL, - active_from_override_relative_to_phase_start character varying, - active_to_override_relative_to_phase_start character varying, - name character varying NOT NULL, - description character varying, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - entitlement_id character(26), - phase_id character(26) NOT NULL, - restarts_billing_period boolean, - discounts jsonb, - annotations jsonb -); - - --- --- Name: subscription_phases; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscription_phases ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - key character varying NOT NULL, - name character varying NOT NULL, - description character varying, - active_from timestamp with time zone NOT NULL, - subscription_id character(26) NOT NULL, - sort_hint smallint -); - - --- --- Name: subscriptions; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscriptions ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - active_from timestamp with time zone NOT NULL, - active_to timestamp with time zone, - currency character varying NOT NULL, - customer_id character(26) NOT NULL, - name character varying DEFAULT 'Subscription'::character varying NOT NULL, - description character varying, - plan_id character(26), - billing_cadence character varying NOT NULL, - pro_rating_config jsonb NOT NULL, - billing_anchor timestamp with time zone NOT NULL -); - - --- --- Name: usage_resets; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.usage_resets ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - reset_time timestamp with time zone NOT NULL, - entitlement_id character(26) NOT NULL, - anchor timestamp with time zone NOT NULL -); - - --- --- Name: addon_rate_cards addon_rate_cards_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_pkey PRIMARY KEY (id); - - --- --- Name: addons addons_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.addons - ADD CONSTRAINT addons_pkey PRIMARY KEY (id); - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_custom_invoicings app_custom_invoicings_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicings - ADD CONSTRAINT app_custom_invoicings_pkey PRIMARY KEY (id); - - --- --- Name: app_customers app_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_stripe_customers app_stripe_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_stripes app_stripes_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripes - ADD CONSTRAINT app_stripes_pkey PRIMARY KEY (id); - - --- --- Name: apps apps_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.apps - ADD CONSTRAINT apps_pkey PRIMARY KEY (id); - - --- --- Name: balance_snapshots balance_snapshots_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.balance_snapshots - ADD CONSTRAINT balance_snapshots_pkey PRIMARY KEY (id); - - --- --- Name: billing_customer_locks billing_customer_locks_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_locks - ADD CONSTRAINT billing_customer_locks_pkey PRIMARY KEY (id); - - --- --- Name: billing_customer_overrides billing_customer_overrides_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_flat_fee_line_configs billing_invoice_flat_fee_line_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_flat_fee_line_configs - ADD CONSTRAINT billing_invoice_flat_fee_line_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_line_discounts billing_invoice_line_discounts_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_discounts - ADD CONSTRAINT billing_invoice_line_discounts_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_line_usage_discounts billing_invoice_line_usage_discounts_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_usage_discounts - ADD CONSTRAINT billing_invoice_line_usage_discounts_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_lines billing_invoice_lines_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_usage_based_line_configs billing_invoice_usage_based_line_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_usage_based_line_configs - ADD CONSTRAINT billing_invoice_usage_based_line_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_validation_issues billing_invoice_validation_issues_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_validation_issues - ADD CONSTRAINT billing_invoice_validation_issues_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoices billing_invoices_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_pkey PRIMARY KEY (id); - - --- --- Name: billing_profiles billing_profiles_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_pkey PRIMARY KEY (id); - - --- --- Name: billing_sequence_numbers billing_sequence_numbers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_sequence_numbers - ADD CONSTRAINT billing_sequence_numbers_pkey PRIMARY KEY (id); - - --- --- Name: billing_workflow_configs billing_workflow_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_workflow_configs - ADD CONSTRAINT billing_workflow_configs_pkey PRIMARY KEY (id); - - --- --- Name: customer_subjects customer_subjects_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.customer_subjects - ADD CONSTRAINT customer_subjects_pkey PRIMARY KEY (id); - - --- --- Name: customers customers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.customers - ADD CONSTRAINT customers_pkey PRIMARY KEY (id); - - --- --- Name: entitlements entitlements_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.entitlements - ADD CONSTRAINT entitlements_pkey PRIMARY KEY (id); - - --- --- Name: features features_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.features - ADD CONSTRAINT features_pkey PRIMARY KEY (id); - - --- --- Name: grants grants_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.grants - ADD CONSTRAINT grants_pkey PRIMARY KEY (id); - - --- --- Name: meters meters_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.meters - ADD CONSTRAINT meters_pkey PRIMARY KEY (id); - - --- --- Name: notification_channel_rules notification_channel_rules_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_pkey PRIMARY KEY (notification_channel_id, notification_rule_id); - - --- --- Name: notification_channels notification_channels_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_channels - ADD CONSTRAINT notification_channels_pkey PRIMARY KEY (id); - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_pkey PRIMARY KEY (notification_event_delivery_status_id, notification_event_id); - - --- --- Name: notification_event_delivery_status notification_event_delivery_status_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_event_delivery_status - ADD CONSTRAINT notification_event_delivery_status_pkey PRIMARY KEY (id); - - --- --- Name: notification_events notification_events_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_events - ADD CONSTRAINT notification_events_pkey PRIMARY KEY (id); - - --- --- Name: notification_rules notification_rules_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_rules - ADD CONSTRAINT notification_rules_pkey PRIMARY KEY (id); - - --- --- Name: plan_addons plan_addons_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_pkey PRIMARY KEY (id); - - --- --- Name: plan_phases plan_phases_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_phases - ADD CONSTRAINT plan_phases_pkey PRIMARY KEY (id); - - --- --- Name: plan_rate_cards plan_rate_cards_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_pkey PRIMARY KEY (id); - - --- --- Name: plans plans_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plans - ADD CONSTRAINT plans_pkey PRIMARY KEY (id); - - --- --- Name: schema_om schema_om_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.schema_om - ADD CONSTRAINT schema_om_pkey PRIMARY KEY (version); - - --- --- Name: subjects subjects_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subjects - ADD CONSTRAINT subjects_pkey PRIMARY KEY (id); - - --- --- Name: subscription_addon_quantities subscription_addon_quantities_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addon_quantities - ADD CONSTRAINT subscription_addon_quantities_pkey PRIMARY KEY (id); - - --- --- Name: subscription_addons subscription_addons_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_pkey PRIMARY KEY (id); - - --- --- Name: subscription_items subscription_items_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_pkey PRIMARY KEY (id); - - --- --- Name: subscription_phases subscription_phases_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_phases - ADD CONSTRAINT subscription_phases_pkey PRIMARY KEY (id); - - --- --- Name: subscriptions subscriptions_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_pkey PRIMARY KEY (id); - - --- --- Name: usage_resets usage_resets_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.usage_resets - ADD CONSTRAINT usage_resets_pkey PRIMARY KEY (id); - - --- --- Name: addon_annotations; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX addon_annotations ON public.addons USING gin (annotations); - - --- --- Name: addon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addon_id ON public.addons USING btree (id); - - --- --- Name: addon_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX addon_namespace ON public.addons USING btree (namespace); - - --- --- Name: addon_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addon_namespace_id ON public.addons USING btree (namespace, id); - - --- --- Name: addon_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addon_namespace_key_deleted_at ON public.addons USING btree (namespace, key, deleted_at); - - --- --- Name: addon_namespace_key_version; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addon_namespace_key_version ON public.addons USING btree (namespace, key, version) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_addon_id_feature_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_addon_id_feature_key ON public.addon_rate_cards USING btree (addon_id, feature_key) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_addon_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_addon_id_key ON public.addon_rate_cards USING btree (addon_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_id ON public.addon_rate_cards USING btree (id); - - --- --- Name: addonratecard_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX addonratecard_namespace ON public.addon_rate_cards USING btree (namespace); - - --- --- Name: addonratecard_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_namespace_id ON public.addon_rate_cards USING btree (namespace, id); - - --- --- Name: addonratecard_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_namespace_key_deleted_at ON public.addon_rate_cards USING btree (namespace, key, deleted_at); - - --- --- Name: app_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX app_id ON public.apps USING btree (id); - - --- --- Name: app_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX app_namespace ON public.apps USING btree (namespace); - - --- --- Name: app_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX app_namespace_id ON public.apps USING btree (namespace, id); - - --- --- Name: app_namespace_type; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX app_namespace_type ON public.apps USING btree (namespace, type); - - --- --- Name: appcustomer_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appcustomer_namespace ON public.app_customers USING btree (namespace); - - --- --- Name: appcustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appcustomer_namespace_app_id_customer_id ON public.app_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: appcustominvoicing_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appcustominvoicing_id ON public.app_custom_invoicings USING btree (id); - - --- --- Name: appcustominvoicing_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appcustominvoicing_namespace ON public.app_custom_invoicings USING btree (namespace); - - --- --- Name: appcustominvoicing_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appcustominvoicing_namespace_id ON public.app_custom_invoicings USING btree (namespace, id); - - --- --- Name: appcustominvoicingcustomer_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appcustominvoicingcustomer_namespace ON public.app_custom_invoicing_customers USING btree (namespace); - - --- --- Name: appcustominvoicingcustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appcustominvoicingcustomer_namespace_app_id_customer_id ON public.app_custom_invoicing_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: appstripe_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appstripe_id ON public.app_stripes USING btree (id); - - --- --- Name: appstripe_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appstripe_namespace ON public.app_stripes USING btree (namespace); - - --- --- Name: appstripe_namespace_stripe_account_id_stripe_livemode; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appstripe_namespace_stripe_account_id_stripe_livemode ON public.app_stripes USING btree (namespace, stripe_account_id, stripe_livemode) WHERE (deleted_at IS NULL); - - --- --- Name: appstripecustomer_app_id_stripe_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appstripecustomer_app_id_stripe_customer_id ON public.app_stripe_customers USING btree (app_id, stripe_customer_id); - - --- --- Name: appstripecustomer_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appstripecustomer_namespace ON public.app_stripe_customers USING btree (namespace); - - --- --- Name: appstripecustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appstripecustomer_namespace_app_id_customer_id ON public.app_stripe_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: balancesnapshot_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX balancesnapshot_namespace ON public.balance_snapshots USING btree (namespace); - - --- --- Name: balancesnapshot_namespace_owner_id_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX balancesnapshot_namespace_owner_id_at ON public.balance_snapshots USING btree (namespace, owner_id, at) WHERE (deleted_at IS NULL); - - --- --- Name: billing_customer_overrides_customer_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_customer_overrides_customer_id_key ON public.billing_customer_overrides USING btree (customer_id); - - --- --- Name: billing_invoices_workflow_config_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_invoices_workflow_config_id_key ON public.billing_invoices USING btree (workflow_config_id); - - --- --- Name: billing_profiles_workflow_config_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_profiles_workflow_config_id_key ON public.billing_profiles USING btree (workflow_config_id); - - --- --- Name: billingcustomerlock_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomerlock_id ON public.billing_customer_locks USING btree (id); - - --- --- Name: billingcustomerlock_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingcustomerlock_namespace ON public.billing_customer_locks USING btree (namespace); - - --- --- Name: billingcustomerlock_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomerlock_namespace_customer_id ON public.billing_customer_locks USING btree (namespace, customer_id); - - --- --- Name: billingcustomeroverride_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_id ON public.billing_customer_overrides USING btree (id); - - --- --- Name: billingcustomeroverride_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingcustomeroverride_namespace ON public.billing_customer_overrides USING btree (namespace); - - --- --- Name: billingcustomeroverride_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_namespace_customer_id ON public.billing_customer_overrides USING btree (namespace, customer_id); - - --- --- Name: billingcustomeroverride_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_namespace_id ON public.billing_customer_overrides USING btree (namespace, id); - - --- --- Name: billinginvoice_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoice_id ON public.billing_invoices USING btree (id); - - --- --- Name: billinginvoice_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace ON public.billing_invoices USING btree (namespace); - - --- --- Name: billinginvoice_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_customer_id ON public.billing_invoices USING btree (namespace, customer_id); - - --- --- Name: billinginvoice_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_id ON public.billing_invoices USING btree (namespace, id); - - --- --- Name: billinginvoice_namespace_status; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_status ON public.billing_invoices USING btree (namespace, status); - - --- --- Name: billinginvoice_status_details_cache; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_status_details_cache ON public.billing_invoices USING gin (status_details_cache); - - --- --- Name: billinginvoiceflatfeelineconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceflatfeelineconfig_id ON public.billing_invoice_flat_fee_line_configs USING btree (id); - - --- --- Name: billinginvoiceflatfeelineconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceflatfeelineconfig_namespace ON public.billing_invoice_flat_fee_line_configs USING btree (namespace); - - --- --- Name: billinginvoiceline_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_id ON public.billing_invoice_lines USING btree (id); - - --- --- Name: billinginvoiceline_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace ON public.billing_invoice_lines USING btree (namespace); - - --- --- Name: billinginvoiceline_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_namespace_id ON public.billing_invoice_lines USING btree (namespace, id); - - --- --- Name: billinginvoiceline_namespace_invoice_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_invoice_id ON public.billing_invoice_lines USING btree (namespace, invoice_id); - - --- --- Name: billinginvoiceline_namespace_parent_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_parent_line_id ON public.billing_invoice_lines USING btree (namespace, parent_line_id); - - --- --- Name: billinginvoiceline_namespace_parent_line_id_child_unique_refere; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_namespace_parent_line_id_child_unique_refere ON public.billing_invoice_lines USING btree (namespace, parent_line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoiceline_namespace_subscription_id_subscription_phase; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_subscription_id_subscription_phase ON public.billing_invoice_lines USING btree (namespace, subscription_id, subscription_phase_id, subscription_item_id); - - --- --- Name: billinginvoicelinediscount_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelinediscount_id ON public.billing_invoice_line_discounts USING btree (id); - - --- --- Name: billinginvoicelinediscount_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelinediscount_namespace ON public.billing_invoice_line_discounts USING btree (namespace); - - --- --- Name: billinginvoicelinediscount_namespace_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelinediscount_namespace_line_id ON public.billing_invoice_line_discounts USING btree (namespace, line_id); - - --- --- Name: billinginvoicelinediscount_namespace_line_id_child_unique_refer; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelinediscount_namespace_line_id_child_unique_refer ON public.billing_invoice_line_discounts USING btree (namespace, line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoicelineusagediscount_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelineusagediscount_id ON public.billing_invoice_line_usage_discounts USING btree (id); - - --- --- Name: billinginvoicelineusagediscount_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelineusagediscount_namespace ON public.billing_invoice_line_usage_discounts USING btree (namespace); - - --- --- Name: billinginvoicelineusagediscount_namespace_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelineusagediscount_namespace_line_id ON public.billing_invoice_line_usage_discounts USING btree (namespace, line_id); - - --- --- Name: billinginvoicelineusagediscount_namespace_line_id_child_unique_; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelineusagediscount_namespace_line_id_child_unique_ ON public.billing_invoice_line_usage_discounts USING btree (namespace, line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoicesplitlinegroup_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_id ON public.billing_invoice_split_line_groups USING btree (id); - - --- --- Name: billinginvoicesplitlinegroup_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicesplitlinegroup_namespace ON public.billing_invoice_split_line_groups USING btree (namespace); - - --- --- Name: billinginvoicesplitlinegroup_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_namespace_id ON public.billing_invoice_split_line_groups USING btree (namespace, id); - - --- --- Name: billinginvoicesplitlinegroup_namespace_unique_reference_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_namespace_unique_reference_id ON public.billing_invoice_split_line_groups USING btree (namespace, unique_reference_id) WHERE ((unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoiceusagebasedlineconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceusagebasedlineconfig_id ON public.billing_invoice_usage_based_line_configs USING btree (id); - - --- --- Name: billinginvoiceusagebasedlineconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceusagebasedlineconfig_namespace ON public.billing_invoice_usage_based_line_configs USING btree (namespace); - - --- --- Name: billinginvoicevalidationissue_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicevalidationissue_id ON public.billing_invoice_validation_issues USING btree (id); - - --- --- Name: billinginvoicevalidationissue_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicevalidationissue_namespace ON public.billing_invoice_validation_issues USING btree (namespace); - - --- --- Name: billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash ON public.billing_invoice_validation_issues USING btree (namespace, invoice_id, dedupe_hash); - - --- --- Name: billingprofile_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_id ON public.billing_profiles USING btree (id); - - --- --- Name: billingprofile_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingprofile_namespace ON public.billing_profiles USING btree (namespace); - - --- --- Name: billingprofile_namespace_default; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_namespace_default ON public.billing_profiles USING btree (namespace, "default") WHERE ("default" AND (deleted_at IS NULL)); - - --- --- Name: billingprofile_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_namespace_id ON public.billing_profiles USING btree (namespace, id); - - --- --- Name: billingsequencenumbers_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingsequencenumbers_namespace ON public.billing_sequence_numbers USING btree (namespace); - - --- --- Name: billingsequencenumbers_namespace_scope; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingsequencenumbers_namespace_scope ON public.billing_sequence_numbers USING btree (namespace, scope); - - --- --- Name: billingworkflowconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingworkflowconfig_id ON public.billing_workflow_configs USING btree (id); - - --- --- Name: billingworkflowconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingworkflowconfig_namespace ON public.billing_workflow_configs USING btree (namespace); - - --- --- Name: billingworkflowconfig_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingworkflowconfig_namespace_id ON public.billing_workflow_configs USING btree (namespace, id); - - --- --- Name: customer_created_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customer_created_at ON public.customers USING btree (created_at); - - --- --- Name: customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX customer_id ON public.customers USING btree (id); - - --- --- Name: customer_name; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customer_name ON public.customers USING btree (name); - - --- --- Name: customer_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customer_namespace ON public.customers USING btree (namespace); - - --- --- Name: customer_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX customer_namespace_id ON public.customers USING btree (namespace, id); - - --- --- Name: customer_namespace_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX customer_namespace_key ON public.customers USING btree (namespace, key) WHERE (deleted_at IS NULL); - - --- --- Name: customer_primary_email; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customer_primary_email ON public.customers USING btree (primary_email); - - --- --- Name: customersubjects_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customersubjects_namespace ON public.customer_subjects USING btree (namespace); - - --- --- Name: customersubjects_namespace_customer_id_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customersubjects_namespace_customer_id_deleted_at ON public.customer_subjects USING btree (namespace, customer_id, deleted_at); - - --- --- Name: customersubjects_namespace_subject_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX customersubjects_namespace_subject_key ON public.customer_subjects USING btree (namespace, subject_key) WHERE (deleted_at IS NULL); - - --- --- Name: entitlement_created_at_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX entitlement_created_at_id ON public.entitlements USING btree (created_at, id); - - --- --- Name: entitlement_current_usage_period_end_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_current_usage_period_end_deleted_at ON public.entitlements USING btree (current_usage_period_end, deleted_at); - - --- --- Name: entitlement_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX entitlement_id ON public.entitlements USING btree (id); - - --- --- Name: entitlement_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace ON public.entitlements USING btree (namespace); - - --- --- Name: entitlement_namespace_current_usage_period_end; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_current_usage_period_end ON public.entitlements USING btree (namespace, current_usage_period_end); - - --- --- Name: entitlement_namespace_feature_id_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_feature_id_id ON public.entitlements USING btree (namespace, feature_id, id); - - --- --- Name: entitlement_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_id ON public.entitlements USING btree (namespace, id); - - --- --- Name: entitlement_namespace_id_subject_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_id_subject_key ON public.entitlements USING btree (namespace, id, subject_key); - - --- --- Name: entitlement_namespace_subject_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_subject_key ON public.entitlements USING btree (namespace, subject_key); - - --- --- Name: feature_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX feature_id ON public.features USING btree (id); - - --- --- Name: feature_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX feature_namespace_id ON public.features USING btree (namespace, id); - - --- --- Name: feature_namespace_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX feature_namespace_key ON public.features USING btree (namespace, key) WHERE (archived_at IS NULL); - - --- --- Name: grant_effective_at_expires_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX grant_effective_at_expires_at ON public.grants USING btree (effective_at, expires_at); - - --- --- Name: grant_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX grant_id ON public.grants USING btree (id); - - --- --- Name: grant_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX grant_namespace ON public.grants USING btree (namespace); - - --- --- Name: grant_namespace_owner_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX grant_namespace_owner_id ON public.grants USING btree (namespace, owner_id); - - --- --- Name: meter_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX meter_id ON public.meters USING btree (id); - - --- --- Name: meter_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX meter_namespace ON public.meters USING btree (namespace); - - --- --- Name: meter_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX meter_namespace_id ON public.meters USING btree (namespace, id); - - --- --- Name: meter_namespace_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX meter_namespace_key ON public.meters USING btree (namespace, key) WHERE (deleted_at IS NULL); - - --- --- Name: meter_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX meter_namespace_key_deleted_at ON public.meters USING btree (namespace, key, deleted_at); - - --- --- Name: notificationchannel_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX notificationchannel_id ON public.notification_channels USING btree (id); - - --- --- Name: notificationchannel_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationchannel_namespace ON public.notification_channels USING btree (namespace); - - --- --- Name: notificationchannel_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationchannel_namespace_id ON public.notification_channels USING btree (namespace, id); - - --- --- Name: notificationchannel_namespace_type; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationchannel_namespace_type ON public.notification_channels USING btree (namespace, type); - - --- --- Name: notificationevent_annotations; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationevent_annotations ON public.notification_events USING gin (annotations); - - --- --- Name: notificationevent_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX notificationevent_id ON public.notification_events USING btree (id); - - --- --- Name: notificationevent_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationevent_namespace ON public.notification_events USING btree (namespace); - - --- --- Name: notificationevent_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationevent_namespace_id ON public.notification_events USING btree (namespace, id); - - --- --- Name: notificationevent_namespace_type; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationevent_namespace_type ON public.notification_events USING btree (namespace, type); - - --- --- Name: notificationeventdeliverystatus_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX notificationeventdeliverystatus_id ON public.notification_event_delivery_status USING btree (id); - - --- --- Name: notificationeventdeliverystatus_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationeventdeliverystatus_namespace ON public.notification_event_delivery_status USING btree (namespace); - - --- --- Name: notificationeventdeliverystatus_namespace_event_id_channel_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationeventdeliverystatus_namespace_event_id_channel_id ON public.notification_event_delivery_status USING btree (namespace, event_id, channel_id); - - --- --- Name: notificationeventdeliverystatus_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationeventdeliverystatus_namespace_id ON public.notification_event_delivery_status USING btree (namespace, id); - - --- --- Name: notificationeventdeliverystatus_namespace_state; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationeventdeliverystatus_namespace_state ON public.notification_event_delivery_status USING btree (namespace, state); - - --- --- Name: notificationrule_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX notificationrule_id ON public.notification_rules USING btree (id); - - --- --- Name: notificationrule_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationrule_namespace ON public.notification_rules USING btree (namespace); - - --- --- Name: notificationrule_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationrule_namespace_id ON public.notification_rules USING btree (namespace, id); - - --- --- Name: notificationrule_namespace_type; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationrule_namespace_type ON public.notification_rules USING btree (namespace, type); - - --- --- Name: plan_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX plan_id ON public.plans USING btree (id); - - --- --- Name: plan_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX plan_namespace ON public.plans USING btree (namespace); - - --- --- Name: plan_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX plan_namespace_id ON public.plans USING btree (namespace, id); - - --- --- Name: plan_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX plan_namespace_key_deleted_at ON public.plans USING btree (namespace, key, deleted_at); - - --- --- Name: plan_namespace_key_version; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX plan_namespace_key_version ON public.plans USING btree (namespace, key, version) WHERE (deleted_at IS NULL); - - --- --- Name: planaddon_annotations; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planaddon_annotations ON public.plan_addons USING gin (annotations); - - --- --- Name: planaddon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planaddon_id ON public.plan_addons USING btree (id); - - --- --- Name: planaddon_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planaddon_namespace ON public.plan_addons USING btree (namespace); - - --- --- Name: planaddon_namespace_plan_id_addon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planaddon_namespace_plan_id_addon_id ON public.plan_addons USING btree (namespace, plan_id, addon_id) WHERE (deleted_at IS NULL); - - --- --- Name: planphase_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_id ON public.plan_phases USING btree (id); - - --- --- Name: planphase_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planphase_namespace ON public.plan_phases USING btree (namespace); - - --- --- Name: planphase_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_namespace_id ON public.plan_phases USING btree (namespace, id); - - --- --- Name: planphase_namespace_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planphase_namespace_key ON public.plan_phases USING btree (namespace, key); - - --- --- Name: planphase_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_namespace_key_deleted_at ON public.plan_phases USING btree (namespace, key, deleted_at); - - --- --- Name: planphase_plan_id_index; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_plan_id_index ON public.plan_phases USING btree (plan_id, index) WHERE (deleted_at IS NULL); - - --- --- Name: planphase_plan_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_plan_id_key ON public.plan_phases USING btree (plan_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: planratecard_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_id ON public.plan_rate_cards USING btree (id); - - --- --- Name: planratecard_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planratecard_namespace ON public.plan_rate_cards USING btree (namespace); - - --- --- Name: planratecard_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_namespace_id ON public.plan_rate_cards USING btree (namespace, id); - - --- --- Name: planratecard_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_namespace_key_deleted_at ON public.plan_rate_cards USING btree (namespace, key, deleted_at); - - --- --- Name: planratecard_phase_id_feature_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_phase_id_feature_key ON public.plan_rate_cards USING btree (phase_id, feature_key) WHERE (deleted_at IS NULL); - - --- --- Name: planratecard_phase_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_phase_id_key ON public.plan_rate_cards USING btree (phase_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: subject_display_name; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subject_display_name ON public.subjects USING btree (display_name); - - --- --- Name: subject_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subject_id ON public.subjects USING btree (id); - - --- --- Name: subject_key_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subject_key_namespace ON public.subjects USING btree (key, namespace); - - --- --- Name: subject_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subject_namespace ON public.subjects USING btree (namespace); - - --- --- Name: subscription_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscription_id ON public.subscriptions USING btree (id); - - --- --- Name: subscription_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscription_namespace ON public.subscriptions USING btree (namespace); - - --- --- Name: subscription_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscription_namespace_customer_id ON public.subscriptions USING btree (namespace, customer_id); - - --- --- Name: subscription_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscription_namespace_id ON public.subscriptions USING btree (namespace, id); - - --- --- Name: subscriptionaddon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscriptionaddon_id ON public.subscription_addons USING btree (id); - - --- --- Name: subscriptionaddon_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionaddon_namespace ON public.subscription_addons USING btree (namespace); - - --- --- Name: subscriptionaddonquantity_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscriptionaddonquantity_id ON public.subscription_addon_quantities USING btree (id); - - --- --- Name: subscriptionaddonquantity_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionaddonquantity_namespace ON public.subscription_addon_quantities USING btree (namespace); - - --- --- Name: subscriptionaddonquantity_subscription_addon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionaddonquantity_subscription_addon_id ON public.subscription_addon_quantities USING btree (subscription_addon_id); - - --- --- Name: subscriptionitem_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscriptionitem_id ON public.subscription_items USING btree (id); - - --- --- Name: subscriptionitem_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionitem_namespace ON public.subscription_items USING btree (namespace); - - --- --- Name: subscriptionitem_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionitem_namespace_id ON public.subscription_items USING btree (namespace, id); - - --- --- Name: subscriptionitem_namespace_phase_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionitem_namespace_phase_id_key ON public.subscription_items USING btree (namespace, phase_id, key); - - --- --- Name: subscriptionphase_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscriptionphase_id ON public.subscription_phases USING btree (id); - - --- --- Name: subscriptionphase_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionphase_namespace ON public.subscription_phases USING btree (namespace); - - --- --- Name: subscriptionphase_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionphase_namespace_id ON public.subscription_phases USING btree (namespace, id); - - --- --- Name: subscriptionphase_namespace_subscription_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionphase_namespace_subscription_id ON public.subscription_phases USING btree (namespace, subscription_id); - - --- --- Name: subscriptionphase_namespace_subscription_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionphase_namespace_subscription_id_key ON public.subscription_phases USING btree (namespace, subscription_id, key); - - --- --- Name: usagereset_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX usagereset_id ON public.usage_resets USING btree (id); - - --- --- Name: usagereset_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX usagereset_namespace ON public.usage_resets USING btree (namespace); - - --- --- Name: usagereset_namespace_entitlement_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX usagereset_namespace_entitlement_id ON public.usage_resets USING btree (namespace, entitlement_id); - - --- --- Name: usagereset_namespace_entitlement_id_reset_time; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX usagereset_namespace_entitlement_id_reset_time ON public.usage_resets USING btree (namespace, entitlement_id, reset_time); - - --- --- Name: subscription_items trigger_delete_entitlement_on_subscription_item_delete; Type: TRIGGER; Schema: public; Owner: - --- - -CREATE TRIGGER trigger_delete_entitlement_on_subscription_item_delete AFTER DELETE ON public.subscription_items FOR EACH ROW EXECUTE FUNCTION public.delete_entitlement_on_subscription_item_delete(); - - --- --- Name: addon_rate_cards addon_rate_cards_addons_ratecards; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_addons_ratecards FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: addon_rate_cards addon_rate_cards_features_addon_ratecard; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_features_addon_ratecard FOREIGN KEY (feature_id) REFERENCES public.features(id) ON DELETE SET NULL; - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_app_custom_invoicings_customer_a; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_app_custom_invoicings_customer_a FOREIGN KEY (app_id) REFERENCES public.app_custom_invoicings(id) ON DELETE CASCADE; - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_customers_customer; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_customers_customer FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_custom_invoicings app_custom_invoicings_apps_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicings - ADD CONSTRAINT app_custom_invoicings_apps_app FOREIGN KEY (id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: app_customers app_customers_apps_customer_apps; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_apps_customer_apps FOREIGN KEY (app_id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: app_customers app_customers_customers_apps; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_customers_apps FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_stripe_customers app_stripe_customers_app_stripes_customer_apps; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_app_stripes_customer_apps FOREIGN KEY (app_id) REFERENCES public.app_stripes(id) ON DELETE CASCADE; - - --- --- Name: app_stripe_customers app_stripe_customers_customers_customer; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_customers_customer FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_stripes app_stripes_apps_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripes - ADD CONSTRAINT app_stripes_apps_app FOREIGN KEY (id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: balance_snapshots balance_snapshots_entitlements_balance_snapshot; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.balance_snapshots - ADD CONSTRAINT balance_snapshots_entitlements_balance_snapshot FOREIGN KEY (owner_id) REFERENCES public.entitlements(id) ON DELETE CASCADE; - - --- --- Name: billing_customer_overrides billing_customer_overrides_billing_profiles_billing_customer_ov; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_billing_profiles_billing_customer_ov FOREIGN KEY (billing_profile_id) REFERENCES public.billing_profiles(id) ON DELETE SET NULL; - - --- --- Name: billing_customer_overrides billing_customer_overrides_customers_billing_customer_override; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_customers_billing_customer_override FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_line_discounts billing_invoice_line_discounts_billing_invoice_lines_line_amoun; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_discounts - ADD CONSTRAINT billing_invoice_line_discounts_billing_invoice_lines_line_amoun FOREIGN KEY (line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_line_usage_discounts billing_invoice_line_usage_discounts_billing_invoice_lines_line; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_usage_discounts - ADD CONSTRAINT billing_invoice_line_usage_discounts_billing_invoice_lines_line FOREIGN KEY (line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_flat_fee_line_configs_fla; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_flat_fee_line_configs_fla FOREIGN KEY (fee_line_config_id) REFERENCES public.billing_invoice_flat_fee_line_configs(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_lines_detailed_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_lines_detailed_lines FOREIGN KEY (parent_line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_split_line_groups_billing; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_split_line_groups_billing FOREIGN KEY (split_line_group_id) REFERENCES public.billing_invoice_split_line_groups(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_usage_based_line_configs_; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_usage_based_line_configs_ FOREIGN KEY (usage_based_line_config_id) REFERENCES public.billing_invoice_usage_based_line_configs(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoices_billing_invoice_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoices_billing_invoice_lines FOREIGN KEY (invoice_id) REFERENCES public.billing_invoices(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscription_items_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscription_items_billing_lines FOREIGN KEY (subscription_item_id) REFERENCES public.subscription_items(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscription_phases_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscription_phases_billing_lines FOREIGN KEY (subscription_phase_id) REFERENCES public.subscription_phases(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscriptions_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscriptions_billing_lines FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscription_items_billing_sp; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscription_items_billing_sp FOREIGN KEY (subscription_item_id) REFERENCES public.subscription_items(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscription_phases_billing_s; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscription_phases_billing_s FOREIGN KEY (subscription_phase_id) REFERENCES public.subscription_phases(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscriptions_billing_split_l; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscriptions_billing_split_l FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_validation_issues billing_invoice_validation_issues_billing_invoices_billing_invo; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_validation_issues - ADD CONSTRAINT billing_invoice_validation_issues_billing_invoices_billing_invo FOREIGN KEY (invoice_id) REFERENCES public.billing_invoices(id) ON DELETE CASCADE; - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_invoicing_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_invoicing_app FOREIGN KEY (invoicing_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_payment_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_payment_app FOREIGN KEY (payment_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_tax_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_tax_app FOREIGN KEY (tax_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_billing_profiles_billing_invoices; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_billing_profiles_billing_invoices FOREIGN KEY (source_billing_profile_id) REFERENCES public.billing_profiles(id); - - --- --- Name: billing_invoices billing_invoices_billing_workflow_configs_billing_invoices; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_billing_workflow_configs_billing_invoices FOREIGN KEY (workflow_config_id) REFERENCES public.billing_workflow_configs(id); - - --- --- Name: billing_invoices billing_invoices_customers_billing_invoice; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_customers_billing_invoice FOREIGN KEY (customer_id) REFERENCES public.customers(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_invoicing_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_invoicing_app FOREIGN KEY (invoicing_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_payment_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_payment_app FOREIGN KEY (payment_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_tax_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_tax_app FOREIGN KEY (tax_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_billing_workflow_configs_billing_profile; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_billing_workflow_configs_billing_profile FOREIGN KEY (workflow_config_id) REFERENCES public.billing_workflow_configs(id); - - --- --- Name: customer_subjects customer_subjects_customers_subjects; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.customer_subjects - ADD CONSTRAINT customer_subjects_customers_subjects FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: entitlements entitlements_features_entitlement; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.entitlements - ADD CONSTRAINT entitlements_features_entitlement FOREIGN KEY (feature_id) REFERENCES public.features(id); - - --- --- Name: grants grants_entitlements_grant; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.grants - ADD CONSTRAINT grants_entitlements_grant FOREIGN KEY (owner_id) REFERENCES public.entitlements(id) ON DELETE CASCADE; - - --- --- Name: notification_channel_rules notification_channel_rules_notification_channel_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_notification_channel_id FOREIGN KEY (notification_channel_id) REFERENCES public.notification_channels(id) ON DELETE CASCADE; - - --- --- Name: notification_channel_rules notification_channel_rules_notification_rule_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_notification_rule_id FOREIGN KEY (notification_rule_id) REFERENCES public.notification_rules(id) ON DELETE CASCADE; - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_notification_event_de; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_notification_event_de FOREIGN KEY (notification_event_delivery_status_id) REFERENCES public.notification_event_delivery_status(id) ON DELETE CASCADE; - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_notification_event_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_notification_event_id FOREIGN KEY (notification_event_id) REFERENCES public.notification_events(id) ON DELETE CASCADE; - - --- --- Name: notification_events notification_events_notification_rules_events; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_events - ADD CONSTRAINT notification_events_notification_rules_events FOREIGN KEY (rule_id) REFERENCES public.notification_rules(id); - - --- --- Name: plan_addons plan_addons_addons_plans; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_addons_plans FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: plan_addons plan_addons_plans_addons; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_plans_addons FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE CASCADE; - - --- --- Name: plan_phases plan_phases_plans_phases; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_phases - ADD CONSTRAINT plan_phases_plans_phases FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE CASCADE; - - --- --- Name: plan_rate_cards plan_rate_cards_features_ratecard; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_features_ratecard FOREIGN KEY (feature_id) REFERENCES public.features(id) ON DELETE SET NULL; - - --- --- Name: plan_rate_cards plan_rate_cards_plan_phases_ratecards; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_plan_phases_ratecards FOREIGN KEY (phase_id) REFERENCES public.plan_phases(id) ON DELETE CASCADE; - - --- --- Name: subscription_addon_quantities subscription_addon_quantities_subscription_addons_quantities; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addon_quantities - ADD CONSTRAINT subscription_addon_quantities_subscription_addons_quantities FOREIGN KEY (subscription_addon_id) REFERENCES public.subscription_addons(id) ON DELETE CASCADE; - - --- --- Name: subscription_addons subscription_addons_addons_subscription_addons; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_addons_subscription_addons FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: subscription_addons subscription_addons_subscriptions_addons; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_subscriptions_addons FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE CASCADE; - - --- --- Name: subscription_items subscription_items_entitlements_subscription_item; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_entitlements_subscription_item FOREIGN KEY (entitlement_id) REFERENCES public.entitlements(id) ON DELETE SET NULL; - - --- --- Name: subscription_items subscription_items_subscription_phases_items; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_subscription_phases_items FOREIGN KEY (phase_id) REFERENCES public.subscription_phases(id) ON DELETE CASCADE; - - --- --- Name: subscription_phases subscription_phases_subscriptions_phases; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_phases - ADD CONSTRAINT subscription_phases_subscriptions_phases FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE CASCADE; - - --- --- Name: subscriptions subscriptions_customers_subscription; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_customers_subscription FOREIGN KEY (customer_id) REFERENCES public.customers(id); - - --- --- Name: subscriptions subscriptions_plans_subscriptions; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_plans_subscriptions FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE SET NULL; - - --- --- Name: usage_resets usage_resets_entitlements_usage_reset; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.usage_resets - ADD CONSTRAINT usage_resets_entitlements_usage_reset FOREIGN KEY (entitlement_id) REFERENCES public.entitlements(id) ON DELETE CASCADE; - - --- --- PostgreSQL database dump complete --- - diff --git a/tools/migrate/testdata/sqlcgen/20250624115812/sqlc/queries.sql b/tools/migrate/testdata/sqlcgen/20250624115812/sqlc/queries.sql deleted file mode 100644 index 66c19a562c..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250624115812/sqlc/queries.sql +++ /dev/null @@ -1,53 +0,0 @@ --- Insert queries for test setup --- name: CreateFeature :exec -INSERT INTO features ( - namespace, - id, - key, - name, - created_at, - updated_at -) VALUES ( - $1, $2, $3, $4, $5, $6 -); - --- name: CreateEntitlement :exec -INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - usage_period_interval, - usage_period_anchor -) VALUES ( - $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 -); - --- name: CreateUsageReset :exec -INSERT INTO usage_resets ( - namespace, - id, - created_at, - updated_at, - entitlement_id, - reset_time, - anchor -) VALUES ( - $1, $2, $3, $4, $5, $6, $7 -); - --- Query to verify usage reset data --- name: GetUsageResetByID :one -SELECT * FROM usage_resets WHERE id = $1; - --- Query to get entitlement info --- name: GetEntitlementByID :one -SELECT * FROM entitlements WHERE id = $1; - --- Placeholder query for SQLC validation --- name: GetSchemaVersion :one -SELECT version FROM schema_om ORDER BY version DESC LIMIT 1; diff --git a/tools/migrate/testdata/sqlcgen/20250703081943/db/db.go b/tools/migrate/testdata/sqlcgen/20250703081943/db/db.go deleted file mode 100644 index 0c56c2b4e8..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250703081943/db/db.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 - -package db - -import ( - "context" - "database/sql" -) - -type DBTX interface { - ExecContext(context.Context, string, ...interface{}) (sql.Result, error) - PrepareContext(context.Context, string) (*sql.Stmt, error) - QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) - QueryRowContext(context.Context, string, ...interface{}) *sql.Row -} - -func New(db DBTX) *Queries { - return &Queries{db: db} -} - -type Queries struct { - db DBTX -} - -func (q *Queries) WithTx(tx *sql.Tx) *Queries { - return &Queries{ - db: tx, - } -} diff --git a/tools/migrate/testdata/sqlcgen/20250703081943/db/models.go b/tools/migrate/testdata/sqlcgen/20250703081943/db/models.go deleted file mode 100644 index 8c3cbb3af1..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250703081943/db/models.go +++ /dev/null @@ -1,740 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 - -package db - -import ( - "database/sql" - "encoding/json" - "time" - - "github.com/sqlc-dev/pqtype" -) - -type Addon struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - Version int64 - Currency string - EffectiveFrom sql.NullTime - EffectiveTo sql.NullTime - Annotations pqtype.NullRawMessage - InstanceType string -} - -type AddonRateCard struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - Type string - FeatureKey sql.NullString - EntitlementTemplate pqtype.NullRawMessage - TaxConfig pqtype.NullRawMessage - BillingCadence sql.NullString - Price pqtype.NullRawMessage - Discounts pqtype.NullRawMessage - AddonID string - FeatureID sql.NullString -} - -type App struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Type string - Status string -} - -type AppCustomInvoicing struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - EnableDraftSyncHook bool - EnableIssuingSyncHook bool -} - -type AppCustomInvoicingCustomer struct { - ID int64 - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - AppID string - CustomerID string -} - -type AppCustomer struct { - ID int64 - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - AppID string - CustomerID string -} - -type AppStripe struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - StripeAccountID string - StripeLivemode bool - ApiKey string - StripeWebhookID string - WebhookSecret string - MaskedApiKey string -} - -type AppStripeCustomer struct { - ID int64 - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - StripeCustomerID string - StripeDefaultPaymentMethodID sql.NullString - AppID string - CustomerID string -} - -type BalanceSnapshot struct { - ID int64 - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - GrantBalances json.RawMessage - Balance string - Overage string - At time.Time - OwnerID string - Usage pqtype.NullRawMessage -} - -type BillingCustomerLock struct { - ID string - Namespace string - CustomerID string -} - -type BillingCustomerOverride struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - CollectionAlignment sql.NullString - InvoiceAutoAdvance sql.NullBool - InvoiceCollectionMethod sql.NullString - BillingProfileID sql.NullString - CustomerID string - LineCollectionPeriod sql.NullString - InvoiceDraftPeriod sql.NullString - InvoiceDueAfter sql.NullString - InvoiceProgressiveBilling sql.NullBool - InvoiceDefaultTaxConfig pqtype.NullRawMessage -} - -type BillingInvoice struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - CustomerID string - VoidedAt sql.NullTime - Currency string - Status string - PeriodStart sql.NullTime - PeriodEnd sql.NullTime - SourceBillingProfileID string - WorkflowConfigID string - Number string - SupplierAddressCountry sql.NullString - SupplierAddressPostalCode sql.NullString - SupplierAddressState sql.NullString - SupplierAddressCity sql.NullString - SupplierAddressLine1 sql.NullString - SupplierAddressLine2 sql.NullString - SupplierAddressPhoneNumber sql.NullString - CustomerAddressCountry sql.NullString - CustomerAddressPostalCode sql.NullString - CustomerAddressState sql.NullString - CustomerAddressCity sql.NullString - CustomerAddressLine1 sql.NullString - CustomerAddressLine2 sql.NullString - CustomerAddressPhoneNumber sql.NullString - SupplierName string - SupplierTaxCode sql.NullString - CustomerName string - Type string - Description sql.NullString - IssuedAt sql.NullTime - DueAt sql.NullTime - TaxAppID string - InvoicingAppID string - PaymentAppID string - DraftUntil sql.NullTime - CustomerUsageAttribution json.RawMessage - Amount string - TaxesTotal string - TaxesInclusiveTotal string - TaxesExclusiveTotal string - ChargesTotal string - DiscountsTotal string - Total string - InvoicingAppExternalID sql.NullString - PaymentAppExternalID sql.NullString - CollectionAt sql.NullTime - SentToCustomerAt sql.NullTime - TaxAppExternalID sql.NullString - StatusDetailsCache pqtype.NullRawMessage - QuantitySnapshotedAt sql.NullTime -} - -type BillingInvoiceFlatFeeLineConfig struct { - ID string - Namespace string - PerUnitAmount string - Category string - PaymentTerm string - Index sql.NullInt64 -} - -type BillingInvoiceLine struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - PeriodStart time.Time - PeriodEnd time.Time - InvoiceAt time.Time - Type string - Status string - Currency string - Quantity sql.NullString - TaxConfig pqtype.NullRawMessage - InvoiceID string - FeeLineConfigID sql.NullString - UsageBasedLineConfigID sql.NullString - ParentLineID sql.NullString - ChildUniqueReferenceID sql.NullString - Amount string - TaxesTotal string - TaxesInclusiveTotal string - TaxesExclusiveTotal string - ChargesTotal string - DiscountsTotal string - Total string - InvoicingAppExternalID sql.NullString - SubscriptionID sql.NullString - SubscriptionItemID sql.NullString - SubscriptionPhaseID sql.NullString - LineIds sql.NullString - ManagedBy string - RatecardDiscounts pqtype.NullRawMessage - SplitLineGroupID sql.NullString -} - -type BillingInvoiceLineDiscount struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - ChildUniqueReferenceID sql.NullString - Description sql.NullString - Amount string - LineID string - InvoicingAppExternalID sql.NullString - Reason string - Type sql.NullString - RoundingAmount sql.NullString - Quantity sql.NullString - PreLinePeriodQuantity sql.NullString - SourceDiscount pqtype.NullRawMessage -} - -type BillingInvoiceLineUsageDiscount struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - ChildUniqueReferenceID sql.NullString - Description sql.NullString - Reason string - InvoicingAppExternalID sql.NullString - Quantity string - PreLinePeriodQuantity sql.NullString - ReasonDetails pqtype.NullRawMessage - LineID string -} - -type BillingInvoiceSplitLineGroup struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Currency string - TaxConfig pqtype.NullRawMessage - ServicePeriodStart time.Time - ServicePeriodEnd time.Time - UniqueReferenceID sql.NullString - RatecardDiscounts pqtype.NullRawMessage - FeatureKey sql.NullString - Price json.RawMessage - SubscriptionID sql.NullString - SubscriptionItemID sql.NullString - SubscriptionPhaseID sql.NullString -} - -type BillingInvoiceUsageBasedLineConfig struct { - ID string - Namespace string - PriceType string - FeatureKey sql.NullString - Price json.RawMessage - PreLinePeriodQuantity sql.NullString - MeteredQuantity sql.NullString - MeteredPreLinePeriodQuantity sql.NullString -} - -type BillingInvoiceValidationIssue struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Severity string - Code sql.NullString - Message string - Path sql.NullString - Component string - DedupeHash []byte - InvoiceID string -} - -type BillingProfile struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Default bool - WorkflowConfigID string - Metadata pqtype.NullRawMessage - SupplierAddressCountry sql.NullString - SupplierAddressPostalCode sql.NullString - SupplierAddressState sql.NullString - SupplierAddressCity sql.NullString - SupplierAddressLine1 sql.NullString - SupplierAddressLine2 sql.NullString - SupplierAddressPhoneNumber sql.NullString - SupplierName string - Name string - Description sql.NullString - SupplierTaxCode sql.NullString - TaxAppID string - InvoicingAppID string - PaymentAppID string -} - -type BillingSequenceNumber struct { - ID int64 - Namespace string - Scope string - Last string -} - -type BillingWorkflowConfig struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - CollectionAlignment string - InvoiceAutoAdvance bool - InvoiceCollectionMethod string - LineCollectionPeriod string - InvoiceDraftPeriod string - InvoiceDueAfter string - InvoiceProgressiveBilling bool - InvoiceDefaultTaxSettings pqtype.NullRawMessage - TaxEnabled bool - TaxEnforced bool -} - -type Customer struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Currency sql.NullString - PrimaryEmail sql.NullString - BillingAddressCountry sql.NullString - BillingAddressPostalCode sql.NullString - BillingAddressState sql.NullString - BillingAddressCity sql.NullString - BillingAddressLine1 sql.NullString - BillingAddressLine2 sql.NullString - BillingAddressPhoneNumber sql.NullString - Description sql.NullString - Key sql.NullString -} - -type CustomerSubject struct { - ID int64 - SubjectKey string - CreatedAt time.Time - CustomerID string - Namespace string - DeletedAt sql.NullTime -} - -type Entitlement struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - EntitlementType string - FeatureKey string - SubjectKey string - MeasureUsageFrom sql.NullTime - IssueAfterReset sql.NullFloat64 - IssueAfterResetPriority sql.NullInt16 - IsSoftLimit sql.NullBool - PreserveOverageAtReset sql.NullBool - Config pqtype.NullRawMessage - UsagePeriodInterval sql.NullString - UsagePeriodAnchor sql.NullTime - CurrentUsagePeriodStart sql.NullTime - CurrentUsagePeriodEnd sql.NullTime - FeatureID string - ActiveFrom sql.NullTime - ActiveTo sql.NullTime - Annotations pqtype.NullRawMessage -} - -type Feature struct { - ID string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - Namespace string - Name string - Key string - MeterSlug sql.NullString - MeterGroupByFilters pqtype.NullRawMessage - ArchivedAt sql.NullTime -} - -type Grant struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Amount string - Priority int16 - EffectiveAt time.Time - Expiration json.RawMessage - ExpiresAt time.Time - VoidedAt sql.NullTime - ResetMaxRollover string - ResetMinRollover string - RecurrencePeriod sql.NullString - RecurrenceAnchor sql.NullTime - OwnerID string -} - -type Meter struct { - ID string - CreatedAt time.Time - UpdatedAt time.Time - Key string - Description sql.NullString - EventType string - ValueProperty sql.NullString - GroupBy pqtype.NullRawMessage - Aggregation string - Namespace string - Name string - EventFrom sql.NullTime - Metadata pqtype.NullRawMessage - DeletedAt sql.NullTime -} - -type NotificationChannel struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Type string - Name string - Disabled sql.NullBool - Config json.RawMessage -} - -type NotificationChannelRule struct { - NotificationChannelID string - NotificationRuleID string -} - -type NotificationEvent struct { - ID string - Namespace string - CreatedAt time.Time - Type string - Payload json.RawMessage - Annotations pqtype.NullRawMessage - RuleID string -} - -type NotificationEventDeliveryStatus struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - EventID string - ChannelID string - State string - Reason sql.NullString -} - -type NotificationEventDeliveryStatusEvent struct { - NotificationEventDeliveryStatusID string - NotificationEventID string -} - -type NotificationRule struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Type string - Name string - Disabled sql.NullBool - Config json.RawMessage -} - -type Plan struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - Version int64 - Currency string - EffectiveFrom sql.NullTime - EffectiveTo sql.NullTime - BillingCadence string - ProRatingConfig json.RawMessage -} - -type PlanAddon struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - Annotations pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - FromPlanPhase string - MaxQuantity sql.NullInt64 - AddonID string - PlanID string -} - -type PlanPhase struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - PlanID string - Index int16 - Duration sql.NullString -} - -type PlanRateCard struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Name string - Description sql.NullString - Key string - Type string - FeatureKey sql.NullString - EntitlementTemplate pqtype.NullRawMessage - TaxConfig pqtype.NullRawMessage - BillingCadence sql.NullString - Price pqtype.NullRawMessage - FeatureID sql.NullString - PhaseID string - Discounts pqtype.NullRawMessage -} - -type SchemaOm struct { - Version int64 - Dirty bool -} - -type Subject struct { - CreatedAt time.Time - UpdatedAt time.Time - ID string - Key string - DisplayName sql.NullString - Metadata pqtype.NullRawMessage - StripeCustomerID sql.NullString - Namespace string -} - -type Subscription struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - ActiveFrom time.Time - ActiveTo sql.NullTime - Currency string - CustomerID string - Name string - Description sql.NullString - PlanID sql.NullString - BillingCadence string - ProRatingConfig json.RawMessage - BillingAnchor time.Time -} - -type SubscriptionAddon struct { - ID string - Namespace string - Metadata pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - AddonID string - SubscriptionID string -} - -type SubscriptionAddonQuantity struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - ActiveFrom time.Time - Quantity int64 - SubscriptionAddonID string -} - -type SubscriptionItem struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - ActiveFrom time.Time - ActiveTo sql.NullTime - Key string - ActiveFromOverrideRelativeToPhaseStart sql.NullString - ActiveToOverrideRelativeToPhaseStart sql.NullString - Name string - Description sql.NullString - FeatureKey sql.NullString - EntitlementTemplate pqtype.NullRawMessage - TaxConfig pqtype.NullRawMessage - BillingCadence sql.NullString - Price pqtype.NullRawMessage - EntitlementID sql.NullString - PhaseID string - RestartsBillingPeriod sql.NullBool - Discounts pqtype.NullRawMessage - Annotations pqtype.NullRawMessage -} - -type SubscriptionPhase struct { - ID string - Namespace string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - Metadata pqtype.NullRawMessage - Key string - Name string - Description sql.NullString - ActiveFrom time.Time - SubscriptionID string - SortHint sql.NullInt16 -} - -type UsageReset struct { - ID string - Namespace string - Annotations pqtype.NullRawMessage - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt sql.NullTime - ResetTime time.Time - EntitlementID string - Anchor time.Time - UsagePeriodInterval string -} diff --git a/tools/migrate/testdata/sqlcgen/20250703081943/db/queries.sql.go b/tools/migrate/testdata/sqlcgen/20250703081943/db/queries.sql.go deleted file mode 100644 index d5e884d633..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250703081943/db/queries.sql.go +++ /dev/null @@ -1,277 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 -// source: queries.sql - -package db - -import ( - "context" - "database/sql" - "time" -) - -const createEntitlement = `-- name: CreateEntitlement :exec -INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - usage_period_interval, - usage_period_anchor, - measure_usage_from -) -VALUES ( - $1, - $2, - $3, - $4, - $5, - $6, - $7, - $8, - $9, - $10, - $11 -) -` - -type CreateEntitlementParams struct { - Namespace string - ID string - CreatedAt time.Time - UpdatedAt time.Time - EntitlementType string - FeatureKey string - FeatureID string - SubjectKey string - UsagePeriodInterval sql.NullString - UsagePeriodAnchor sql.NullTime - MeasureUsageFrom sql.NullTime -} - -func (q *Queries) CreateEntitlement(ctx context.Context, arg CreateEntitlementParams) error { - _, err := q.db.ExecContext(ctx, createEntitlement, - arg.Namespace, - arg.ID, - arg.CreatedAt, - arg.UpdatedAt, - arg.EntitlementType, - arg.FeatureKey, - arg.FeatureID, - arg.SubjectKey, - arg.UsagePeriodInterval, - arg.UsagePeriodAnchor, - arg.MeasureUsageFrom, - ) - return err -} - -const createFeature = `-- name: CreateFeature :exec -INSERT INTO features ( - namespace, - id, - key, - name, - created_at, - updated_at -) -VALUES ( - $1, - $2, - $3, - $4, - $5, - $6 -) -` - -type CreateFeatureParams struct { - Namespace string - ID string - Key string - Name string - CreatedAt time.Time - UpdatedAt time.Time -} - -func (q *Queries) CreateFeature(ctx context.Context, arg CreateFeatureParams) error { - _, err := q.db.ExecContext(ctx, createFeature, - arg.Namespace, - arg.ID, - arg.Key, - arg.Name, - arg.CreatedAt, - arg.UpdatedAt, - ) - return err -} - -const createUsageResetWithInterval = `-- name: CreateUsageResetWithInterval :exec -INSERT INTO usage_resets ( - namespace, - id, - created_at, - updated_at, - entitlement_id, - reset_time, - anchor, - usage_period_interval -) VALUES ( - $1, $2, $3, $4, $5, $6, $7, $8 -) -` - -type CreateUsageResetWithIntervalParams struct { - Namespace string - ID string - CreatedAt time.Time - UpdatedAt time.Time - EntitlementID string - ResetTime time.Time - Anchor time.Time - UsagePeriodInterval string -} - -// Insert usage reset with the new column (should fail with NULL) -func (q *Queries) CreateUsageResetWithInterval(ctx context.Context, arg CreateUsageResetWithIntervalParams) error { - _, err := q.db.ExecContext(ctx, createUsageResetWithInterval, - arg.Namespace, - arg.ID, - arg.CreatedAt, - arg.UpdatedAt, - arg.EntitlementID, - arg.ResetTime, - arg.Anchor, - arg.UsagePeriodInterval, - ) - return err -} - -const getEntitlementByID = `-- name: GetEntitlementByID :one -SELECT id, namespace, metadata, created_at, updated_at, deleted_at, entitlement_type, feature_key, subject_key, measure_usage_from, issue_after_reset, issue_after_reset_priority, is_soft_limit, preserve_overage_at_reset, config, usage_period_interval, usage_period_anchor, current_usage_period_start, current_usage_period_end, feature_id, active_from, active_to, annotations FROM entitlements WHERE id = $1 -` - -// Query to get an entitlement by ID -func (q *Queries) GetEntitlementByID(ctx context.Context, id string) (Entitlement, error) { - row := q.db.QueryRowContext(ctx, getEntitlementByID, id) - var i Entitlement - err := row.Scan( - &i.ID, - &i.Namespace, - &i.Metadata, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.EntitlementType, - &i.FeatureKey, - &i.SubjectKey, - &i.MeasureUsageFrom, - &i.IssueAfterReset, - &i.IssueAfterResetPriority, - &i.IsSoftLimit, - &i.PreserveOverageAtReset, - &i.Config, - &i.UsagePeriodInterval, - &i.UsagePeriodAnchor, - &i.CurrentUsagePeriodStart, - &i.CurrentUsagePeriodEnd, - &i.FeatureID, - &i.ActiveFrom, - &i.ActiveTo, - &i.Annotations, - ) - return i, err -} - -const getSchemaVersion = `-- name: GetSchemaVersion :one -SELECT version FROM schema_om ORDER BY version DESC LIMIT 1 -` - -// Placeholder query for SQLC validation -func (q *Queries) GetSchemaVersion(ctx context.Context) (int64, error) { - row := q.db.QueryRowContext(ctx, getSchemaVersion) - var version int64 - err := row.Scan(&version) - return version, err -} - -const getUsageResetByID = `-- name: GetUsageResetByID :one - -SELECT id, namespace, annotations, created_at, updated_at, deleted_at, reset_time, entitlement_id, anchor, usage_period_interval FROM usage_resets WHERE id = $1 -` - -// Post-migration queries with usage_period_interval column -// Query to verify usage reset data (including the new column) -func (q *Queries) GetUsageResetByID(ctx context.Context, id string) (UsageReset, error) { - row := q.db.QueryRowContext(ctx, getUsageResetByID, id) - var i UsageReset - err := row.Scan( - &i.ID, - &i.Namespace, - &i.Annotations, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.ResetTime, - &i.EntitlementID, - &i.Anchor, - &i.UsagePeriodInterval, - ) - return i, err -} - -const getUsageResetInterval = `-- name: GetUsageResetInterval :one -SELECT usage_period_interval FROM usage_resets WHERE id = $1 -` - -// Query to get usage_period_interval specifically -func (q *Queries) GetUsageResetInterval(ctx context.Context, id string) (string, error) { - row := q.db.QueryRowContext(ctx, getUsageResetInterval, id) - var usage_period_interval string - err := row.Scan(&usage_period_interval) - return usage_period_interval, err -} - -const getUsageResetsByEntitlementID = `-- name: GetUsageResetsByEntitlementID :many -SELECT id, namespace, annotations, created_at, updated_at, deleted_at, reset_time, entitlement_id, anchor, usage_period_interval FROM usage_resets WHERE entitlement_id = $1 ORDER BY reset_time ASC -` - -// Query to get all usage resets for an entitlement -func (q *Queries) GetUsageResetsByEntitlementID(ctx context.Context, entitlementID string) ([]UsageReset, error) { - rows, err := q.db.QueryContext(ctx, getUsageResetsByEntitlementID, entitlementID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []UsageReset - for rows.Next() { - var i UsageReset - if err := rows.Scan( - &i.ID, - &i.Namespace, - &i.Annotations, - &i.CreatedAt, - &i.UpdatedAt, - &i.DeletedAt, - &i.ResetTime, - &i.EntitlementID, - &i.Anchor, - &i.UsagePeriodInterval, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Close(); err != nil { - return nil, err - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} diff --git a/tools/migrate/testdata/sqlcgen/20250703081943/sqlc.yaml b/tools/migrate/testdata/sqlcgen/20250703081943/sqlc.yaml deleted file mode 100644 index b88fc3da87..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250703081943/sqlc.yaml +++ /dev/null @@ -1,9 +0,0 @@ -version: "2" -sql: - - engine: "postgresql" - queries: "sqlc/queries.sql" - schema: "sqlc/db-schema.sql" - gen: - go: - package: "db" - out: "db" diff --git a/tools/migrate/testdata/sqlcgen/20250703081943/sqlc/db-schema.sql b/tools/migrate/testdata/sqlcgen/20250703081943/sqlc/db-schema.sql deleted file mode 100644 index cced5e7f36..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250703081943/sqlc/db-schema.sql +++ /dev/null @@ -1,3197 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 14.9 (Debian 14.9-1.pgdg120+1) --- Dumped by pg_dump version 14.9 (Debian 14.9-1.pgdg120+1) - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- Name: pgcrypto; Type: EXTENSION; Schema: -; Owner: - --- - -CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; - - --- --- Name: EXTENSION pgcrypto; Type: COMMENT; Schema: -; Owner: - --- - -COMMENT ON EXTENSION pgcrypto IS 'cryptographic functions'; - - --- --- Name: delete_entitlement_on_subscription_item_delete(); Type: FUNCTION; Schema: public; Owner: - --- - -CREATE FUNCTION public.delete_entitlement_on_subscription_item_delete() RETURNS trigger - LANGUAGE plpgsql - AS $$ -BEGIN - -- Delete the entitlement if it exists and is referenced by the deleted subscription_item - IF OLD.entitlement_id IS NOT NULL THEN - DELETE FROM entitlements WHERE id = OLD.entitlement_id; - END IF; - RETURN OLD; -END; -$$; - - -SET default_tablespace = ''; - -SET default_table_access_method = heap; - --- --- Name: addon_rate_cards; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.addon_rate_cards ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - type character varying NOT NULL, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - discounts jsonb, - addon_id character(26) NOT NULL, - feature_id character(26) -); - - --- --- Name: addons; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - version bigint NOT NULL, - currency character varying DEFAULT 'USD'::character varying NOT NULL, - effective_from timestamp with time zone, - effective_to timestamp with time zone, - annotations jsonb, - instance_type character varying DEFAULT 'single'::character varying NOT NULL -); - - --- --- Name: app_custom_invoicing_customers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_custom_invoicing_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: app_custom_invoicing_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.app_custom_invoicing_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_custom_invoicing_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_custom_invoicings; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_custom_invoicings ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - enable_draft_sync_hook boolean DEFAULT false NOT NULL, - enable_issuing_sync_hook boolean DEFAULT false NOT NULL -); - - --- --- Name: app_customers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: app_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.app_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_stripe_customers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_stripe_customers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - stripe_customer_id character varying NOT NULL, - stripe_default_payment_method_id character varying, - app_id character(26) NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: app_stripe_customers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.app_stripe_customers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.app_stripe_customers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: app_stripes; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.app_stripes ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - stripe_account_id character varying NOT NULL, - stripe_livemode boolean NOT NULL, - api_key character varying NOT NULL, - stripe_webhook_id character varying NOT NULL, - webhook_secret character varying NOT NULL, - masked_api_key character varying NOT NULL -); - - --- --- Name: apps; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.apps ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - type character varying NOT NULL, - status character varying NOT NULL -); - - --- --- Name: balance_snapshots; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.balance_snapshots ( - id bigint NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - grant_balances jsonb NOT NULL, - balance numeric NOT NULL, - overage numeric NOT NULL, - at timestamp with time zone NOT NULL, - owner_id character(26) NOT NULL, - usage jsonb -); - - --- --- Name: balance_snapshots_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.balance_snapshots ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.balance_snapshots_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: billing_customer_locks; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_customer_locks ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - customer_id character(26) NOT NULL -); - - --- --- Name: billing_customer_overrides; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_customer_overrides ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - collection_alignment character varying, - invoice_auto_advance boolean, - invoice_collection_method character varying, - billing_profile_id character(26), - customer_id character(26) NOT NULL, - line_collection_period character varying, - invoice_draft_period character varying, - invoice_due_after character varying, - invoice_progressive_billing boolean, - invoice_default_tax_config jsonb -); - - --- --- Name: billing_invoice_flat_fee_line_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_flat_fee_line_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - per_unit_amount numeric NOT NULL, - category character varying DEFAULT 'regular'::character varying NOT NULL, - payment_term character varying DEFAULT 'in_advance'::character varying NOT NULL, - index bigint -); - - --- --- Name: billing_invoice_line_discounts; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_line_discounts ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - child_unique_reference_id character varying, - description character varying, - amount numeric NOT NULL, - line_id character(26) NOT NULL, - invoicing_app_external_id character varying, - reason character varying NOT NULL, - type character varying, - rounding_amount numeric, - quantity numeric, - pre_line_period_quantity numeric, - source_discount jsonb -); - - --- --- Name: billing_invoice_line_usage_discounts; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_line_usage_discounts ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - child_unique_reference_id character varying, - description character varying, - reason character varying NOT NULL, - invoicing_app_external_id character varying, - quantity numeric NOT NULL, - pre_line_period_quantity numeric, - reason_details jsonb, - line_id character(26) NOT NULL -); - - --- --- Name: billing_invoice_lines; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_lines ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - period_start timestamp with time zone NOT NULL, - period_end timestamp with time zone NOT NULL, - invoice_at timestamp with time zone NOT NULL, - type character varying NOT NULL, - status character varying NOT NULL, - currency character varying(3) NOT NULL, - quantity numeric, - tax_config jsonb, - invoice_id character(26) NOT NULL, - fee_line_config_id character(26), - usage_based_line_config_id character(26), - parent_line_id character(26), - child_unique_reference_id character varying, - amount numeric NOT NULL, - taxes_total numeric NOT NULL, - taxes_inclusive_total numeric NOT NULL, - taxes_exclusive_total numeric NOT NULL, - charges_total numeric NOT NULL, - discounts_total numeric NOT NULL, - total numeric NOT NULL, - invoicing_app_external_id character varying, - subscription_id character(26), - subscription_item_id character(26), - subscription_phase_id character(26), - line_ids character(26), - managed_by character varying NOT NULL, - ratecard_discounts jsonb, - split_line_group_id character(26) -); - - --- --- Name: billing_invoice_split_line_groups; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_split_line_groups ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - currency character varying(3) NOT NULL, - tax_config jsonb, - service_period_start timestamp with time zone NOT NULL, - service_period_end timestamp with time zone NOT NULL, - unique_reference_id character varying, - ratecard_discounts jsonb, - feature_key character varying, - price jsonb NOT NULL, - subscription_id character(26), - subscription_item_id character(26), - subscription_phase_id character(26) -); - - --- --- Name: billing_invoice_usage_based_line_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_usage_based_line_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - price_type character varying NOT NULL, - feature_key character varying, - price jsonb NOT NULL, - pre_line_period_quantity numeric, - metered_quantity numeric, - metered_pre_line_period_quantity numeric -); - - --- --- Name: billing_invoice_validation_issues; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoice_validation_issues ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - severity character varying NOT NULL, - code character varying, - message character varying NOT NULL, - path character varying, - component character varying NOT NULL, - dedupe_hash bytea NOT NULL, - invoice_id character(26) NOT NULL -); - - --- --- Name: billing_invoices; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_invoices ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - customer_id character(26) NOT NULL, - voided_at timestamp with time zone, - currency character varying(3) NOT NULL, - status character varying NOT NULL, - period_start timestamp with time zone, - period_end timestamp with time zone, - source_billing_profile_id character(26) NOT NULL, - workflow_config_id character(26) NOT NULL, - number character varying NOT NULL, - supplier_address_country character varying, - supplier_address_postal_code character varying, - supplier_address_state character varying, - supplier_address_city character varying, - supplier_address_line1 character varying, - supplier_address_line2 character varying, - supplier_address_phone_number character varying, - customer_address_country character varying, - customer_address_postal_code character varying, - customer_address_state character varying, - customer_address_city character varying, - customer_address_line1 character varying, - customer_address_line2 character varying, - customer_address_phone_number character varying, - supplier_name character varying NOT NULL, - supplier_tax_code character varying, - customer_name character varying NOT NULL, - type character varying NOT NULL, - description character varying, - issued_at timestamp with time zone, - due_at timestamp with time zone, - tax_app_id character(26) NOT NULL, - invoicing_app_id character(26) NOT NULL, - payment_app_id character(26) NOT NULL, - draft_until timestamp with time zone, - customer_usage_attribution jsonb NOT NULL, - amount numeric NOT NULL, - taxes_total numeric NOT NULL, - taxes_inclusive_total numeric NOT NULL, - taxes_exclusive_total numeric NOT NULL, - charges_total numeric NOT NULL, - discounts_total numeric NOT NULL, - total numeric NOT NULL, - invoicing_app_external_id character varying, - payment_app_external_id character varying, - collection_at timestamp with time zone, - sent_to_customer_at timestamp with time zone, - tax_app_external_id character varying, - status_details_cache jsonb, - quantity_snapshoted_at timestamp with time zone -); - - --- --- Name: billing_profiles; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_profiles ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - "default" boolean DEFAULT false NOT NULL, - workflow_config_id character(26) NOT NULL, - metadata jsonb, - supplier_address_country character varying, - supplier_address_postal_code character varying, - supplier_address_state character varying, - supplier_address_city character varying, - supplier_address_line1 character varying, - supplier_address_line2 character varying, - supplier_address_phone_number character varying, - supplier_name character varying NOT NULL, - name character varying NOT NULL, - description character varying, - supplier_tax_code character varying, - tax_app_id character(26) NOT NULL, - invoicing_app_id character(26) NOT NULL, - payment_app_id character(26) NOT NULL -); - - --- --- Name: billing_sequence_numbers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_sequence_numbers ( - id bigint NOT NULL, - namespace character varying NOT NULL, - scope character varying NOT NULL, - last numeric NOT NULL -); - - --- --- Name: billing_sequence_numbers_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.billing_sequence_numbers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.billing_sequence_numbers_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: billing_workflow_configs; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.billing_workflow_configs ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - collection_alignment character varying NOT NULL, - invoice_auto_advance boolean NOT NULL, - invoice_collection_method character varying NOT NULL, - line_collection_period character varying NOT NULL, - invoice_draft_period character varying NOT NULL, - invoice_due_after character varying NOT NULL, - invoice_progressive_billing boolean NOT NULL, - invoice_default_tax_settings jsonb, - tax_enabled boolean DEFAULT true NOT NULL, - tax_enforced boolean DEFAULT false NOT NULL -); - - --- --- Name: customer_subjects; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.customer_subjects ( - id bigint NOT NULL, - subject_key character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - customer_id character(26) NOT NULL, - namespace character varying NOT NULL, - deleted_at timestamp with time zone -); - - --- --- Name: customer_subjects_id_seq; Type: SEQUENCE; Schema: public; Owner: - --- - -ALTER TABLE public.customer_subjects ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( - SEQUENCE NAME public.customer_subjects_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1 -); - - --- --- Name: customers; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.customers ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - currency character varying, - primary_email character varying, - billing_address_country character varying, - billing_address_postal_code character varying, - billing_address_state character varying, - billing_address_city character varying, - billing_address_line1 character varying, - billing_address_line2 character varying, - billing_address_phone_number character varying, - description character varying, - key character varying -); - - --- --- Name: entitlements; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.entitlements ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - entitlement_type character varying NOT NULL, - feature_key character varying NOT NULL, - subject_key character varying NOT NULL, - measure_usage_from timestamp with time zone, - issue_after_reset double precision, - issue_after_reset_priority smallint, - is_soft_limit boolean, - preserve_overage_at_reset boolean, - config jsonb, - usage_period_interval character varying, - usage_period_anchor timestamp with time zone, - current_usage_period_start timestamp with time zone, - current_usage_period_end timestamp with time zone, - feature_id character(26) NOT NULL, - active_from timestamp with time zone, - active_to timestamp with time zone, - annotations jsonb -); - - --- --- Name: features; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.features ( - id character(26) NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - namespace character varying NOT NULL, - name character varying NOT NULL, - key character varying NOT NULL, - meter_slug character varying, - meter_group_by_filters jsonb, - archived_at timestamp with time zone -); - - --- --- Name: grants; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.grants ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - amount numeric NOT NULL, - priority smallint DEFAULT 0 NOT NULL, - effective_at timestamp with time zone NOT NULL, - expiration jsonb NOT NULL, - expires_at timestamp with time zone NOT NULL, - voided_at timestamp with time zone, - reset_max_rollover numeric NOT NULL, - reset_min_rollover numeric NOT NULL, - recurrence_period character varying, - recurrence_anchor timestamp with time zone, - owner_id character(26) NOT NULL -); - - --- --- Name: meters; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.meters ( - id character(26) NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - key character varying NOT NULL, - description character varying, - event_type character varying NOT NULL, - value_property character varying, - group_by jsonb, - aggregation character varying NOT NULL, - namespace character varying NOT NULL, - name character varying NOT NULL, - event_from timestamp with time zone, - metadata jsonb, - deleted_at timestamp with time zone -); - - --- --- Name: notification_channel_rules; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_channel_rules ( - notification_channel_id character(26) NOT NULL, - notification_rule_id character(26) NOT NULL -); - - --- --- Name: notification_channels; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_channels ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - type character varying NOT NULL, - name character varying NOT NULL, - disabled boolean DEFAULT false, - config jsonb NOT NULL -); - - --- --- Name: notification_event_delivery_status; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_event_delivery_status ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - event_id character varying NOT NULL, - channel_id character varying NOT NULL, - state character varying DEFAULT 'PENDING'::character varying NOT NULL, - reason character varying -); - - --- --- Name: notification_event_delivery_status_events; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_event_delivery_status_events ( - notification_event_delivery_status_id character(26) NOT NULL, - notification_event_id character(26) NOT NULL -); - - --- --- Name: notification_events; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_events ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - type character varying NOT NULL, - payload jsonb NOT NULL, - annotations jsonb, - rule_id character(26) NOT NULL -); - - --- --- Name: notification_rules; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.notification_rules ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - type character varying NOT NULL, - name character varying NOT NULL, - disabled boolean DEFAULT false, - config jsonb NOT NULL -); - - --- --- Name: plan_addons; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.plan_addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - annotations jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - from_plan_phase character varying NOT NULL, - max_quantity bigint, - addon_id character(26) NOT NULL, - plan_id character(26) NOT NULL -); - - --- --- Name: plan_phases; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.plan_phases ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - plan_id character(26) NOT NULL, - index smallint NOT NULL, - duration character varying -); - - --- --- Name: plan_rate_cards; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.plan_rate_cards ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - type character varying NOT NULL, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - feature_id character(26), - phase_id character(26) NOT NULL, - discounts jsonb -); - - --- --- Name: plans; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.plans ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - name character varying NOT NULL, - description character varying, - key character varying NOT NULL, - version bigint NOT NULL, - currency character varying DEFAULT 'USD'::character varying NOT NULL, - effective_from timestamp with time zone, - effective_to timestamp with time zone, - billing_cadence character varying NOT NULL, - pro_rating_config jsonb NOT NULL -); - - --- --- Name: schema_om; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.schema_om ( - version bigint NOT NULL, - dirty boolean NOT NULL -); - - --- --- Name: subjects; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subjects ( - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - id character(26) NOT NULL, - key character varying NOT NULL, - display_name character varying, - metadata jsonb, - stripe_customer_id character varying, - namespace character varying NOT NULL -); - - --- --- Name: subscription_addon_quantities; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscription_addon_quantities ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - active_from timestamp with time zone NOT NULL, - quantity bigint DEFAULT 1 NOT NULL, - subscription_addon_id character(26) NOT NULL -); - - --- --- Name: subscription_addons; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscription_addons ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - metadata jsonb, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - addon_id character(26) NOT NULL, - subscription_id character(26) NOT NULL -); - - --- --- Name: subscription_items; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscription_items ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - active_from timestamp with time zone NOT NULL, - active_to timestamp with time zone, - key character varying NOT NULL, - active_from_override_relative_to_phase_start character varying, - active_to_override_relative_to_phase_start character varying, - name character varying NOT NULL, - description character varying, - feature_key character varying, - entitlement_template jsonb, - tax_config jsonb, - billing_cadence character varying, - price jsonb, - entitlement_id character(26), - phase_id character(26) NOT NULL, - restarts_billing_period boolean, - discounts jsonb, - annotations jsonb -); - - --- --- Name: subscription_phases; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscription_phases ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - key character varying NOT NULL, - name character varying NOT NULL, - description character varying, - active_from timestamp with time zone NOT NULL, - subscription_id character(26) NOT NULL, - sort_hint smallint -); - - --- --- Name: subscriptions; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.subscriptions ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - metadata jsonb, - active_from timestamp with time zone NOT NULL, - active_to timestamp with time zone, - currency character varying NOT NULL, - customer_id character(26) NOT NULL, - name character varying DEFAULT 'Subscription'::character varying NOT NULL, - description character varying, - plan_id character(26), - billing_cadence character varying NOT NULL, - pro_rating_config jsonb NOT NULL, - billing_anchor timestamp with time zone NOT NULL -); - - --- --- Name: usage_resets; Type: TABLE; Schema: public; Owner: - --- - -CREATE TABLE public.usage_resets ( - id character(26) NOT NULL, - namespace character varying NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone, - reset_time timestamp with time zone NOT NULL, - entitlement_id character(26) NOT NULL, - anchor timestamp with time zone NOT NULL, - usage_period_interval character varying NOT NULL -); - - --- --- Name: addon_rate_cards addon_rate_cards_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_pkey PRIMARY KEY (id); - - --- --- Name: addons addons_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.addons - ADD CONSTRAINT addons_pkey PRIMARY KEY (id); - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_custom_invoicings app_custom_invoicings_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicings - ADD CONSTRAINT app_custom_invoicings_pkey PRIMARY KEY (id); - - --- --- Name: app_customers app_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_stripe_customers app_stripe_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_pkey PRIMARY KEY (id); - - --- --- Name: app_stripes app_stripes_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripes - ADD CONSTRAINT app_stripes_pkey PRIMARY KEY (id); - - --- --- Name: apps apps_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.apps - ADD CONSTRAINT apps_pkey PRIMARY KEY (id); - - --- --- Name: balance_snapshots balance_snapshots_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.balance_snapshots - ADD CONSTRAINT balance_snapshots_pkey PRIMARY KEY (id); - - --- --- Name: billing_customer_locks billing_customer_locks_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_locks - ADD CONSTRAINT billing_customer_locks_pkey PRIMARY KEY (id); - - --- --- Name: billing_customer_overrides billing_customer_overrides_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_flat_fee_line_configs billing_invoice_flat_fee_line_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_flat_fee_line_configs - ADD CONSTRAINT billing_invoice_flat_fee_line_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_line_discounts billing_invoice_line_discounts_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_discounts - ADD CONSTRAINT billing_invoice_line_discounts_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_line_usage_discounts billing_invoice_line_usage_discounts_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_usage_discounts - ADD CONSTRAINT billing_invoice_line_usage_discounts_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_lines billing_invoice_lines_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_usage_based_line_configs billing_invoice_usage_based_line_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_usage_based_line_configs - ADD CONSTRAINT billing_invoice_usage_based_line_configs_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoice_validation_issues billing_invoice_validation_issues_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_validation_issues - ADD CONSTRAINT billing_invoice_validation_issues_pkey PRIMARY KEY (id); - - --- --- Name: billing_invoices billing_invoices_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_pkey PRIMARY KEY (id); - - --- --- Name: billing_profiles billing_profiles_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_pkey PRIMARY KEY (id); - - --- --- Name: billing_sequence_numbers billing_sequence_numbers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_sequence_numbers - ADD CONSTRAINT billing_sequence_numbers_pkey PRIMARY KEY (id); - - --- --- Name: billing_workflow_configs billing_workflow_configs_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_workflow_configs - ADD CONSTRAINT billing_workflow_configs_pkey PRIMARY KEY (id); - - --- --- Name: customer_subjects customer_subjects_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.customer_subjects - ADD CONSTRAINT customer_subjects_pkey PRIMARY KEY (id); - - --- --- Name: customers customers_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.customers - ADD CONSTRAINT customers_pkey PRIMARY KEY (id); - - --- --- Name: entitlements entitlements_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.entitlements - ADD CONSTRAINT entitlements_pkey PRIMARY KEY (id); - - --- --- Name: features features_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.features - ADD CONSTRAINT features_pkey PRIMARY KEY (id); - - --- --- Name: grants grants_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.grants - ADD CONSTRAINT grants_pkey PRIMARY KEY (id); - - --- --- Name: meters meters_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.meters - ADD CONSTRAINT meters_pkey PRIMARY KEY (id); - - --- --- Name: notification_channel_rules notification_channel_rules_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_pkey PRIMARY KEY (notification_channel_id, notification_rule_id); - - --- --- Name: notification_channels notification_channels_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_channels - ADD CONSTRAINT notification_channels_pkey PRIMARY KEY (id); - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_pkey PRIMARY KEY (notification_event_delivery_status_id, notification_event_id); - - --- --- Name: notification_event_delivery_status notification_event_delivery_status_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_event_delivery_status - ADD CONSTRAINT notification_event_delivery_status_pkey PRIMARY KEY (id); - - --- --- Name: notification_events notification_events_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_events - ADD CONSTRAINT notification_events_pkey PRIMARY KEY (id); - - --- --- Name: notification_rules notification_rules_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_rules - ADD CONSTRAINT notification_rules_pkey PRIMARY KEY (id); - - --- --- Name: plan_addons plan_addons_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_pkey PRIMARY KEY (id); - - --- --- Name: plan_phases plan_phases_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_phases - ADD CONSTRAINT plan_phases_pkey PRIMARY KEY (id); - - --- --- Name: plan_rate_cards plan_rate_cards_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_pkey PRIMARY KEY (id); - - --- --- Name: plans plans_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plans - ADD CONSTRAINT plans_pkey PRIMARY KEY (id); - - --- --- Name: schema_om schema_om_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.schema_om - ADD CONSTRAINT schema_om_pkey PRIMARY KEY (version); - - --- --- Name: subjects subjects_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subjects - ADD CONSTRAINT subjects_pkey PRIMARY KEY (id); - - --- --- Name: subscription_addon_quantities subscription_addon_quantities_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addon_quantities - ADD CONSTRAINT subscription_addon_quantities_pkey PRIMARY KEY (id); - - --- --- Name: subscription_addons subscription_addons_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_pkey PRIMARY KEY (id); - - --- --- Name: subscription_items subscription_items_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_pkey PRIMARY KEY (id); - - --- --- Name: subscription_phases subscription_phases_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_phases - ADD CONSTRAINT subscription_phases_pkey PRIMARY KEY (id); - - --- --- Name: subscriptions subscriptions_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_pkey PRIMARY KEY (id); - - --- --- Name: usage_resets usage_resets_pkey; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.usage_resets - ADD CONSTRAINT usage_resets_pkey PRIMARY KEY (id); - - --- --- Name: addon_annotations; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX addon_annotations ON public.addons USING gin (annotations); - - --- --- Name: addon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addon_id ON public.addons USING btree (id); - - --- --- Name: addon_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX addon_namespace ON public.addons USING btree (namespace); - - --- --- Name: addon_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addon_namespace_id ON public.addons USING btree (namespace, id); - - --- --- Name: addon_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addon_namespace_key_deleted_at ON public.addons USING btree (namespace, key, deleted_at); - - --- --- Name: addon_namespace_key_version; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addon_namespace_key_version ON public.addons USING btree (namespace, key, version) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_addon_id_feature_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_addon_id_feature_key ON public.addon_rate_cards USING btree (addon_id, feature_key) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_addon_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_addon_id_key ON public.addon_rate_cards USING btree (addon_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: addonratecard_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_id ON public.addon_rate_cards USING btree (id); - - --- --- Name: addonratecard_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX addonratecard_namespace ON public.addon_rate_cards USING btree (namespace); - - --- --- Name: addonratecard_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_namespace_id ON public.addon_rate_cards USING btree (namespace, id); - - --- --- Name: addonratecard_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX addonratecard_namespace_key_deleted_at ON public.addon_rate_cards USING btree (namespace, key, deleted_at); - - --- --- Name: app_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX app_id ON public.apps USING btree (id); - - --- --- Name: app_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX app_namespace ON public.apps USING btree (namespace); - - --- --- Name: app_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX app_namespace_id ON public.apps USING btree (namespace, id); - - --- --- Name: app_namespace_type; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX app_namespace_type ON public.apps USING btree (namespace, type); - - --- --- Name: appcustomer_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appcustomer_namespace ON public.app_customers USING btree (namespace); - - --- --- Name: appcustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appcustomer_namespace_app_id_customer_id ON public.app_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: appcustominvoicing_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appcustominvoicing_id ON public.app_custom_invoicings USING btree (id); - - --- --- Name: appcustominvoicing_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appcustominvoicing_namespace ON public.app_custom_invoicings USING btree (namespace); - - --- --- Name: appcustominvoicing_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appcustominvoicing_namespace_id ON public.app_custom_invoicings USING btree (namespace, id); - - --- --- Name: appcustominvoicingcustomer_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appcustominvoicingcustomer_namespace ON public.app_custom_invoicing_customers USING btree (namespace); - - --- --- Name: appcustominvoicingcustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appcustominvoicingcustomer_namespace_app_id_customer_id ON public.app_custom_invoicing_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: appstripe_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appstripe_id ON public.app_stripes USING btree (id); - - --- --- Name: appstripe_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appstripe_namespace ON public.app_stripes USING btree (namespace); - - --- --- Name: appstripe_namespace_stripe_account_id_stripe_livemode; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appstripe_namespace_stripe_account_id_stripe_livemode ON public.app_stripes USING btree (namespace, stripe_account_id, stripe_livemode) WHERE (deleted_at IS NULL); - - --- --- Name: appstripecustomer_app_id_stripe_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appstripecustomer_app_id_stripe_customer_id ON public.app_stripe_customers USING btree (app_id, stripe_customer_id); - - --- --- Name: appstripecustomer_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX appstripecustomer_namespace ON public.app_stripe_customers USING btree (namespace); - - --- --- Name: appstripecustomer_namespace_app_id_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX appstripecustomer_namespace_app_id_customer_id ON public.app_stripe_customers USING btree (namespace, app_id, customer_id); - - --- --- Name: balancesnapshot_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX balancesnapshot_namespace ON public.balance_snapshots USING btree (namespace); - - --- --- Name: balancesnapshot_namespace_owner_id_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX balancesnapshot_namespace_owner_id_at ON public.balance_snapshots USING btree (namespace, owner_id, at) WHERE (deleted_at IS NULL); - - --- --- Name: billing_customer_overrides_customer_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_customer_overrides_customer_id_key ON public.billing_customer_overrides USING btree (customer_id); - - --- --- Name: billing_invoices_workflow_config_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_invoices_workflow_config_id_key ON public.billing_invoices USING btree (workflow_config_id); - - --- --- Name: billing_profiles_workflow_config_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billing_profiles_workflow_config_id_key ON public.billing_profiles USING btree (workflow_config_id); - - --- --- Name: billingcustomerlock_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomerlock_id ON public.billing_customer_locks USING btree (id); - - --- --- Name: billingcustomerlock_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingcustomerlock_namespace ON public.billing_customer_locks USING btree (namespace); - - --- --- Name: billingcustomerlock_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomerlock_namespace_customer_id ON public.billing_customer_locks USING btree (namespace, customer_id); - - --- --- Name: billingcustomeroverride_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_id ON public.billing_customer_overrides USING btree (id); - - --- --- Name: billingcustomeroverride_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingcustomeroverride_namespace ON public.billing_customer_overrides USING btree (namespace); - - --- --- Name: billingcustomeroverride_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_namespace_customer_id ON public.billing_customer_overrides USING btree (namespace, customer_id); - - --- --- Name: billingcustomeroverride_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingcustomeroverride_namespace_id ON public.billing_customer_overrides USING btree (namespace, id); - - --- --- Name: billinginvoice_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoice_id ON public.billing_invoices USING btree (id); - - --- --- Name: billinginvoice_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace ON public.billing_invoices USING btree (namespace); - - --- --- Name: billinginvoice_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_customer_id ON public.billing_invoices USING btree (namespace, customer_id); - - --- --- Name: billinginvoice_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_id ON public.billing_invoices USING btree (namespace, id); - - --- --- Name: billinginvoice_namespace_status; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_namespace_status ON public.billing_invoices USING btree (namespace, status); - - --- --- Name: billinginvoice_status_details_cache; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoice_status_details_cache ON public.billing_invoices USING gin (status_details_cache); - - --- --- Name: billinginvoiceflatfeelineconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceflatfeelineconfig_id ON public.billing_invoice_flat_fee_line_configs USING btree (id); - - --- --- Name: billinginvoiceflatfeelineconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceflatfeelineconfig_namespace ON public.billing_invoice_flat_fee_line_configs USING btree (namespace); - - --- --- Name: billinginvoiceline_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_id ON public.billing_invoice_lines USING btree (id); - - --- --- Name: billinginvoiceline_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace ON public.billing_invoice_lines USING btree (namespace); - - --- --- Name: billinginvoiceline_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_namespace_id ON public.billing_invoice_lines USING btree (namespace, id); - - --- --- Name: billinginvoiceline_namespace_invoice_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_invoice_id ON public.billing_invoice_lines USING btree (namespace, invoice_id); - - --- --- Name: billinginvoiceline_namespace_parent_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_parent_line_id ON public.billing_invoice_lines USING btree (namespace, parent_line_id); - - --- --- Name: billinginvoiceline_namespace_parent_line_id_child_unique_refere; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceline_namespace_parent_line_id_child_unique_refere ON public.billing_invoice_lines USING btree (namespace, parent_line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoiceline_namespace_subscription_id_subscription_phase; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceline_namespace_subscription_id_subscription_phase ON public.billing_invoice_lines USING btree (namespace, subscription_id, subscription_phase_id, subscription_item_id); - - --- --- Name: billinginvoicelinediscount_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelinediscount_id ON public.billing_invoice_line_discounts USING btree (id); - - --- --- Name: billinginvoicelinediscount_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelinediscount_namespace ON public.billing_invoice_line_discounts USING btree (namespace); - - --- --- Name: billinginvoicelinediscount_namespace_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelinediscount_namespace_line_id ON public.billing_invoice_line_discounts USING btree (namespace, line_id); - - --- --- Name: billinginvoicelinediscount_namespace_line_id_child_unique_refer; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelinediscount_namespace_line_id_child_unique_refer ON public.billing_invoice_line_discounts USING btree (namespace, line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoicelineusagediscount_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelineusagediscount_id ON public.billing_invoice_line_usage_discounts USING btree (id); - - --- --- Name: billinginvoicelineusagediscount_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelineusagediscount_namespace ON public.billing_invoice_line_usage_discounts USING btree (namespace); - - --- --- Name: billinginvoicelineusagediscount_namespace_line_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicelineusagediscount_namespace_line_id ON public.billing_invoice_line_usage_discounts USING btree (namespace, line_id); - - --- --- Name: billinginvoicelineusagediscount_namespace_line_id_child_unique_; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicelineusagediscount_namespace_line_id_child_unique_ ON public.billing_invoice_line_usage_discounts USING btree (namespace, line_id, child_unique_reference_id) WHERE ((child_unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoicesplitlinegroup_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_id ON public.billing_invoice_split_line_groups USING btree (id); - - --- --- Name: billinginvoicesplitlinegroup_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicesplitlinegroup_namespace ON public.billing_invoice_split_line_groups USING btree (namespace); - - --- --- Name: billinginvoicesplitlinegroup_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_namespace_id ON public.billing_invoice_split_line_groups USING btree (namespace, id); - - --- --- Name: billinginvoicesplitlinegroup_namespace_unique_reference_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicesplitlinegroup_namespace_unique_reference_id ON public.billing_invoice_split_line_groups USING btree (namespace, unique_reference_id) WHERE ((unique_reference_id IS NOT NULL) AND (deleted_at IS NULL)); - - --- --- Name: billinginvoiceusagebasedlineconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoiceusagebasedlineconfig_id ON public.billing_invoice_usage_based_line_configs USING btree (id); - - --- --- Name: billinginvoiceusagebasedlineconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoiceusagebasedlineconfig_namespace ON public.billing_invoice_usage_based_line_configs USING btree (namespace); - - --- --- Name: billinginvoicevalidationissue_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicevalidationissue_id ON public.billing_invoice_validation_issues USING btree (id); - - --- --- Name: billinginvoicevalidationissue_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billinginvoicevalidationissue_namespace ON public.billing_invoice_validation_issues USING btree (namespace); - - --- --- Name: billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billinginvoicevalidationissue_namespace_invoice_id_dedupe_hash ON public.billing_invoice_validation_issues USING btree (namespace, invoice_id, dedupe_hash); - - --- --- Name: billingprofile_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_id ON public.billing_profiles USING btree (id); - - --- --- Name: billingprofile_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingprofile_namespace ON public.billing_profiles USING btree (namespace); - - --- --- Name: billingprofile_namespace_default; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_namespace_default ON public.billing_profiles USING btree (namespace, "default") WHERE ("default" AND (deleted_at IS NULL)); - - --- --- Name: billingprofile_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingprofile_namespace_id ON public.billing_profiles USING btree (namespace, id); - - --- --- Name: billingsequencenumbers_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingsequencenumbers_namespace ON public.billing_sequence_numbers USING btree (namespace); - - --- --- Name: billingsequencenumbers_namespace_scope; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingsequencenumbers_namespace_scope ON public.billing_sequence_numbers USING btree (namespace, scope); - - --- --- Name: billingworkflowconfig_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX billingworkflowconfig_id ON public.billing_workflow_configs USING btree (id); - - --- --- Name: billingworkflowconfig_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingworkflowconfig_namespace ON public.billing_workflow_configs USING btree (namespace); - - --- --- Name: billingworkflowconfig_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX billingworkflowconfig_namespace_id ON public.billing_workflow_configs USING btree (namespace, id); - - --- --- Name: customer_created_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customer_created_at ON public.customers USING btree (created_at); - - --- --- Name: customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX customer_id ON public.customers USING btree (id); - - --- --- Name: customer_name; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customer_name ON public.customers USING btree (name); - - --- --- Name: customer_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customer_namespace ON public.customers USING btree (namespace); - - --- --- Name: customer_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX customer_namespace_id ON public.customers USING btree (namespace, id); - - --- --- Name: customer_namespace_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX customer_namespace_key ON public.customers USING btree (namespace, key) WHERE (deleted_at IS NULL); - - --- --- Name: customer_primary_email; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customer_primary_email ON public.customers USING btree (primary_email); - - --- --- Name: customersubjects_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customersubjects_namespace ON public.customer_subjects USING btree (namespace); - - --- --- Name: customersubjects_namespace_customer_id_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX customersubjects_namespace_customer_id_deleted_at ON public.customer_subjects USING btree (namespace, customer_id, deleted_at); - - --- --- Name: customersubjects_namespace_subject_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX customersubjects_namespace_subject_key ON public.customer_subjects USING btree (namespace, subject_key) WHERE (deleted_at IS NULL); - - --- --- Name: entitlement_created_at_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX entitlement_created_at_id ON public.entitlements USING btree (created_at, id); - - --- --- Name: entitlement_current_usage_period_end_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_current_usage_period_end_deleted_at ON public.entitlements USING btree (current_usage_period_end, deleted_at); - - --- --- Name: entitlement_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX entitlement_id ON public.entitlements USING btree (id); - - --- --- Name: entitlement_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace ON public.entitlements USING btree (namespace); - - --- --- Name: entitlement_namespace_current_usage_period_end; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_current_usage_period_end ON public.entitlements USING btree (namespace, current_usage_period_end); - - --- --- Name: entitlement_namespace_feature_id_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_feature_id_id ON public.entitlements USING btree (namespace, feature_id, id); - - --- --- Name: entitlement_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_id ON public.entitlements USING btree (namespace, id); - - --- --- Name: entitlement_namespace_id_subject_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_id_subject_key ON public.entitlements USING btree (namespace, id, subject_key); - - --- --- Name: entitlement_namespace_subject_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX entitlement_namespace_subject_key ON public.entitlements USING btree (namespace, subject_key); - - --- --- Name: feature_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX feature_id ON public.features USING btree (id); - - --- --- Name: feature_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX feature_namespace_id ON public.features USING btree (namespace, id); - - --- --- Name: feature_namespace_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX feature_namespace_key ON public.features USING btree (namespace, key) WHERE (archived_at IS NULL); - - --- --- Name: grant_effective_at_expires_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX grant_effective_at_expires_at ON public.grants USING btree (effective_at, expires_at); - - --- --- Name: grant_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX grant_id ON public.grants USING btree (id); - - --- --- Name: grant_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX grant_namespace ON public.grants USING btree (namespace); - - --- --- Name: grant_namespace_owner_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX grant_namespace_owner_id ON public.grants USING btree (namespace, owner_id); - - --- --- Name: meter_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX meter_id ON public.meters USING btree (id); - - --- --- Name: meter_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX meter_namespace ON public.meters USING btree (namespace); - - --- --- Name: meter_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX meter_namespace_id ON public.meters USING btree (namespace, id); - - --- --- Name: meter_namespace_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX meter_namespace_key ON public.meters USING btree (namespace, key) WHERE (deleted_at IS NULL); - - --- --- Name: meter_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX meter_namespace_key_deleted_at ON public.meters USING btree (namespace, key, deleted_at); - - --- --- Name: notificationchannel_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX notificationchannel_id ON public.notification_channels USING btree (id); - - --- --- Name: notificationchannel_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationchannel_namespace ON public.notification_channels USING btree (namespace); - - --- --- Name: notificationchannel_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationchannel_namespace_id ON public.notification_channels USING btree (namespace, id); - - --- --- Name: notificationchannel_namespace_type; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationchannel_namespace_type ON public.notification_channels USING btree (namespace, type); - - --- --- Name: notificationevent_annotations; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationevent_annotations ON public.notification_events USING gin (annotations); - - --- --- Name: notificationevent_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX notificationevent_id ON public.notification_events USING btree (id); - - --- --- Name: notificationevent_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationevent_namespace ON public.notification_events USING btree (namespace); - - --- --- Name: notificationevent_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationevent_namespace_id ON public.notification_events USING btree (namespace, id); - - --- --- Name: notificationevent_namespace_type; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationevent_namespace_type ON public.notification_events USING btree (namespace, type); - - --- --- Name: notificationeventdeliverystatus_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX notificationeventdeliverystatus_id ON public.notification_event_delivery_status USING btree (id); - - --- --- Name: notificationeventdeliverystatus_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationeventdeliverystatus_namespace ON public.notification_event_delivery_status USING btree (namespace); - - --- --- Name: notificationeventdeliverystatus_namespace_event_id_channel_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationeventdeliverystatus_namespace_event_id_channel_id ON public.notification_event_delivery_status USING btree (namespace, event_id, channel_id); - - --- --- Name: notificationeventdeliverystatus_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationeventdeliverystatus_namespace_id ON public.notification_event_delivery_status USING btree (namespace, id); - - --- --- Name: notificationeventdeliverystatus_namespace_state; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationeventdeliverystatus_namespace_state ON public.notification_event_delivery_status USING btree (namespace, state); - - --- --- Name: notificationrule_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX notificationrule_id ON public.notification_rules USING btree (id); - - --- --- Name: notificationrule_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationrule_namespace ON public.notification_rules USING btree (namespace); - - --- --- Name: notificationrule_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationrule_namespace_id ON public.notification_rules USING btree (namespace, id); - - --- --- Name: notificationrule_namespace_type; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX notificationrule_namespace_type ON public.notification_rules USING btree (namespace, type); - - --- --- Name: plan_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX plan_id ON public.plans USING btree (id); - - --- --- Name: plan_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX plan_namespace ON public.plans USING btree (namespace); - - --- --- Name: plan_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX plan_namespace_id ON public.plans USING btree (namespace, id); - - --- --- Name: plan_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX plan_namespace_key_deleted_at ON public.plans USING btree (namespace, key, deleted_at); - - --- --- Name: plan_namespace_key_version; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX plan_namespace_key_version ON public.plans USING btree (namespace, key, version) WHERE (deleted_at IS NULL); - - --- --- Name: planaddon_annotations; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planaddon_annotations ON public.plan_addons USING gin (annotations); - - --- --- Name: planaddon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planaddon_id ON public.plan_addons USING btree (id); - - --- --- Name: planaddon_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planaddon_namespace ON public.plan_addons USING btree (namespace); - - --- --- Name: planaddon_namespace_plan_id_addon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planaddon_namespace_plan_id_addon_id ON public.plan_addons USING btree (namespace, plan_id, addon_id) WHERE (deleted_at IS NULL); - - --- --- Name: planphase_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_id ON public.plan_phases USING btree (id); - - --- --- Name: planphase_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planphase_namespace ON public.plan_phases USING btree (namespace); - - --- --- Name: planphase_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_namespace_id ON public.plan_phases USING btree (namespace, id); - - --- --- Name: planphase_namespace_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planphase_namespace_key ON public.plan_phases USING btree (namespace, key); - - --- --- Name: planphase_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_namespace_key_deleted_at ON public.plan_phases USING btree (namespace, key, deleted_at); - - --- --- Name: planphase_plan_id_index; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_plan_id_index ON public.plan_phases USING btree (plan_id, index) WHERE (deleted_at IS NULL); - - --- --- Name: planphase_plan_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planphase_plan_id_key ON public.plan_phases USING btree (plan_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: planratecard_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_id ON public.plan_rate_cards USING btree (id); - - --- --- Name: planratecard_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX planratecard_namespace ON public.plan_rate_cards USING btree (namespace); - - --- --- Name: planratecard_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_namespace_id ON public.plan_rate_cards USING btree (namespace, id); - - --- --- Name: planratecard_namespace_key_deleted_at; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_namespace_key_deleted_at ON public.plan_rate_cards USING btree (namespace, key, deleted_at); - - --- --- Name: planratecard_phase_id_feature_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_phase_id_feature_key ON public.plan_rate_cards USING btree (phase_id, feature_key) WHERE (deleted_at IS NULL); - - --- --- Name: planratecard_phase_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX planratecard_phase_id_key ON public.plan_rate_cards USING btree (phase_id, key) WHERE (deleted_at IS NULL); - - --- --- Name: subject_display_name; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subject_display_name ON public.subjects USING btree (display_name); - - --- --- Name: subject_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subject_id ON public.subjects USING btree (id); - - --- --- Name: subject_key_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subject_key_namespace ON public.subjects USING btree (key, namespace); - - --- --- Name: subject_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subject_namespace ON public.subjects USING btree (namespace); - - --- --- Name: subscription_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscription_id ON public.subscriptions USING btree (id); - - --- --- Name: subscription_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscription_namespace ON public.subscriptions USING btree (namespace); - - --- --- Name: subscription_namespace_customer_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscription_namespace_customer_id ON public.subscriptions USING btree (namespace, customer_id); - - --- --- Name: subscription_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscription_namespace_id ON public.subscriptions USING btree (namespace, id); - - --- --- Name: subscriptionaddon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscriptionaddon_id ON public.subscription_addons USING btree (id); - - --- --- Name: subscriptionaddon_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionaddon_namespace ON public.subscription_addons USING btree (namespace); - - --- --- Name: subscriptionaddonquantity_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscriptionaddonquantity_id ON public.subscription_addon_quantities USING btree (id); - - --- --- Name: subscriptionaddonquantity_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionaddonquantity_namespace ON public.subscription_addon_quantities USING btree (namespace); - - --- --- Name: subscriptionaddonquantity_subscription_addon_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionaddonquantity_subscription_addon_id ON public.subscription_addon_quantities USING btree (subscription_addon_id); - - --- --- Name: subscriptionitem_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscriptionitem_id ON public.subscription_items USING btree (id); - - --- --- Name: subscriptionitem_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionitem_namespace ON public.subscription_items USING btree (namespace); - - --- --- Name: subscriptionitem_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionitem_namespace_id ON public.subscription_items USING btree (namespace, id); - - --- --- Name: subscriptionitem_namespace_phase_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionitem_namespace_phase_id_key ON public.subscription_items USING btree (namespace, phase_id, key); - - --- --- Name: subscriptionphase_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX subscriptionphase_id ON public.subscription_phases USING btree (id); - - --- --- Name: subscriptionphase_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionphase_namespace ON public.subscription_phases USING btree (namespace); - - --- --- Name: subscriptionphase_namespace_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionphase_namespace_id ON public.subscription_phases USING btree (namespace, id); - - --- --- Name: subscriptionphase_namespace_subscription_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionphase_namespace_subscription_id ON public.subscription_phases USING btree (namespace, subscription_id); - - --- --- Name: subscriptionphase_namespace_subscription_id_key; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX subscriptionphase_namespace_subscription_id_key ON public.subscription_phases USING btree (namespace, subscription_id, key); - - --- --- Name: usagereset_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE UNIQUE INDEX usagereset_id ON public.usage_resets USING btree (id); - - --- --- Name: usagereset_namespace; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX usagereset_namespace ON public.usage_resets USING btree (namespace); - - --- --- Name: usagereset_namespace_entitlement_id; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX usagereset_namespace_entitlement_id ON public.usage_resets USING btree (namespace, entitlement_id); - - --- --- Name: usagereset_namespace_entitlement_id_reset_time; Type: INDEX; Schema: public; Owner: - --- - -CREATE INDEX usagereset_namespace_entitlement_id_reset_time ON public.usage_resets USING btree (namespace, entitlement_id, reset_time); - - --- --- Name: subscription_items trigger_delete_entitlement_on_subscription_item_delete; Type: TRIGGER; Schema: public; Owner: - --- - -CREATE TRIGGER trigger_delete_entitlement_on_subscription_item_delete AFTER DELETE ON public.subscription_items FOR EACH ROW EXECUTE FUNCTION public.delete_entitlement_on_subscription_item_delete(); - - --- --- Name: addon_rate_cards addon_rate_cards_addons_ratecards; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_addons_ratecards FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: addon_rate_cards addon_rate_cards_features_addon_ratecard; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.addon_rate_cards - ADD CONSTRAINT addon_rate_cards_features_addon_ratecard FOREIGN KEY (feature_id) REFERENCES public.features(id) ON DELETE SET NULL; - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_app_custom_invoicings_customer_a; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_app_custom_invoicings_customer_a FOREIGN KEY (app_id) REFERENCES public.app_custom_invoicings(id) ON DELETE CASCADE; - - --- --- Name: app_custom_invoicing_customers app_custom_invoicing_customers_customers_customer; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicing_customers - ADD CONSTRAINT app_custom_invoicing_customers_customers_customer FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_custom_invoicings app_custom_invoicings_apps_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_custom_invoicings - ADD CONSTRAINT app_custom_invoicings_apps_app FOREIGN KEY (id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: app_customers app_customers_apps_customer_apps; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_apps_customer_apps FOREIGN KEY (app_id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: app_customers app_customers_customers_apps; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_customers - ADD CONSTRAINT app_customers_customers_apps FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_stripe_customers app_stripe_customers_app_stripes_customer_apps; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_app_stripes_customer_apps FOREIGN KEY (app_id) REFERENCES public.app_stripes(id) ON DELETE CASCADE; - - --- --- Name: app_stripe_customers app_stripe_customers_customers_customer; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripe_customers - ADD CONSTRAINT app_stripe_customers_customers_customer FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: app_stripes app_stripes_apps_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.app_stripes - ADD CONSTRAINT app_stripes_apps_app FOREIGN KEY (id) REFERENCES public.apps(id) ON DELETE CASCADE; - - --- --- Name: balance_snapshots balance_snapshots_entitlements_balance_snapshot; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.balance_snapshots - ADD CONSTRAINT balance_snapshots_entitlements_balance_snapshot FOREIGN KEY (owner_id) REFERENCES public.entitlements(id) ON DELETE CASCADE; - - --- --- Name: billing_customer_overrides billing_customer_overrides_billing_profiles_billing_customer_ov; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_billing_profiles_billing_customer_ov FOREIGN KEY (billing_profile_id) REFERENCES public.billing_profiles(id) ON DELETE SET NULL; - - --- --- Name: billing_customer_overrides billing_customer_overrides_customers_billing_customer_override; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_customer_overrides - ADD CONSTRAINT billing_customer_overrides_customers_billing_customer_override FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_line_discounts billing_invoice_line_discounts_billing_invoice_lines_line_amoun; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_discounts - ADD CONSTRAINT billing_invoice_line_discounts_billing_invoice_lines_line_amoun FOREIGN KEY (line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_line_usage_discounts billing_invoice_line_usage_discounts_billing_invoice_lines_line; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_line_usage_discounts - ADD CONSTRAINT billing_invoice_line_usage_discounts_billing_invoice_lines_line FOREIGN KEY (line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_flat_fee_line_configs_fla; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_flat_fee_line_configs_fla FOREIGN KEY (fee_line_config_id) REFERENCES public.billing_invoice_flat_fee_line_configs(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_lines_detailed_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_lines_detailed_lines FOREIGN KEY (parent_line_id) REFERENCES public.billing_invoice_lines(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_split_line_groups_billing; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_split_line_groups_billing FOREIGN KEY (split_line_group_id) REFERENCES public.billing_invoice_split_line_groups(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoice_usage_based_line_configs_; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoice_usage_based_line_configs_ FOREIGN KEY (usage_based_line_config_id) REFERENCES public.billing_invoice_usage_based_line_configs(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_billing_invoices_billing_invoice_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_billing_invoices_billing_invoice_lines FOREIGN KEY (invoice_id) REFERENCES public.billing_invoices(id) ON DELETE CASCADE; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscription_items_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscription_items_billing_lines FOREIGN KEY (subscription_item_id) REFERENCES public.subscription_items(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscription_phases_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscription_phases_billing_lines FOREIGN KEY (subscription_phase_id) REFERENCES public.subscription_phases(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_lines billing_invoice_lines_subscriptions_billing_lines; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_lines - ADD CONSTRAINT billing_invoice_lines_subscriptions_billing_lines FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscription_items_billing_sp; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscription_items_billing_sp FOREIGN KEY (subscription_item_id) REFERENCES public.subscription_items(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscription_phases_billing_s; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscription_phases_billing_s FOREIGN KEY (subscription_phase_id) REFERENCES public.subscription_phases(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_split_line_groups billing_invoice_split_line_groups_subscriptions_billing_split_l; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_split_line_groups - ADD CONSTRAINT billing_invoice_split_line_groups_subscriptions_billing_split_l FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE SET NULL; - - --- --- Name: billing_invoice_validation_issues billing_invoice_validation_issues_billing_invoices_billing_invo; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoice_validation_issues - ADD CONSTRAINT billing_invoice_validation_issues_billing_invoices_billing_invo FOREIGN KEY (invoice_id) REFERENCES public.billing_invoices(id) ON DELETE CASCADE; - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_invoicing_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_invoicing_app FOREIGN KEY (invoicing_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_payment_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_payment_app FOREIGN KEY (payment_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_apps_billing_invoice_tax_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_apps_billing_invoice_tax_app FOREIGN KEY (tax_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_invoices billing_invoices_billing_profiles_billing_invoices; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_billing_profiles_billing_invoices FOREIGN KEY (source_billing_profile_id) REFERENCES public.billing_profiles(id); - - --- --- Name: billing_invoices billing_invoices_billing_workflow_configs_billing_invoices; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_billing_workflow_configs_billing_invoices FOREIGN KEY (workflow_config_id) REFERENCES public.billing_workflow_configs(id); - - --- --- Name: billing_invoices billing_invoices_customers_billing_invoice; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_invoices - ADD CONSTRAINT billing_invoices_customers_billing_invoice FOREIGN KEY (customer_id) REFERENCES public.customers(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_invoicing_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_invoicing_app FOREIGN KEY (invoicing_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_payment_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_payment_app FOREIGN KEY (payment_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_apps_billing_profile_tax_app; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_apps_billing_profile_tax_app FOREIGN KEY (tax_app_id) REFERENCES public.apps(id); - - --- --- Name: billing_profiles billing_profiles_billing_workflow_configs_billing_profile; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.billing_profiles - ADD CONSTRAINT billing_profiles_billing_workflow_configs_billing_profile FOREIGN KEY (workflow_config_id) REFERENCES public.billing_workflow_configs(id); - - --- --- Name: customer_subjects customer_subjects_customers_subjects; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.customer_subjects - ADD CONSTRAINT customer_subjects_customers_subjects FOREIGN KEY (customer_id) REFERENCES public.customers(id) ON DELETE CASCADE; - - --- --- Name: entitlements entitlements_features_entitlement; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.entitlements - ADD CONSTRAINT entitlements_features_entitlement FOREIGN KEY (feature_id) REFERENCES public.features(id); - - --- --- Name: grants grants_entitlements_grant; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.grants - ADD CONSTRAINT grants_entitlements_grant FOREIGN KEY (owner_id) REFERENCES public.entitlements(id) ON DELETE CASCADE; - - --- --- Name: notification_channel_rules notification_channel_rules_notification_channel_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_notification_channel_id FOREIGN KEY (notification_channel_id) REFERENCES public.notification_channels(id) ON DELETE CASCADE; - - --- --- Name: notification_channel_rules notification_channel_rules_notification_rule_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_channel_rules - ADD CONSTRAINT notification_channel_rules_notification_rule_id FOREIGN KEY (notification_rule_id) REFERENCES public.notification_rules(id) ON DELETE CASCADE; - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_notification_event_de; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_notification_event_de FOREIGN KEY (notification_event_delivery_status_id) REFERENCES public.notification_event_delivery_status(id) ON DELETE CASCADE; - - --- --- Name: notification_event_delivery_status_events notification_event_delivery_status_events_notification_event_id; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_event_delivery_status_events - ADD CONSTRAINT notification_event_delivery_status_events_notification_event_id FOREIGN KEY (notification_event_id) REFERENCES public.notification_events(id) ON DELETE CASCADE; - - --- --- Name: notification_events notification_events_notification_rules_events; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.notification_events - ADD CONSTRAINT notification_events_notification_rules_events FOREIGN KEY (rule_id) REFERENCES public.notification_rules(id); - - --- --- Name: plan_addons plan_addons_addons_plans; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_addons_plans FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: plan_addons plan_addons_plans_addons; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_addons - ADD CONSTRAINT plan_addons_plans_addons FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE CASCADE; - - --- --- Name: plan_phases plan_phases_plans_phases; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_phases - ADD CONSTRAINT plan_phases_plans_phases FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE CASCADE; - - --- --- Name: plan_rate_cards plan_rate_cards_features_ratecard; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_features_ratecard FOREIGN KEY (feature_id) REFERENCES public.features(id) ON DELETE SET NULL; - - --- --- Name: plan_rate_cards plan_rate_cards_plan_phases_ratecards; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.plan_rate_cards - ADD CONSTRAINT plan_rate_cards_plan_phases_ratecards FOREIGN KEY (phase_id) REFERENCES public.plan_phases(id) ON DELETE CASCADE; - - --- --- Name: subscription_addon_quantities subscription_addon_quantities_subscription_addons_quantities; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addon_quantities - ADD CONSTRAINT subscription_addon_quantities_subscription_addons_quantities FOREIGN KEY (subscription_addon_id) REFERENCES public.subscription_addons(id) ON DELETE CASCADE; - - --- --- Name: subscription_addons subscription_addons_addons_subscription_addons; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_addons_subscription_addons FOREIGN KEY (addon_id) REFERENCES public.addons(id) ON DELETE CASCADE; - - --- --- Name: subscription_addons subscription_addons_subscriptions_addons; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_addons - ADD CONSTRAINT subscription_addons_subscriptions_addons FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE CASCADE; - - --- --- Name: subscription_items subscription_items_entitlements_subscription_item; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_entitlements_subscription_item FOREIGN KEY (entitlement_id) REFERENCES public.entitlements(id) ON DELETE SET NULL; - - --- --- Name: subscription_items subscription_items_subscription_phases_items; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_items - ADD CONSTRAINT subscription_items_subscription_phases_items FOREIGN KEY (phase_id) REFERENCES public.subscription_phases(id) ON DELETE CASCADE; - - --- --- Name: subscription_phases subscription_phases_subscriptions_phases; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscription_phases - ADD CONSTRAINT subscription_phases_subscriptions_phases FOREIGN KEY (subscription_id) REFERENCES public.subscriptions(id) ON DELETE CASCADE; - - --- --- Name: subscriptions subscriptions_customers_subscription; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_customers_subscription FOREIGN KEY (customer_id) REFERENCES public.customers(id); - - --- --- Name: subscriptions subscriptions_plans_subscriptions; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.subscriptions - ADD CONSTRAINT subscriptions_plans_subscriptions FOREIGN KEY (plan_id) REFERENCES public.plans(id) ON DELETE SET NULL; - - --- --- Name: usage_resets usage_resets_entitlements_usage_reset; Type: FK CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.usage_resets - ADD CONSTRAINT usage_resets_entitlements_usage_reset FOREIGN KEY (entitlement_id) REFERENCES public.entitlements(id) ON DELETE CASCADE; - - --- --- PostgreSQL database dump complete --- - diff --git a/tools/migrate/testdata/sqlcgen/20250703081943/sqlc/queries.sql b/tools/migrate/testdata/sqlcgen/20250703081943/sqlc/queries.sql deleted file mode 100644 index c3f091d066..0000000000 --- a/tools/migrate/testdata/sqlcgen/20250703081943/sqlc/queries.sql +++ /dev/null @@ -1,83 +0,0 @@ --- Post-migration queries with usage_period_interval column - --- Query to verify usage reset data (including the new column) --- name: GetUsageResetByID :one -SELECT * FROM usage_resets WHERE id = $1; - --- Query to get usage_period_interval specifically --- name: GetUsageResetInterval :one -SELECT usage_period_interval FROM usage_resets WHERE id = $1; - --- Query to get all usage resets for an entitlement --- name: GetUsageResetsByEntitlementID :many -SELECT * FROM usage_resets WHERE entitlement_id = $1 ORDER BY reset_time ASC; - --- Query to get an entitlement by ID --- name: GetEntitlementByID :one -SELECT * FROM entitlements WHERE id = $1; - --- Insert usage reset with the new column (should fail with NULL) --- name: CreateUsageResetWithInterval :exec -INSERT INTO usage_resets ( - namespace, - id, - created_at, - updated_at, - entitlement_id, - reset_time, - anchor, - usage_period_interval -) VALUES ( - $1, $2, $3, $4, $5, $6, $7, $8 -); - --- name: CreateFeature :exec -INSERT INTO features ( - namespace, - id, - key, - name, - created_at, - updated_at -) -VALUES ( - $1, - $2, - $3, - $4, - $5, - $6 -); - --- name: CreateEntitlement :exec -INSERT INTO entitlements ( - namespace, - id, - created_at, - updated_at, - entitlement_type, - feature_key, - feature_id, - subject_key, - usage_period_interval, - usage_period_anchor, - measure_usage_from -) -VALUES ( - $1, - $2, - $3, - $4, - $5, - $6, - $7, - $8, - $9, - $10, - $11 -); - - --- Placeholder query for SQLC validation --- name: GetSchemaVersion :one -SELECT version FROM schema_om ORDER BY version DESC LIMIT 1;