TIMESTAMP 열 추가

TIMESTAMP 열을 추가하여 스키마를 업데이트합니다.

코드 샘플

C#

Cloud Spanner용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Spanner 클라이언트 라이브러리를 참조하세요.

// Initialize request argument(s).
string connectionString =
    $"Data Source=projects/{projectId}/instances/"
    + $"{instanceId}/databases/{databaseId}";
string alterStatement =
    "ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP "
    + " OPTIONS (allow_commit_timestamp=true)";
// Make the request.
using (var connection = new SpannerConnection(connectionString))
{
    var updateCmd = connection.CreateDdlCommand(alterStatement);
    await updateCmd.ExecuteNonQueryAsync();
}
Console.WriteLine("Added LastUpdateTime as a commit timestamp column in Albums table.");

C++

Cloud Spanner용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Spanner 클라이언트 라이브러리를 참조하세요.

void AddTimestampColumn(google::cloud::spanner::DatabaseAdminClient 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);
  auto metadata =
      client
          .UpdateDatabase(
              database,
              {"ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP "
               "OPTIONS (allow_commit_timestamp=true)"})
          .get();
  if (!metadata) throw std::runtime_error(metadata.status().message());
  std::cout << "Added LastUpdateTime column\n";
}

Go

Cloud Spanner용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Spanner 클라이언트 라이브러리를 참조하세요.


import (
	"context"
	"fmt"
	"io"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	adminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1"
)

func addCommitTimestamp(w io.Writer, db string) error {
	ctx := context.Background()
	adminClient, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()

	op, err := adminClient.UpdateDatabaseDdl(ctx, &adminpb.UpdateDatabaseDdlRequest{
		Database: db,
		Statements: []string{
			"ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP " +
				"OPTIONS (allow_commit_timestamp=true)",
		},
	})
	if err != nil {
		return err
	}
	if err := op.Wait(ctx); err != nil {
		return err
	}
	fmt.Fprintf(w, "Added LastUpdateTime as a commit timestamp column in Albums table\n")
	return nil
}

자바

Cloud Spanner용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Spanner 클라이언트 라이브러리를 참조하세요.

static void addCommitTimestamp(DatabaseAdminClient adminClient, DatabaseId dbId) {
  OperationFuture<Void, UpdateDatabaseDdlMetadata> op =
      adminClient.updateDatabaseDdl(
          dbId.getInstanceId().getInstance(),
          dbId.getDatabase(),
          Arrays.asList(
              "ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP "
                  + "OPTIONS (allow_commit_timestamp=true)"),
          null);
  try {
    // Initiate the request which returns an OperationFuture.
    op.get();
    System.out.println("Added LastUpdateTime as a commit timestamp column in Albums table.");
  } catch (ExecutionException e) {
    // If the operation failed during execution, expose the cause.
    throw (SpannerException) e.getCause();
  } catch (InterruptedException e) {
    // Throw when a thread is waiting, sleeping, or otherwise occupied,
    // and the thread is interrupted, either before or during the activity.
    throw SpannerExceptionFactory.propagateInterrupt(e);
  }
}

Node.js

Cloud Spanner용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Spanner 클라이언트 라이브러리를 참조하세요.

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);

const request = [
  `ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP OPTIONS
  (allow_commit_timestamp=true)`,
];

// Adds a new commit timestamp column to the Albums table
try {
  const [operation] = await database.updateSchema(request);

  console.log('Waiting for operation to complete...');

  await operation.promise();

  console.log(
    'Added LastUpdateTime as a commit timestamp column in Albums table.'
  );
} catch (err) {
  console.error('ERROR:', err);
} finally {
  // Close the database when finished.
  database.close();
}

PHP

Cloud Spanner용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Spanner 클라이언트 라이브러리를 참조하세요.

use Google\Cloud\Spanner\SpannerClient;

/**
 * Adds a commit timestamp column to a table.
 * Example:
 * ```
 * add_timestamp_column($instanceId, $databaseId);
 * ```
 *
 * @param string $instanceId The Spanner instance ID.
 * @param string $databaseId The Spanner database ID.
 */
function add_timestamp_column($instanceId, $databaseId)
{
    $spanner = new SpannerClient();
    $instance = $spanner->instance($instanceId);
    $database = $instance->database($databaseId);

    $operation = $database->updateDdl(
        "ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP OPTIONS (allow_commit_timestamp=true)"
    );

    print('Waiting for operation to complete...' . PHP_EOL);
    $operation->pollUntilComplete();

    printf('Added LastUpdateTime as a commit timestamp column in Albums table' . PHP_EOL);
}

Python

Cloud Spanner용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Spanner 클라이언트 라이브러리를 참조하세요.

def add_timestamp_column(instance_id, database_id):
    """ Adds a new TIMESTAMP column to the Albums table in the example database.
    """
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)

    database = instance.database(database_id)

    operation = database.update_ddl(
        [
            "ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP "
            "OPTIONS(allow_commit_timestamp=true)"
        ]
    )

    print("Waiting for operation to complete...")
    operation.result(120)

    print(
        'Altered table "Albums" on database {} on instance {}.'.format(
            database_id, instance_id
        )
    )

Ruby

Cloud Spanner용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud Spanner 클라이언트 라이브러리를 참조하세요.

# project_id  = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"

require "google/cloud/spanner"

spanner  = Google::Cloud::Spanner.new project: project_id
instance = spanner.instance instance_id
database = instance.database database_id

job = database.update statements: [
  "ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP
   OPTIONS (allow_commit_timestamp=true)"
]

puts "Waiting for database update to complete"

job.wait_until_done!

puts "Added the LastUpdateTime as a commit timestamp column in Albums table"

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.