github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/datastore/crdb/migrations/zz_migration.0001_initial_schema.go (about)

     1  package migrations
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/jackc/pgx/v5"
     7  )
     8  
     9  const (
    10  	createNamespaceConfig = `CREATE TABLE namespace_config (
    11      namespace VARCHAR PRIMARY KEY,
    12      serialized_config BYTEA NOT NULL,
    13      timestamp TIMESTAMP WITHOUT TIME ZONE DEFAULT now() NOT NULL
    14  );`
    15  
    16  	createRelationTuple = `CREATE TABLE relation_tuple (
    17      namespace VARCHAR NOT NULL,
    18      object_id VARCHAR NOT NULL,
    19      relation VARCHAR NOT NULL,
    20      userset_namespace VARCHAR NOT NULL,
    21      userset_object_id VARCHAR NOT NULL,
    22      userset_relation VARCHAR NOT NULL,
    23      timestamp TIMESTAMP WITHOUT TIME ZONE DEFAULT now() NOT NULL,
    24      CONSTRAINT pk_relation_tuple PRIMARY KEY (namespace, object_id, relation, userset_namespace, userset_object_id, userset_relation)
    25  );`
    26  
    27  	createSchemaVersion = `CREATE TABLE schema_version (
    28  	version_num VARCHAR NOT NULL
    29  );`
    30  
    31  	insertEmptyVersion = `INSERT INTO schema_version (version_num) VALUES ('');`
    32  
    33  	createReverseQueryIndex = `CREATE INDEX ix_relation_tuple_by_subject ON relation_tuple (userset_object_id, userset_namespace, userset_relation, namespace, relation)`
    34  	createReverseCheckIndex = `CREATE INDEX ix_relation_tuple_by_subject_relation ON relation_tuple (userset_namespace, userset_relation, namespace, relation)`
    35  )
    36  
    37  func init() {
    38  	if err := CRDBMigrations.Register("initial", "", noNonAtomicMigration, func(ctx context.Context, tx pgx.Tx) error {
    39  		statements := []string{
    40  			createNamespaceConfig,
    41  			createRelationTuple,
    42  			createSchemaVersion,
    43  			insertEmptyVersion,
    44  			createReverseQueryIndex,
    45  			createReverseCheckIndex,
    46  		}
    47  		for _, stmt := range statements {
    48  			_, err := tx.Exec(ctx, stmt)
    49  			if err != nil {
    50  				return err
    51  			}
    52  		}
    53  		return nil
    54  	}); err != nil {
    55  		panic("failed to register migration: " + err.Error())
    56  	}
    57  }