com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata Java Examples

The following examples show how to use com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata. 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: CloudSpannerConnection.java    From spanner-jdbc with MIT License 6 votes vote down vote up
/**
 * Execute one or more DDL-statements on the database and wait for it to finish or return after
 * syntax check (when running in async mode). Calling this method will also automatically commit
 * the currently running transaction.
 * 
 * @param inputSql The DDL-statement(s) to execute. Some statements may end up not being sent to
 *        Cloud Spanner if they contain IF [NOT] EXISTS clauses. The driver will check whether the
 *        condition is met, and only then will it be sent to Cloud Spanner.
 * @return Nothing
 * @throws SQLException If an error occurs during the execution of the statement.
 */
public Void executeDDL(List<String> inputSql) throws SQLException {
  if (!getAutoCommit())
    commit();
  // Check for IF [NOT] EXISTS statements
  List<String> sql = getActualSql(inputSql);
  if (!sql.isEmpty()) {
    try {
      Operation<Void, UpdateDatabaseDdlMetadata> operation =
          adminClient.updateDatabaseDdl(database.instance, database.database, sql, null);
      if (asyncDdlOperations) {
        operations.addOperation(sql, operation);
      } else {
        do {
          operation = operation.waitFor();
        } while (!operation.isDone());
      }
      return operation.getResult();
    } catch (SpannerException e) {
      throw new CloudSpannerSQLException("Could not execute DDL statement(s) "
          + String.join("\n;\n", sql) + ": " + e.getMessage(), e);
    }
  }
  return null;
}
 
Example #2
Source File: RunningOperationsStoreTest.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private Operation<Void, UpdateDatabaseDdlMetadata> mockOperation(boolean error) {
  @SuppressWarnings("unchecked")
  Operation<Void, UpdateDatabaseDdlMetadata> op = mock(Operation.class);
  when(op.getName()).then(new Returns("TEST_OPERATION"));
  when(op.isDone()).then(new Answer<Boolean>() {
    @Override
    public Boolean answer(InvocationOnMock invocation) throws Throwable {
      return reportDone;
    }
  });
  when(op.reload()).then(new Returns(op));
  if (error)
    when(op.getResult()).thenThrow(SpannerExceptionFactory
        .newSpannerException(ErrorCode.INVALID_ARGUMENT, "Some exception"));
  else
    when(op.getResult()).then(new Returns(null));
  UpdateDatabaseDdlMetadata metadata = UpdateDatabaseDdlMetadata.getDefaultInstance();
  when(op.getMetadata()).then(new Returns(metadata));

  return op;
}
 
Example #3
Source File: ClientLibraryOperations.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Runs the DDL statement to create a single table.
 */
public void createSingleTable() {
  List<String> airportDdl = loadDdlStrings(DDL_SMALL);
  OperationFuture<Void, UpdateDatabaseDdlMetadata> ddlFuture =
      this.databaseAdminClient.updateDatabaseDdl(
          INSTANCE_NAME, DATABASE_NAME, airportDdl, null);

  try {
    ddlFuture.get();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #4
Source File: ClientLibraryOperations.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Drops a single table.
 */
public void deleteSingleTable() {
  OperationFuture<Void, UpdateDatabaseDdlMetadata> ddlFuture =
      this.databaseAdminClient.updateDatabaseDdl(
          INSTANCE_NAME,
          DATABASE_NAME,
          Collections.singletonList("DROP TABLE " + AIRPORT_TABLE), null);

  try {
    ddlFuture.get();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #5
Source File: ClientLibraryOperations.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Runs DDL to create a large number of tables.
 */
public void runDdlLarge() {
  List<String> airportDdl = loadDdlStrings(DDL_LARGE);
  OperationFuture<Void, UpdateDatabaseDdlMetadata> ddlFuture =
      this.databaseAdminClient.updateDatabaseDdl(
          INSTANCE_NAME, DATABASE_NAME, airportDdl, null);

  try {
    ddlFuture.get();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #6
Source File: CustomStatementsTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testShowDDLOperations() throws SQLException, NoSuchFieldException, SecurityException,
    IllegalArgumentException, IllegalAccessException {
  final String ddl =
      "CREATE TABLE FOO (ID INT64 NOT NULL, NAME STRING(100) NOT NULL) PRIMARY KEY (ID)";

  Field adminClientField = CloudSpannerConnection.class.getDeclaredField("adminClient");
  adminClientField.setAccessible(true);
  DatabaseAdminClient adminClient = mock(DatabaseAdminClient.class);
  @SuppressWarnings("unchecked")
  Operation<Void, UpdateDatabaseDdlMetadata> operation = mock(Operation.class);
  when(operation.reload()).then(new Returns(operation));
  when(operation.getName()).then(new Returns("test"));
  when(adminClient.updateDatabaseDdl(any(), any(), any(), any())).then(new Returns(operation));
  adminClientField.set(connection, adminClient);
  Statement statement = connection.createStatement();
  assertFalse(statement.execute("SET_CONNECTION_PROPERTY AsyncDdlOperations=true"));
  assertEquals(1, statement.getUpdateCount());
  try (ResultSet rs = statement.executeQuery("SHOW_DDL_OPERATIONS")) {
    assertFalse(rs.next());
  }
  statement.execute(ddl);
  try (ResultSet rs = statement.executeQuery("SHOW_DDL_OPERATIONS")) {
    assertTrue(rs.next());
    assertEquals("test", rs.getString("NAME"));
    assertNotNull(rs.getTimestamp("TIME_STARTED"));
    assertEquals(ddl, rs.getString("STATEMENT"));
    assertFalse(rs.getBoolean("DONE"));
    assertNull(rs.getString("EXCEPTION"));
    assertFalse(rs.next());
  }
}
 
Example #7
Source File: SpannerDatabaseAdminTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void executeDdlStrings_createsDatabaseIfMissing() throws Exception {
	when(this.mockDatabasePage.getValues()).thenReturn(Arrays.asList(
			new Database(this.databaseId, State.READY, this.databaseAdminClient)));

	OperationFuture<Void, UpdateDatabaseDdlMetadata> mockFuture = mock(OperationFuture.class);
	when(this.databaseAdminClient.updateDatabaseDdl("fakeinstance", "fakedb", this.ddlList, null)).thenReturn(mockFuture);
	when(mockFuture.get()).thenReturn(null);

	this.spannerDatabaseAdminTemplate.executeDdlStrings(this.ddlList, true);

	verify(this.databaseAdminClient, times(0)).createDatabase("fakeinstance", "fakedb", Arrays.asList("describe Something"));
	verify(this.databaseAdminClient).updateDatabaseDdl("fakeinstance", "fakedb", this.ddlList, null);
}
 
Example #8
Source File: ApplyDDLTransform.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
@Override
public PCollection<Ddl> expand(PCollection<Ddl> input) {
  return input.apply(
      "Apply DDL statements",
      ParDo.of(
          new DoFn<Ddl, Ddl>() {

            private transient ExposedSpannerAccessor spannerAccessor;

            @Setup
            public void setup() {
              spannerAccessor = ExposedSpannerAccessor.create(spannerConfig);
            }

            @Teardown
            public void teardown() {
              spannerAccessor.close();
            }

            @ProcessElement
            public void processElement(ProcessContext c) {
              Ddl ddl = c.element();
              DatabaseAdminClient databaseAdminClient = spannerAccessor.getDatabaseAdminClient();
              List<String> statements = c.sideInput(pendingDDLStatements);
              if (!statements.isEmpty()) {
                // This just kicks off the applying the DDL statements.
                // It does not wait for it to complete.
                OperationFuture<Void, UpdateDatabaseDdlMetadata> op =
                    databaseAdminClient.updateDatabaseDdl(
                        spannerConfig.getInstanceId().get(),
                        spannerConfig.getDatabaseId().get(),
                        statements,
                        null);
                if (waitForApply.get()) {
                  try {
                    op.get();
                  } catch (InterruptedException | ExecutionException e) {
                    throw new RuntimeException(e);
                  }
                }
              }
              c.output(ddl);
            }
          })
      .withSideInputs(pendingDDLStatements));
}
 
Example #9
Source File: RunningOperationsStore.java    From spanner-jdbc with MIT License 4 votes vote down vote up
private DdlOperation(Timestamp timeStarted, List<String> sql,
    Operation<Void, UpdateDatabaseDdlMetadata> operation) {
  this.timeStarted = timeStarted;
  this.sql = new ArrayList<>(sql);
  this.operation = operation;
}
 
Example #10
Source File: RunningOperationsStore.java    From spanner-jdbc with MIT License 4 votes vote down vote up
void addOperation(List<String> sql, Operation<Void, UpdateDatabaseDdlMetadata> operation) {
  operations.add(new DdlOperation(Timestamp.now(), sql, operation));
}