com.google.cloud.spanner.DatabaseId Java Examples
The following examples show how to use
com.google.cloud.spanner.DatabaseId.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Poller.java From spanner-event-exporter with Apache License 2.0 | 6 votes |
private DatabaseClient configureDb() { final SpannerOptions options = SpannerOptions.newBuilder().build(); spanner = options.getService(); final DatabaseId db = DatabaseId.of(PROJECT_ID, instanceName, dbName); final String clientProject = spanner.getOptions().getProjectId(); if (!db.getInstanceId().getProject().equals(clientProject)) { log.error( "Invalid project specified. Project in the database id should match" + "the project name set in the environment variable GCLOUD_PROJECT. Expected: " + clientProject); stop(); System.exit(1); } final DatabaseClient dbClient = spanner.getDatabaseClient(db); return dbClient; }
Example #2
Source File: CreateDatabase.java From quetzal with Eclipse Public License 2.0 | 6 votes |
public static void main(String[] args) { SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); try { DatabaseId db = DatabaseId.of(options.getProjectId(), args[0], args[1]); // [END init_client] // This will return the default project id based on the environment. String clientProject = spanner.getOptions().getProjectId(); if (!db.getInstanceId().getProject().equals(clientProject)) { System.err.println("Invalid project specified. Project in the database id should match" + "the project name set in the environment variable GCLOUD_PROJECT. Expected: " + clientProject); } // [START init_client] DatabaseClient dbClient = spanner.getDatabaseClient(db); DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient(); createDatabase(dbAdminClient, db); } finally { spanner.close(); } }
Example #3
Source File: JdbcExamplesIT.java From java-docs-samples with Apache License 2.0 | 6 votes |
@BeforeClass public static void createTestDatabase() throws Exception { SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); dbClient = spanner.getDatabaseAdminClient(); if (instanceId == null) { Iterator<Instance> iterator = spanner.getInstanceAdminClient().listInstances().iterateAll().iterator(); if (iterator.hasNext()) { instanceId = iterator.next().getId().getInstance(); } } dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId); dbClient.dropDatabase(dbId.getInstanceId().getInstance(), dbId.getDatabase()); dbClient.createDatabase(instanceId, databaseId, Collections.emptyList()).get(); CreateTableExample.createTable(options.getProjectId(), instanceId, databaseId); }
Example #4
Source File: App.java From java-docs-samples with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { if (!(args.length == 3 || args.length == 4)) { printUsageAndExit(); } SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); try { String command = args[0]; DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]); DatabaseClient dbClient = spanner.getDatabaseClient(db); DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient(); switch (command) { case "create": create(dbAdminClient, db); break; default: printUsageAndExit(); } } finally { spanner.close(); } System.out.println("Closed client"); }
Example #5
Source File: SpannerSample.java From java-docs-samples with Apache License 2.0 | 6 votes |
static void listBackupOperations(InstanceAdminClient instanceAdminClient, DatabaseId databaseId) { Instance instance = instanceAdminClient.getInstance(databaseId.getInstanceId().getInstance()); // Get create backup operations for the sample database. String filter = String.format( "(metadata.database:%s) AND " + "(metadata.@type:type.googleapis.com/" + "google.spanner.admin.database.v1.CreateBackupMetadata)", databaseId.getName()); Page<Operation> operations = instance.listBackupOperations(Options.filter(filter)); for (Operation op : operations.iterateAll()) { try { CreateBackupMetadata metadata = op.getMetadata().unpack(CreateBackupMetadata.class); System.out.println( String.format( "Backup %s on database %s pending: %d%% complete", metadata.getName(), metadata.getDatabase(), metadata.getProgress().getProgressPercent())); } catch (InvalidProtocolBufferException e) { // The returned operation does not contain CreateBackupMetadata. System.err.println(e.getMessage()); } } }
Example #6
Source File: SpannerSample.java From java-docs-samples with Apache License 2.0 | 6 votes |
static void clientWithQueryOptions(DatabaseId db) { SpannerOptions options = SpannerOptions.newBuilder() .setDefaultQueryOptions( db, QueryOptions.newBuilder().setOptimizerVersion("1").build()) .build(); Spanner spanner = options.getService(); DatabaseClient dbClient = spanner.getDatabaseClient(db); try (ResultSet resultSet = dbClient .singleUse() .executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) { while (resultSet.next()) { System.out.printf( "%d %d %s\n", resultSet.getLong(0), resultSet.getLong(1), resultSet.getString(2)); } } }
Example #7
Source File: HelloSpanner.java From java-docs-samples with Apache License 2.0 | 6 votes |
DatabaseClient get() throws Throwable { if (!initialized) { synchronized (lock) { if (!initialized) { try { DatabaseId db = DatabaseId.of( SpannerOptions.getDefaultProjectId(), SPANNER_INSTANCE_ID, SPANNER_DATABASE_ID); client = createSpanner().getDatabaseClient(db); } catch (Throwable t) { error = t; } initialized = true; } } } if (error != null) { throw error; } return client; }
Example #8
Source File: SpannerAccessorTest.java From beam with Apache License 2.0 | 6 votes |
@Test public void testCreateOnlyOnce() { SpannerConfig config1 = SpannerConfig.create() .toBuilder() .setServiceFactory(serviceFactory) .setProjectId(StaticValueProvider.of("project")) .setInstanceId(StaticValueProvider.of("test1")) .setDatabaseId(StaticValueProvider.of("test1")) .build(); SpannerAccessor acc1 = SpannerAccessor.getOrCreate(config1); SpannerAccessor acc2 = SpannerAccessor.getOrCreate(config1); SpannerAccessor acc3 = SpannerAccessor.getOrCreate(config1); acc1.close(); acc2.close(); acc3.close(); // getDatabaseClient and close() only called once. verify(serviceFactory.mockSpanner(), times(1)) .getDatabaseClient(DatabaseId.of("project", "test1", "test1")); verify(serviceFactory.mockSpanner(), times(1)).close(); }
Example #9
Source File: SpannerTestKit.java From cloud-spanner-r2dbc with Apache License 2.0 | 6 votes |
private static void createTableIfNeeded(DatabaseId id, String tableName, String definition) { Boolean tableExists = Mono.from(connectionFactory.create()) .flatMapMany(c -> c.createStatement( "SELECT table_name FROM information_schema.tables WHERE table_name = @name") .bind("name", tableName) .execute()) .flatMap(result -> result.map((r, m) -> r)) .hasElements() .block(); if (!tableExists) { logger.info("Table " + tableName + " does not exist; creating"); try { dbAdminClient.updateDatabaseDdl( id.getInstanceId().getInstance(), id.getDatabase(), Collections.singletonList("CREATE TABLE " + tableName + definition), null) .get(); } catch (Exception e) { logger.info("Couldn't run DDL", e); } } }
Example #10
Source File: SpannerSample.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { if (args.length != 3) { printUsageAndExit(); } // [START init_client] SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); try { String command = args[0]; DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]); // [END init_client] // This will return the default project id based on the environment. String clientProject = spanner.getOptions().getProjectId(); if (!db.getInstanceId().getProject().equals(clientProject)) { System.err.println( "Invalid project specified. Project in the database id should match the" + "project name set in the environment variable GOOGLE_CLOUD_PROJECT. Expected: " + clientProject); printUsageAndExit(); } // Generate a backup id for the sample database. String backupName = String.format( "%s_%02d", db.getDatabase(), LocalDate.now().get(ChronoField.ALIGNED_WEEK_OF_YEAR)); BackupId backup = BackupId.of(db.getInstanceId(), backupName); // [START init_client] DatabaseClient dbClient = spanner.getDatabaseClient(db); DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient(); InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient(); // Use client here... // [END init_client] run(dbClient, dbAdminClient, instanceAdminClient, command, db, backup); } finally { spanner.close(); } // [END init_client] System.out.println("Closed client"); }
Example #11
Source File: SpannerSample.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** Get a database id to restore a backup to from the sample database id. */ static String createRestoredSampleDbId(DatabaseId database) { int index = database.getDatabase().indexOf('-'); String prefix = database.getDatabase().substring(0, index); String restoredDbId = database.getDatabase().replace(prefix, "restored"); if (restoredDbId.length() > 30) { restoredDbId = restoredDbId.substring(0, 30); } return restoredDbId; }
Example #12
Source File: QuickstartSample.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void main(String... args) throws Exception { if (args.length != 2) { System.err.println("Usage: QuickStartSample <instance_id> <database_id>"); return; } // Instantiates a client SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); // Name of your instance & database. String instanceId = args[0]; String databaseId = args[1]; try { // Creates a database client DatabaseClient dbClient = spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId)); // Queries the database ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1")); System.out.println("\n\nResults:"); // Prints the results while (resultSet.next()) { System.out.printf("%d\n\n", resultSet.getLong(0)); } } finally { // Closes the client which will free up the resources used spanner.close(); } }
Example #13
Source File: SpannerSampleIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
@BeforeClass public static void setUp() throws Exception { SpannerOptions options = SpannerOptions.newBuilder().build(); spanner = options.getService(); dbClient = spanner.getDatabaseAdminClient(); dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId); dbClient.dropDatabase(dbId.getInstanceId().getInstance(), dbId.getDatabase()); dbClient.dropDatabase( dbId.getInstanceId().getInstance(), SpannerSample.createRestoredSampleDbId(dbId)); }
Example #14
Source File: App.java From java-docs-samples with Apache License 2.0 | 5 votes |
static void delete(DatabaseAdminClient dbAdminClient, DatabaseId db) { try { dbAdminClient.dropDatabase(db.getInstanceId().getInstance(), db.getDatabase()); } catch (Exception e) { System.err.println("Error encountered while deleting database. Error message: " + e); } System.out.printf("Database deleted.\n"); }
Example #15
Source File: AppTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); dbClient = spanner.getDatabaseAdminClient(); dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId); dbClient.dropDatabase(dbId.getInstanceId().getInstance(), dbId.getDatabase()); }
Example #16
Source File: SpannerClient.java From java-docs-samples with Apache License 2.0 | 5 votes |
static DatabaseClient getDatabaseClient() { if (databaseClient == null) { databaseClient = spanner.getDatabaseClient(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DATABASE_ID)); } return databaseClient; }
Example #17
Source File: SpannerClient.java From java-docs-samples with Apache License 2.0 | 5 votes |
static DatabaseClient getDatabaseClient() { if (databaseClient == null) { databaseClient = spanner.getDatabaseClient(DatabaseId.of(PROJECT_ID, INSTANCE_ID, DATABASE_ID)); } return databaseClient; }
Example #18
Source File: SpannerIOWriteTest.java From beam with Apache License 2.0 | 5 votes |
@Test public void testRefCountedSpannerAccessorOnlyOnce() { SpannerConfig config1 = SpannerConfig.create() .toBuilder() .setServiceFactory(serviceFactory) .setProjectId(StaticValueProvider.of("project")) .setInstanceId(StaticValueProvider.of("test1")) .setDatabaseId(StaticValueProvider.of("test1")) .build(); SpannerIO.WriteToSpannerFn test1Fn = new SpannerIO.WriteToSpannerFn(config1, FailureMode.REPORT_FAILURES, null /* failedTag */); SpannerIO.WriteToSpannerFn test2Fn = new SpannerIO.WriteToSpannerFn(config1, FailureMode.REPORT_FAILURES, null /* failedTag */); SpannerIO.WriteToSpannerFn test3Fn = new SpannerIO.WriteToSpannerFn(config1, FailureMode.REPORT_FAILURES, null /* failedTag */); test1Fn.setup(); test2Fn.setup(); test3Fn.setup(); test2Fn.teardown(); test3Fn.teardown(); test1Fn.teardown(); // getDatabaseClient and close() only called once. verify(serviceFactory.mockSpanner(), times(1)) .getDatabaseClient(DatabaseId.of("project", "test1", "test1")); verify(serviceFactory.mockSpanner(), times(1)).close(); }
Example #19
Source File: SpannerWriteIT.java From beam with Apache License 2.0 | 5 votes |
private long countNumberOfRecords() { ResultSet resultSet = spanner .getDatabaseClient(DatabaseId.of(project, options.getInstanceId(), databaseName)) .singleUse() .executeQuery(Statement.of("SELECT COUNT(*) FROM " + options.getTable())); assertThat(resultSet.next(), is(true)); long result = resultSet.getLong(0); assertThat(resultSet.next(), is(false)); return result; }
Example #20
Source File: App.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { if (!(args.length == 3 || args.length == 4)) { printUsageAndExit(); } SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); try { String command = args[0]; DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]); DatabaseClient dbClient = spanner.getDatabaseClient(db); DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient(); switch (command) { case "create": create(dbAdminClient, db); break; case "insert": String insertType; try { insertType = args[3]; } catch (ArrayIndexOutOfBoundsException exception) { insertType = ""; } insert(dbClient, insertType); break; default: printUsageAndExit(); } } finally { spanner.close(); } System.out.println("Closed client"); }
Example #21
Source File: SpannerAccessorTest.java From beam with Apache License 2.0 | 5 votes |
@Test public void testRefCountedSpannerAccessorDifferentDbsOnlyOnce() { SpannerConfig config1 = SpannerConfig.create() .toBuilder() .setServiceFactory(serviceFactory) .setProjectId(StaticValueProvider.of("project")) .setInstanceId(StaticValueProvider.of("test1")) .setDatabaseId(StaticValueProvider.of("test1")) .build(); SpannerConfig config2 = config1 .toBuilder() .setInstanceId(StaticValueProvider.of("test2")) .setDatabaseId(StaticValueProvider.of("test2")) .build(); SpannerAccessor acc1a = SpannerAccessor.getOrCreate(config1); SpannerAccessor acc1b = SpannerAccessor.getOrCreate(config1); SpannerAccessor acc2a = SpannerAccessor.getOrCreate(config2); SpannerAccessor acc2b = SpannerAccessor.getOrCreate(config2); acc1a.close(); acc2a.close(); acc1b.close(); acc2b.close(); // getDatabaseClient called once each for the separate instances. verify(serviceFactory.mockSpanner(), times(1)) .getDatabaseClient(eq(DatabaseId.of("project", "test1", "test1"))); verify(serviceFactory.mockSpanner(), times(1)) .getDatabaseClient(eq(DatabaseId.of("project", "test2", "test2"))); verify(serviceFactory.mockSpanner(), times(2)).close(); }
Example #22
Source File: ClientLibraryOperations.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 5 votes |
/** * Constructs the {@link ClientLibraryOperations} object. */ public ClientLibraryOperations() { SpannerOptions spannerOptions = SpannerOptions.newBuilder().setProjectId(PROJECT_ID).build(); this.spanner = spannerOptions.getService(); this.databaseAdminClient = this.spanner.getDatabaseAdminClient(); this.databaseClient = this.spanner.getDatabaseClient( DatabaseId.of(PROJECT_ID, INSTANCE_NAME, DATABASE_NAME)); }
Example #23
Source File: FakeServiceFactory.java From beam with Apache License 2.0 | 5 votes |
public FakeServiceFactory() { synchronized (lock) { index = count++; mockSpanners.add(mock(Spanner.class, withSettings().serializable())); mockDatabaseClients.add(mock(DatabaseClient.class, withSettings().serializable())); mockBatchClients.add(mock(BatchClient.class, withSettings().serializable())); } when(mockSpanner().getDatabaseClient(Matchers.any(DatabaseId.class))) .thenReturn(mockDatabaseClient()); when(mockSpanner().getBatchClient(Matchers.any(DatabaseId.class))) .thenReturn(mockBatchClient()); }
Example #24
Source File: DatabaseSelect.java From google-cloud-java with Apache License 2.0 | 5 votes |
public static void main(String... args) throws Exception { if (args.length != 2) { System.err.println("Usage: QuickStartSample <instance_id> <database_id>"); return; } // Instantiates a client SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); // Name of your instance & database. String instanceId = args[0]; String databaseId = args[1]; try { // Creates a database client DatabaseClient dbClient = spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId)); // Queries the database try (ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"))) { System.out.println("\n\nResults:"); // Prints the results while (resultSet.next()) { System.out.printf("%d\n\n", resultSet.getLong(0)); } } } finally { // Closes the client which will free up the resources used spanner.close(); } }
Example #25
Source File: GcpSpannerAutoConfiguration.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Bean @ConditionalOnMissingBean public SpannerDatabaseAdminTemplate spannerDatabaseAdminTemplate( Supplier<DatabaseClient> databaseClientProvider, DatabaseAdminClient adminClient, Supplier<DatabaseId> databaseIdProvider) { return new SpannerDatabaseAdminTemplate(adminClient, databaseClientProvider, databaseIdProvider); }
Example #26
Source File: SpannerSnippets.java From google-cloud-java with Apache License 2.0 | 5 votes |
DatabaseClient getDatabaseClient() { // [START get_db_client] SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); final String project = "test-project"; final String instance = "test-instance"; final String database = "example-db"; DatabaseId db = DatabaseId.of(project, instance, database); DatabaseClient dbClient = spanner.getDatabaseClient(db); // [END get_db_client] return dbClient; }
Example #27
Source File: SpannerSnippets.java From google-cloud-java with Apache License 2.0 | 5 votes |
BatchClient getBatchClient() { // [START get_batch_client] SpannerOptions options = SpannerOptions.newBuilder().build(); Spanner spanner = options.getService(); final String project = "test-project"; final String instance = "test-instance"; final String database = "example-db"; DatabaseId db = DatabaseId.of(project, instance, database); BatchClient batchClient = spanner.getBatchClient(db); // [END get_batch_client] return batchClient; }
Example #28
Source File: SpannerDatabaseAdminTemplateTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Before public void setup() { this.databaseAdminClient = mock(DatabaseAdminClient.class); this.databaseClient = mock(DatabaseClient.class); this.mockDatabasePage = mock(Page.class); this.databaseId = DatabaseId.of("fakeproject", "fakeinstance", "fakedb"); this.spannerDatabaseAdminTemplate = new SpannerDatabaseAdminTemplate( this.databaseAdminClient, () -> this.databaseClient, () -> this.databaseId); this.ddlList = new ArrayList<>(); this.ddlList.add("describe Something"); when(this.databaseAdminClient.listDatabases("fakeinstance")).thenReturn(this.mockDatabasePage); }
Example #29
Source File: SpannerBenchWrapperImpl.java From google-cloud-java with Apache License 2.0 | 5 votes |
public SpannerBenchWrapperImpl() { SpannerOptions options = SpannerOptions.newBuilder().setProjectId("test-project-id").build(); spanner = options.getService(); dbClient = spanner.getDatabaseClient( DatabaseId.of(options.getProjectId(), "test-instance", "test-db")); }
Example #30
Source File: CreateDatabase.java From quetzal with Eclipse Public License 2.0 | 5 votes |
static void createDatabase(DatabaseAdminClient dbAdminClient, DatabaseId id) { Operation<Database, CreateDatabaseMetadata> op = dbAdminClient.createDatabase( id.getInstanceId().getInstance(), id.getDatabase(), Arrays.asList("CREATE TABLE DPH (\n" + " subject STRING(MAX) NOT NULL,\n" + " col_0 ARRAY<STRING(MAX)>, \n" + " col_1 ARRAY<STRING(MAX)>, \n" + " col_2 STRING(MAX), \n" + " col_3 STRING(MAX), \n" + " col_4 STRING(MAX), \n" + " col_5 STRING(MAX), \n" + " col_6 STRING(MAX), \n" + " col_7 ARRAY<STRING(MAX)>, \n" + " col_8 STRING(MAX), \n" + " col_9 STRING(MAX), \n" + " col_10 STRING(MAX), \n" + " col_11 STRING(MAX), \n" + " col_12 STRING(MAX), \n" + " col_13 STRING(MAX), \n" + " col_14 ARRAY<STRING(MAX)>, \n" + " col_15 STRING(MAX), \n" + " col_16 STRING(MAX)) \n" + " PRIMARY KEY (subject)")); Database db = op.waitFor().getResult(); System.out.println("Created database [" + db.getId() + "]"); }