시퀀스 만들기 및 관리

이 페이지에서는 데이터 정의 언어(DDL) 문을 사용하여 Spanner에서 시퀀스를 만들고, 변경하고, 삭제하는 방법을 설명합니다. 기본값에서 시퀀스를 사용하여 기본 키 열을 채우는 방법도 확인할 수 있습니다.

GoogleSQL-dialect 데이터베이스PostgreSQL-dialect 데이터베이스에 대한 전체 시퀀스 DDL 구문 참조를 확인하세요.

시퀀스 만들기

다음 코드 예시는 Seq 시퀀스를 만들어서 Customers 테이블에서 기본 키의 기본값으로 사용하고, 3개의 새로운 행을 Customers 테이블에 삽입합니다.

GoogleSQL

C++

void CreateSequence(
    google::cloud::spanner_admin::DatabaseAdminClient admin_client,
    google::cloud::spanner::Client client, std::string const& project_id,
    std::string const& instance_id, std::string const& database_id) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  std::vector<std::string> statements;
  statements.emplace_back(R"""(
      CREATE SEQUENCE Seq
          OPTIONS (sequence_kind = 'bit_reversed_positive')
  )""");
  statements.emplace_back(R"""(
      CREATE TABLE Customers (
          CustomerId INT64 DEFAULT (GET_NEXT_SEQUENCE_VALUE(SEQUENCE Seq)),
          CustomerName STRING(1024)
      ) PRIMARY KEY (CustomerId)
  )""");
  auto metadata =
      admin_client.UpdateDatabaseDdl(database.FullName(), std::move(statements))
          .get();
  if (!metadata) throw std::move(metadata).status();
  std::cout << "Created `Seq` sequence and `Customers` table,"
            << " where the key column `CustomerId`"
            << " uses the sequence as a default value,"
            << " new DDL:\n"
            << metadata->DebugString();
  auto commit = client.Commit(
      [&client](google::cloud::spanner::Transaction txn)
          -> google::cloud::StatusOr<google::cloud::spanner::Mutations> {
        auto sql = google::cloud::spanner::SqlStatement(R"""(
            INSERT INTO Customers (CustomerName)
              VALUES ('Alice'),
                     ('David'),
                     ('Marc')
              THEN RETURN CustomerId
        )""");
        using RowType = std::tuple<std::int64_t>;
        auto rows = client.ExecuteQuery(std::move(txn), std::move(sql));
        // Note: This