* Key Rotation/Destruction (#2477) * fix: Correct kms.CreateKeys comment This method does not return anything. * feat(kms): Add new ListKeys method The new ListKeys method wraps the underlying KMS wrapper, returning all the keys in the scope specified. * feat(scopes): Add new scope actions for key management Adds list-keys, rotate-keys and revoke-keys actions for scopes. * feat(scopes): Add ListKeys API endpoint This new endpoint lists all keys in a scope * feat(api): Add ListKeys to Scopes client This has to be a custom function because it is a custom action and doesn't map well to any of the existing templates, or generalises well in a way that would make it reasonable to create a new template. * feat(cli): Add new scopes list-keys command * add RotateKeys function to the kms repository * Add Rotate Keys Endpoint to Scopes Api (#2360) * add rotate keys endpoint * add tests for RotateKeys endpoint * remove that one comment I forgot about * addressing more PR comments * Add Rotate Keys CLI Command (#2395) * add cli command and client * add bats tests * fix some info text and pr comments * write a new rotate keys description * Add Missing DEK Foreign Keys (#2408) * add missing fks * mark key as nullable in gorm * update tests to use a new wrapper with a real key_id * fix formatting in test and add keys for auth_token test * replace key values * revert postgres_40_01_test.go * style: reformat sql for readability * refactor: change type of key_id columns to kms_private_id * Store key_id and scope_id with oplog entries, re-type columns referencing data key version (#2431) * fix(db): Correct types of data key version referencers * fix(oplog): Fix missing error handling * feat(oplog): Store key_id and scope_id with oplog entries This migration truncates all existing oplog entries, as migrating existing data would have been complex and likely unnecessary. * Update view references * Always delete oplog entries when dropping keys * Fix rebase issues * Fix sql tests * Add schema for new kms destruction jobs (#2479) * feat: Add schema for new kms destruction jobs The schema lets us manage destruction jobs per-table while providing a guarantee that only one run is running at a time. * Apply suggestions from code review Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * Fix table reference and tests Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * update domain, api, and cli to all include key versions in outputs (#2472) * update domain, api, and cli to all include key versions in outputs * fix go sum * add migration to fix immutable error * fix final test issue as well as make gen issue * rebase and fix * address johan pr comments * make gen, didn't realize comments were included * update migrations based on new migration 55 file 03 * Move migrations to 56 * feat: Add key version rewrapping function registry (#2478) The new RegisterTableRewrapFn can be used by a domain to register a callback to use when rewrapping data in a specific table name. * feat(kms): Add scopeId to RewrapFn (#2539) This makes it much easier for rewrap functions to look up the correct wrapper and limit the number of rows searched. * Update Root Cert Proto Definition (#2542) * update root cert proto definition to properly identify public_key as the table primary key * add the test fix as well * Rewrap Functions for Encrypted Tables (#2532) * add oidc rewrap * add argon2 config rewrap * add auth token rewrapping * add worker auth cert rewrapping * check the err * add username password credential rewrapping * add ssh private key credential rewrapping * add vault client certificate rewrap function * add host catalog secret rewrap function * cleanup a little * add host vault token rewrap function * add session credential rewrap function * add session rewrap function * add worker auth rewrap function * update test to include full assert gamut * add session rewrap function TEST * bring all tests up to current standards, make more readable, and include full assert gamut * rework all rewrap functions to utilize scope id * update comments, queries, sql refs, etc, in response to PR comments * forgot a comment * remove hmac updates and fix a couple comments again * Rewrapping Registered Tables Test (#2555) * add the registered table test as well as the two missing rewrap functions * address pr comments, add db r/w conversions, cmp.diff, sql comment, remove (now) faulty immutable test * Add ability to list key version destruction jobs, recurring jobs and destroying key versions (#2498) * feat(kms): Add ability to list data key version destruction jobs * feat(scopes): Add ListKeyVersionDestructionJobs * feat(cli): Add list-key-version-destruction-jobs * feat(kms): Add recurring job that performs table rewrapping The new recurring job runs for each job table with a registered rewrapping callback. It attempts to become the running run and start its rewrapping, gracefully handling sudden interruptions by resuming it's work if it finds evidence of sudden interruption. * feat(kms): Add recurring job for destroying key versions The new job monitors the database for data key version destruction jobs that have finished rewrapping all its data, performing the final data key version revocation. * feat(kms): Add DestroyKeyVersion DestroyKeyVersion immediately destroys a key version if it is a root key version or a data key version which encrypts no data. If the data key version encrypts data which needs to be rewrapped, it queues an asynchronous job to complete the rewrapping operation. * feat(scopes): Add DestroyKeyVersion API endpoint * feat(cli): Add scopes destroy-key-version CLI command * Ensure all secret updates include key ID (#2556) * feat(all): Ensure all secret updates include key ID When updating a secret, it is paramount that the key ID is also updated, as it is the only means we have of ensuring that we only destroy keys once there is no more data associated with the key. * Remove fix to session repository for now This breaks the current private key derivation method * add new encrypt/decrypt funcs and made necessary proto changes (#2557) * add new encrypt/decrypt funcs and made necessary proto changes * address all PR comments * fix test panic * add param checking to rewraps * fix(schema): Correctly organize migrations again * Review comments part 1 * Review comments part 2 * Review comments part 3 * Store cert private key, encrypt tofu token (#2583) * fix(session): store cert private key, encrypt tofu token Previously, we would derive a session certificate private key from the session key used in each project, and not store the key. We would also encrypt the tofu token with the database key but not store a reference to this key in the database. This change fixes this by replacing our key derivation with a key generation step, and instead store the generated key, encrypted, in the database. We also ensure that any new tofu tokens are encrypted with the same key. To handle existing sessions, we lazily rewrite the sessions whenever a user lists them. There is a minor risk that a user could end up destroying the database key that encrypts the tofu token before that session has been rewrapped, but this is going to be rare and temporary. * feat(session): Allow the random source for secrets to be configured * Review comments * Minor fixes * More minor fixes * More small fixes Co-authored-by: Danielle Miu <dani.miu@hashicorp.com> Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com> Co-authored-by: Michael Gaffney <mike@gaffney.cc> Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * fix(session): Unset session key ID when scope is deleted Unsetting the key ID allows the session to live beyond the lifetime of the scope, while allowing the scope to cascade delete its keys. * fix(migrations): Rewrite migration 56 tests These tests can no longer use the normal test helpers as they try to use the new oplog table structure, so we have to manually write all the interactions. * fix(migrations): Rename migration 58 file name This was the name used in the release branch, update it to the new migration number. * fix(e2e): Add some comments and debug to kms tests * fix(session): Handle empty project and user IDs in read When a project or user is deleted, the session is automatically canceled and the respective field on the session is unset. LookupSession did not handle this case gracefully, and would error on decryption in this state. Skip decrypting sessions that do not have either a user or project to avoid this error. The decrypted values are not used for a canceled session. * Fix worker test * Increase test timeout Co-authored-by: Danielle Miu <dani.miu@hashicorp.com> Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com> Co-authored-by: Michael Gaffney <mike@gaffney.cc> Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
582 lines
15 KiB
Go
582 lines
15 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/DATA-DOG/go-sqlmock"
|
|
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
|
_ "github.com/golang-migrate/migrate/v4/source/file"
|
|
"github.com/hashicorp/boundary/internal/db/schema"
|
|
"github.com/hashicorp/boundary/internal/oplog"
|
|
"github.com/hashicorp/boundary/internal/oplog/store"
|
|
"github.com/hashicorp/boundary/testing/dbtest"
|
|
"github.com/hashicorp/go-dbw"
|
|
"github.com/hashicorp/go-kms-wrapping/extras/kms/v2"
|
|
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
|
|
aead "github.com/hashicorp/go-kms-wrapping/v2/aead"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
pgDriver "gorm.io/driver/postgres"
|
|
)
|
|
|
|
// setup the tests (initialize the database one-time and initialized
|
|
// testDatabaseURL). Do not close the returned db. Supported options:
|
|
// WithTestLogLevel, WithTestDatabaseUrl
|
|
func TestSetup(t testing.TB, dialect string, opt ...TestOption) (*DB, string) {
|
|
t.Helper()
|
|
var cleanup func() error
|
|
var url string
|
|
var err error
|
|
ctx := context.Background()
|
|
|
|
opts := getTestOpts(opt...)
|
|
|
|
switch opts.withTestDatabaseUrl {
|
|
case "":
|
|
cleanup, url, _, err = dbtest.StartUsingTemplate(dialect, dbtest.WithTemplate(opts.withTemplate))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() {
|
|
assert.NoError(t, cleanup(), "Got error cleaning up db in docker.")
|
|
})
|
|
default:
|
|
url = opts.withTestDatabaseUrl
|
|
}
|
|
|
|
_, err = schema.MigrateStore(ctx, schema.Dialect(dialect), url)
|
|
if err != nil {
|
|
t.Fatalf("Couldn't init store on existing db: %v", err)
|
|
}
|
|
dbType, err := StringToDbType(dialect)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
db, err := Open(ctx, dbType, url)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
switch {
|
|
case opts.withLogLevel != DefaultTestLogLevel:
|
|
db.wrapped.Load().LogLevel(dbw.LogLevel(opts.withLogLevel))
|
|
default:
|
|
var defaultLevel dbw.LogLevel
|
|
switch strings.ToLower(os.Getenv("DEFAULT_TEST_LOG_LEVEL")) {
|
|
case "silent":
|
|
defaultLevel = dbw.Silent
|
|
case "error":
|
|
defaultLevel = dbw.Error
|
|
case "warn":
|
|
defaultLevel = dbw.Warn
|
|
case "info":
|
|
defaultLevel = dbw.Info
|
|
default:
|
|
defaultLevel = dbw.Silent
|
|
}
|
|
db.wrapped.Load().LogLevel(defaultLevel)
|
|
}
|
|
t.Cleanup(func() {
|
|
sqlDB, err := db.SqlDB(ctx)
|
|
assert.NoError(t, err)
|
|
assert.NoError(t, sqlDB.Close(), "Got error closing gorm db.")
|
|
})
|
|
return db, url
|
|
}
|
|
|
|
// TestSetupWithMock will return a test DB and an associated Sqlmock which can
|
|
// be used to mock out the db responses.
|
|
func TestSetupWithMock(t *testing.T) (*DB, sqlmock.Sqlmock) {
|
|
t.Helper()
|
|
require := require.New(t)
|
|
db, mock, err := sqlmock.New()
|
|
require.NoError(err)
|
|
require.NoError(err)
|
|
dbWith, err := dbw.OpenWith(pgDriver.New(pgDriver.Config{
|
|
Conn: db,
|
|
}))
|
|
require.NoError(err)
|
|
ret := &DB{
|
|
wrapped: new(atomic.Pointer[dbw.DB]),
|
|
}
|
|
ret.wrapped.Store(dbWith)
|
|
return ret, mock
|
|
}
|
|
|
|
// TestWrapper initializes an AEAD wrapping.Wrapper for testing
|
|
func TestWrapper(t testing.TB) wrapping.Wrapper {
|
|
t.Helper()
|
|
rootKey := make([]byte, 32)
|
|
n, err := rand.Read(rootKey)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n != 32 {
|
|
t.Fatal(n)
|
|
}
|
|
root := aead.NewWrapper()
|
|
_, err = root.SetConfig(context.Background(), wrapping.WithKeyId(base64.StdEncoding.EncodeToString(rootKey)))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := root.SetAesGcmKeyBytes(rootKey); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return root
|
|
}
|
|
|
|
// TestDBWrapper initializes a DB wrapper for testing
|
|
func TestDBWrapper(t testing.TB, conn *DB, purpose kms.KeyPurpose) wrapping.Wrapper {
|
|
t.Helper()
|
|
purposes := []kms.KeyPurpose{purpose}
|
|
if purpose != "oplog" {
|
|
// Always add the oplog purpose, most tests need it
|
|
purposes = append(purposes, "oplog")
|
|
}
|
|
kmsCache, err := kms.New(dbw.New(conn.wrapped.Load()), dbw.New(conn.wrapped.Load()), purposes)
|
|
require.NoError(t, err)
|
|
err = kmsCache.AddExternalWrapper(context.Background(), kms.KeyPurposeRootKey, TestWrapper(t))
|
|
require.NoError(t, err)
|
|
err = kmsCache.CreateKeys(context.Background(), "global", purposes)
|
|
require.NoError(t, err)
|
|
wrapper, err := kmsCache.GetWrapper(context.Background(), "global", purpose)
|
|
require.NoError(t, err)
|
|
return wrapper
|
|
}
|
|
|
|
// AssertPublicId is a test helper that asserts that the provided id is in
|
|
// the format of a public id.
|
|
func AssertPublicId(t testing.TB, prefix, actual string) {
|
|
t.Helper()
|
|
assert.NotEmpty(t, actual)
|
|
parts := strings.Split(actual, "_")
|
|
assert.Equalf(t, 2, len(parts), "want one '_' in PublicId, got multiple in %q", actual)
|
|
assert.Equalf(t, prefix, parts[0], "PublicId want prefix: %q, got: %q in %q", prefix, parts[0], actual)
|
|
}
|
|
|
|
// TestDeleteWhere allows you to easily delete resources for testing purposes
|
|
// including all the current resources.
|
|
func TestDeleteWhere(t testing.TB, conn *DB, i any, whereClause string, args ...any) {
|
|
t.Helper()
|
|
require := require.New(t)
|
|
ctx := context.Background()
|
|
tabler, ok := i.(interface {
|
|
TableName() string
|
|
})
|
|
require.True(ok)
|
|
_, err := dbw.New(conn.wrapped.Load()).Exec(ctx, fmt.Sprintf(`delete from "%s" where %s`, tabler.TableName(), whereClause), args)
|
|
require.NoError(err)
|
|
}
|
|
|
|
// TestVerifyOplog will verify that there is an oplog entry that matches the provided resourceId.
|
|
// By default it matches the provided resourceId against the `resource-public-id` tag. If the
|
|
// WithResourcePrivateId option is provided, the lookup will use the `resource-private-id` tag.
|
|
// An error is returned if the entry or it's metadata is not found. Returning an error
|
|
// allows clients to test if an entry was not written, which is a valid use case.
|
|
func TestVerifyOplog(t testing.TB, r Reader, resourceId string, opt ...TestOption) error {
|
|
t.Helper()
|
|
|
|
// sql where clauses
|
|
const (
|
|
whereBase = `
|
|
key = ?
|
|
and value = ?
|
|
`
|
|
|
|
whereOptype = `
|
|
and entry_id in (
|
|
select entry_id
|
|
from oplog_metadata
|
|
where key = 'op-type'
|
|
and value = ?
|
|
)
|
|
`
|
|
whereCreateNotBefore = `
|
|
and create_time > NOW()::timestamp - (interval '1 second' * ?)
|
|
`
|
|
)
|
|
|
|
opts := getTestOpts(opt...)
|
|
withOperation := opts.withOperation
|
|
withCreateNotBefore := opts.withCreateNotBefore
|
|
|
|
whereKey := "resource-public-id"
|
|
if opts.withResourcePrivateId {
|
|
whereKey = "resource-private-id"
|
|
}
|
|
|
|
where := whereBase
|
|
whereArgs := []any{
|
|
whereKey,
|
|
resourceId,
|
|
}
|
|
|
|
if withOperation != oplog.OpType_OP_TYPE_UNSPECIFIED {
|
|
where = where + whereOptype
|
|
whereArgs = append(whereArgs, withOperation.String())
|
|
}
|
|
|
|
if withCreateNotBefore != nil {
|
|
where = where + whereCreateNotBefore
|
|
whereArgs = append(whereArgs, int(*withCreateNotBefore))
|
|
}
|
|
|
|
var metadata store.Metadata
|
|
if err := r.LookupWhere(context.Background(), &metadata, where, whereArgs); err != nil {
|
|
return err
|
|
}
|
|
|
|
var foundEntry oplog.Entry
|
|
if err := r.LookupWhere(context.Background(), &foundEntry, "id = ?", []any{metadata.EntryId}); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// getTestOpts - iterate the inbound TestOptions and return a struct
|
|
func getTestOpts(opt ...TestOption) testOptions {
|
|
opts := getDefaultTestOptions()
|
|
for _, o := range opt {
|
|
o(&opts)
|
|
}
|
|
return opts
|
|
}
|
|
|
|
// TestOption - how Options are passed as arguments
|
|
type TestOption func(*testOptions)
|
|
|
|
// options = how options are represented
|
|
type testOptions struct {
|
|
withCreateNotBefore *int
|
|
withOperation oplog.OpType
|
|
withTestDatabaseUrl string
|
|
withResourcePrivateId bool
|
|
withTemplate string
|
|
withLogLevel TestLogLevel
|
|
}
|
|
|
|
func getDefaultTestOptions() testOptions {
|
|
return testOptions{
|
|
withCreateNotBefore: nil,
|
|
withOperation: oplog.OpType_OP_TYPE_UNSPECIFIED,
|
|
}
|
|
}
|
|
|
|
// WithCreateNotBefore provides an option to specify that the create time is not
|
|
// before (nbf) N seconds
|
|
func WithCreateNotBefore(nbfDuration time.Duration) TestOption {
|
|
return func(o *testOptions) {
|
|
secs := int(nbfDuration.Truncate(time.Second).Seconds())
|
|
o.withCreateNotBefore = &secs
|
|
}
|
|
}
|
|
|
|
// WithOperation provides an option to specify the operation type
|
|
func WithOperation(op oplog.OpType) TestOption {
|
|
return func(o *testOptions) {
|
|
o.withOperation = op
|
|
}
|
|
}
|
|
|
|
// WithTestDatabaseUrl provides a way to specify an existing database for tests
|
|
func WithTestDatabaseUrl(url string) TestOption {
|
|
return func(o *testOptions) {
|
|
o.withTestDatabaseUrl = url
|
|
}
|
|
}
|
|
|
|
// WithResourcePrivateId provides a way to specify that the resource lookup action
|
|
// uses `resource-private-id` tag instead of the default `resource-public-id` tag
|
|
func WithResourcePrivateId(enable bool) TestOption {
|
|
return func(o *testOptions) {
|
|
o.withResourcePrivateId = enable
|
|
}
|
|
}
|
|
|
|
// WithTemplate provides a way to specify the source database template for creating
|
|
// a database.
|
|
func WithTemplate(template string) TestOption {
|
|
return func(o *testOptions) {
|
|
o.withTemplate = template
|
|
}
|
|
}
|
|
|
|
// TestLogLevel defines a test log level for the underlying db package (if applicable)
|
|
type TestLogLevel int
|
|
|
|
const (
|
|
// See WithTestLogLevel(...) test only option
|
|
DefaultTestLogLevel TestLogLevel = iota
|
|
SilentTestLogLevel
|
|
ErrorTestLogLevel
|
|
WarnTestLogLevel
|
|
InfoTestLogLevel
|
|
)
|
|
|
|
// WithTestLogLevel provides a way to specify a test log level for the
|
|
// underlying database package (if applicable).
|
|
func WithTestLogLevel(_ testing.TB, l TestLogLevel) TestOption {
|
|
return func(o *testOptions) {
|
|
o.withLogLevel = l
|
|
}
|
|
}
|
|
|
|
// TestCreateTables will create the test tables for the db pkg
|
|
func TestCreateTables(t testing.TB, conn *DB) {
|
|
t.Helper()
|
|
t.Cleanup(func() { testDropTables(t, conn) })
|
|
require := require.New(t)
|
|
testCtx := context.Background()
|
|
rw := New(conn)
|
|
_, err := rw.Exec(testCtx, testQueryCreateTables, nil)
|
|
require.NoError(err)
|
|
_, err = rw.Exec(testCtx, testQueryAddOplogEntries, nil)
|
|
require.NoError(err)
|
|
}
|
|
|
|
func testDropTables(t testing.TB, conn *DB) {
|
|
t.Helper()
|
|
require := require.New(t)
|
|
testCtx := context.Background()
|
|
rw := New(conn)
|
|
_, err := rw.Exec(testCtx, testQueryDropTables, nil)
|
|
require.NoError(err)
|
|
_, err = rw.Exec(testCtx, testQueryDeleteOplogEntries, nil)
|
|
require.NoError(err)
|
|
}
|
|
|
|
const (
|
|
testQueryCreateTables = `
|
|
begin;
|
|
|
|
-- create test tables used in the unit tests for the internal/db package
|
|
-- these tables (db_test_user, db_test_car, db_test_rental, db_test_scooter) are
|
|
-- not part of the boundary domain model... they are simply used for testing
|
|
-- the internal/db package
|
|
create table if not exists db_test_user (
|
|
id bigint generated always as identity primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
public_id text not null unique,
|
|
name text unique,
|
|
phone_number text,
|
|
email text,
|
|
version wt_version
|
|
);
|
|
|
|
create trigger
|
|
update_time_column
|
|
before
|
|
update on db_test_user
|
|
for each row execute procedure update_time_column();
|
|
|
|
-- define the immutable fields for db_test_user
|
|
create trigger
|
|
immutable_columns
|
|
before
|
|
update on db_test_user
|
|
for each row execute procedure immutable_columns('create_time');
|
|
|
|
create trigger
|
|
default_create_time_column
|
|
before
|
|
insert on db_test_user
|
|
for each row execute procedure default_create_time();
|
|
|
|
create trigger
|
|
update_version_column
|
|
after update on db_test_user
|
|
for each row execute procedure update_version_column();
|
|
|
|
create table if not exists db_test_car (
|
|
id bigint generated always as identity primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
public_id text not null unique,
|
|
name text unique,
|
|
model text,
|
|
mpg smallint
|
|
);
|
|
|
|
create trigger
|
|
update_time_column
|
|
before
|
|
update on db_test_car
|
|
for each row execute procedure update_time_column();
|
|
|
|
-- define the immutable fields for db_test_car
|
|
create trigger
|
|
immutable_columns
|
|
before
|
|
update on db_test_car
|
|
for each row execute procedure immutable_columns('create_time');
|
|
|
|
create trigger
|
|
default_create_time_column
|
|
before
|
|
insert on db_test_car
|
|
for each row execute procedure default_create_time();
|
|
|
|
create table if not exists db_test_rental (
|
|
id bigint generated always as identity primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
public_id text not null unique,
|
|
name text unique,
|
|
user_id bigint not null references db_test_user(id),
|
|
car_id bigint not null references db_test_car(id)
|
|
);
|
|
|
|
create trigger
|
|
update_time_column
|
|
before
|
|
update on db_test_rental
|
|
for each row execute procedure update_time_column();
|
|
|
|
-- define the immutable fields for db_test_rental
|
|
create trigger
|
|
immutable_columns
|
|
before
|
|
update on db_test_rental
|
|
for each row execute procedure immutable_columns('create_time');
|
|
|
|
create trigger
|
|
default_create_time_column
|
|
before
|
|
insert on db_test_rental
|
|
for each row execute procedure default_create_time();
|
|
|
|
|
|
create table if not exists db_test_scooter (
|
|
id bigint generated always as identity primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
private_id text not null unique,
|
|
name text unique,
|
|
model text,
|
|
mpg smallint
|
|
);
|
|
|
|
create trigger
|
|
update_time_column
|
|
before
|
|
update on db_test_scooter
|
|
for each row execute procedure update_time_column();
|
|
|
|
|
|
-- define the immutable fields for db_test_scooter
|
|
create trigger
|
|
immutable_columns
|
|
before
|
|
update on db_test_scooter
|
|
for each row execute procedure immutable_columns('create_time');
|
|
|
|
create trigger
|
|
default_create_time_column
|
|
before
|
|
insert on db_test_scooter
|
|
for each row execute procedure default_create_time();
|
|
|
|
create table if not exists db_test_accessory (
|
|
accessory_id bigint generated always as identity primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
description text not null
|
|
);
|
|
|
|
create trigger
|
|
update_time_column
|
|
before
|
|
update on db_test_accessory
|
|
for each row execute procedure update_time_column();
|
|
|
|
create trigger
|
|
immutable_columns
|
|
before
|
|
update on db_test_accessory
|
|
for each row execute procedure immutable_columns('create_time');
|
|
|
|
create trigger
|
|
default_create_time_column
|
|
before
|
|
insert on db_test_accessory
|
|
for each row execute procedure default_create_time();
|
|
|
|
|
|
create table if not exists db_test_scooter_accessory (
|
|
accessory_id bigint references db_test_accessory(accessory_id),
|
|
scooter_id bigint references db_test_scooter(id),
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
review text,
|
|
primary key(accessory_id, scooter_id)
|
|
);
|
|
|
|
create trigger
|
|
update_time_column
|
|
before
|
|
update on db_test_scooter_accessory
|
|
for each row execute procedure update_time_column();
|
|
|
|
create trigger
|
|
immutable_columns
|
|
before
|
|
update on db_test_scooter_accessory
|
|
for each row execute procedure immutable_columns('create_time');
|
|
|
|
create trigger
|
|
default_create_time_column
|
|
before
|
|
insert on db_test_scooter_accessory
|
|
for each row execute procedure default_create_time();
|
|
|
|
commit;
|
|
`
|
|
testQueryDropTables = `
|
|
begin;
|
|
drop table if exists db_test_user cascade;
|
|
drop table if exists db_test_car cascade;
|
|
drop table if exists db_test_rental cascade;
|
|
drop table if exists db_test_scooter cascade;
|
|
drop table if exists db_test_accessory cascade;
|
|
drop table if exists db_test_scooter_accessory cascade;
|
|
commit;
|
|
`
|
|
|
|
testQueryAddOplogEntries = `
|
|
begin;
|
|
|
|
insert into oplog_ticket (name, version)
|
|
values
|
|
('db_test_user', 1),
|
|
('db_test_car', 1),
|
|
('db_test_rental', 1),
|
|
('db_test_scooter', 1),
|
|
('db_test_accessory', 1),
|
|
('db_test_scooter_accessory', 1);
|
|
commit;
|
|
`
|
|
testQueryDeleteOplogEntries = `
|
|
begin;
|
|
|
|
delete from oplog_ticket where name in
|
|
(
|
|
'db_test_user',
|
|
'db_test_car',
|
|
'db_test_rental',
|
|
'db_test_scooter',
|
|
'db_test_accessory',
|
|
'db_test_scooter_accessory'
|
|
);
|
|
|
|
commit;
|
|
`
|
|
)
|