blob: aa8c4ace59d80ae9e387e75e35232f26dd9a4156 [file] [log] [blame]
// Copyright (C) 2023 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.spannerrefdb;
import com.gerritforge.gerrit.globalrefdb.GlobalRefDbSystemError;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.List;
@Singleton
class DatabaseSchemaCreator implements LifecycleListener {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private DatabaseAdminClient dbAdminClient;
private DatabaseId dbId;
@Inject
DatabaseSchemaCreator(DatabaseAdminClient dbAdminClient, DatabaseId dbId) {
this.dbAdminClient = dbAdminClient;
this.dbId = dbId;
}
@Override
public void start() {
try {
dbAdminClient
.updateDatabaseDdl(
dbId.getInstanceId().getInstance(),
dbId.getDatabase(),
List.of(
"CREATE TABLE IF NOT EXISTS refs"
+ "("
+ "project STRING(MAX) NOT NULL,"
+ "ref STRING(MAX) NOT NULL,"
+ "value STRING(MAX) NOT NULL"
+ ")"
+ "PRIMARY KEY (project, ref)",
"CREATE TABLE IF NOT EXISTS locks"
+ "("
+ "project STRING(MAX) NOT NULL,"
+ "ref STRING(MAX) NOT NULL,"
+ "heartbeat TIMESTAMP OPTIONS (allow_commit_timestamp = true),"
+ "token TIMESTAMP OPTIONS (allow_commit_timestamp = true),"
+ "owner STRING(MAX) NOT NULL"
+ ")"
+ "PRIMARY KEY (project, ref)",
"ALTER TABLE refs ADD COLUMN IF NOT EXISTS "
+ "time TIMESTAMP OPTIONS (allow_commit_timestamp=true)",
"CREATE INDEX IF NOT EXISTS project_time ON refs(project, time)"),
null)
.get();
} catch (Exception e) {
throw new GlobalRefDbSystemError(
String.format("Failed to create schema in database [%s]", dbId), e);
}
logger.atInfo().log("Created schema in database [%s]", dbId);
}
@Override
public void stop() {}
}