Skip to content

Commit 43a338a

Browse files
committed
update tests
1 parent 4d832cf commit 43a338a

File tree

7 files changed

+286
-32
lines changed

7 files changed

+286
-32
lines changed

astra-db-java/src/main/java/com/datastax/astra/client/admin/AstraDBAdmin.java

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -319,18 +319,16 @@ public DatabaseInfo getDatabaseInfo(@NonNull UUID id) {
319319
*
320320
* @param databaseId
321321
* database identifier
322-
* @param keyspace
322+
* @param options
323323
* target keyspace name
324324
* @return
325325
* database client
326326
*/
327-
public com.datastax.astra.client.databases.Database getDatabase(UUID databaseId, String keyspace) {
327+
public com.datastax.astra.client.databases.Database getDatabase(UUID databaseId, DatabaseOptions dbOptions) {
328328
Assert.notNull(databaseId, "databaseId");
329-
Assert.hasLength(keyspace, "keyspace");
330329
if (!adminOptions.getDataAPIClientOptions().isAstra()) {
331330
throwErrorRestrictedAstra("getDatabase(id, keyspace)", adminOptions.getDataAPIClientOptions().getDestination());
332331
}
333-
334332
String databaseRegion = devopsDbClient
335333
.findById(databaseId.toString())
336334
.map(db -> db.getInfo().getRegion())
@@ -339,13 +337,26 @@ public com.datastax.astra.client.databases.Database getDatabase(UUID databaseId,
339337
AstraApiEndpoint astraApiEndpoint = new AstraApiEndpoint(databaseId,
340338
databaseRegion, adminOptions.getDataAPIClientOptions().getAstraEnvironment());
341339

342-
// Accessing DB with the right keyspace
343-
DatabaseOptions dbOptions = new DatabaseOptions(this.adminOptions.getToken(), this.adminOptions.getDataAPIClientOptions())
344-
.keyspace(keyspace);
345-
346340
return new com.datastax.astra.client.databases.Database(astraApiEndpoint.getApiEndPoint(), dbOptions);
347341
}
348342

343+
/**
344+
* Access the database functions.
345+
*
346+
* @param databaseId
347+
* database identifier
348+
* @param keyspace
349+
* target keyspace name
350+
* @return
351+
* database client
352+
*/
353+
public com.datastax.astra.client.databases.Database getDatabase(UUID databaseId, String keyspace) {
354+
return getDatabase(databaseId, new DatabaseOptions(
355+
this.adminOptions.getToken(),
356+
this.adminOptions.getDataAPIClientOptions())
357+
.keyspace(keyspace));
358+
}
359+
349360
/**
350361
* Access the database functions.
351362
*

astra-db-java/src/main/java/com/datastax/astra/client/databases/Database.java

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,11 @@ public class Database extends AbstractCommandRunner<DatabaseOptions> {
110110
*/
111111
private final String rootEndpoint;
112112

113+
/**
114+
* Database information cached if (getInfo()) is called
115+
*/
116+
private DatabaseInfo cachedDbInfo;
117+
113118
/**
114119
* Initializes a {@link Database} instance with the specified API endpoint and connection options.
115120
* This constructor configures the database client to interact with the Data API at the provided
@@ -199,14 +204,51 @@ public UUID getId() {
199204

200205
/**
201206
* Retrieves information about the current database, including metadata and configuration details.
202-
* This method interacts with the administration client to fetch database information.
207+
*
208+
* <p>This method interacts with the devops API to fetch database information. To optimize
209+
* performance, the database information is cached after the first retrieval. Subsequent calls to this
210+
* method return the cached {@link DatabaseInfo} object unless the cache is invalidated externally.</p>
211+
*
212+
* <p>Example usage:</p>
213+
* <pre>
214+
* {@code
215+
* DatabaseInfo info = database.getInfo();
216+
* System.out.println("Database Name: " + info.getName());
217+
* System.out.println("Database Version: " + info.getVersion());
218+
* }
219+
* </pre>
203220
*
204221
* @return A {@link DatabaseInfo} object containing details about the current database.
205222
* @throws IllegalStateException if the database information cannot be retrieved or if the
206223
* database is not properly configured for administration operations.
207224
*/
208225
public DatabaseInfo getInfo() {
209-
return getAdmin().getDatabaseInfo(getId());
226+
if (cachedDbInfo == null) {
227+
cachedDbInfo = getAdmin().getDatabaseInfo(getId());
228+
}
229+
return cachedDbInfo;
230+
}
231+
232+
/**
233+
* Retrieves the name of the current database.
234+
*
235+
* <p>This method provides a convenient way to access the database name from the {@link DatabaseInfo}
236+
* object returned by {@link #getInfo()}. It encapsulates the process of fetching and extracting
237+
* the database name.</p>
238+
*
239+
* <p>Example usage:</p>
240+
* <pre>
241+
* {@code
242+
* String dbName = database.getName();
243+
* System.out.println("Database Name: " + dbName);
244+
* }
245+
* </pre>
246+
*
247+
* @return The name of the current database as a {@link String}.
248+
* @throws IllegalStateException if the database information cannot be retrieved or is unavailable.
249+
*/
250+
public String getName() {
251+
return getInfo().getName();
210252
}
211253

212254
/**
@@ -1367,16 +1409,4 @@ public String getApiEndpoint() {
13671409
return this.apiEndpoint;
13681410
}
13691411

1370-
/**
1371-
* Register a listener to execute commands on the collection. Please now use {@link BaseOptions}.
1372-
*
1373-
* @param logger
1374-
* name for the logger
1375-
* @param commandObserver
1376-
* class for the logger
1377-
*/
1378-
public void registerListener(String logger, CommandObserver commandObserver) {
1379-
this.options.registerObserver(logger, commandObserver);
1380-
}
1381-
13821412
}

astra-db-java/src/test/java/com/datastax/astra/test/integration/AbstractDatabaseTest.java

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,25 @@
66
import com.datastax.astra.client.collections.documents.Document;
77
import com.datastax.astra.client.collections.results.CollectionInsertManyResult;
88
import com.datastax.astra.client.collections.results.CollectionInsertOneResult;
9+
import com.datastax.astra.client.core.auth.EmbeddingAPIKeyHeaderProvider;
910
import com.datastax.astra.client.core.commands.Command;
1011
import com.datastax.astra.client.core.types.ObjectId;
1112
import com.datastax.astra.client.core.types.UUIDv6;
1213
import com.datastax.astra.client.core.types.UUIDv7;
1314
import com.datastax.astra.client.core.vector.SimilarityMetric;
15+
import com.datastax.astra.client.databases.options.ListTablesOptions;
1416
import com.datastax.astra.client.exception.DataAPIException;
17+
import com.datastax.astra.client.tables.Table;
18+
import com.datastax.astra.client.tables.TableDefinition;
19+
import com.datastax.astra.client.tables.TableDescriptor;
20+
import com.datastax.astra.client.tables.TableOptions;
21+
import com.datastax.astra.client.tables.columns.ColumnDefinitionVector;
22+
import com.datastax.astra.client.tables.columns.ColumnTypes;
23+
import com.datastax.astra.client.tables.ddl.CreateTableOptions;
24+
import com.datastax.astra.client.tables.row.Row;
1525
import com.datastax.astra.internal.api.DataAPIResponse;
26+
import com.datastax.astra.test.model.TableEntityGameWithAnnotation;
27+
import com.datastax.astra.test.model.TableEntityGameWithAnnotationAllHints;
1628
import com.fasterxml.jackson.annotation.JsonProperty;
1729
import lombok.AllArgsConstructor;
1830
import lombok.Data;
@@ -23,6 +35,7 @@
2335
import org.junit.jupiter.api.Test;
2436
import org.junit.jupiter.api.TestMethodOrder;
2537

38+
import java.time.Duration;
2639
import java.util.List;
2740
import java.util.Optional;
2841
import java.util.UUID;
@@ -31,6 +44,10 @@
3144
import static com.datastax.astra.client.collections.CollectionDefaultIdTypes.UUIDV6;
3245
import static com.datastax.astra.client.collections.CollectionDefaultIdTypes.UUIDV7;
3346
import static com.datastax.astra.client.core.query.Filters.eq;
47+
import static com.datastax.astra.client.core.query.Sort.ascending;
48+
import static com.datastax.astra.client.core.vector.SimilarityMetric.COSINE;
49+
import static com.datastax.astra.client.tables.ddl.DropTableOptions.IF_EXISTS;
50+
import static java.time.Duration.ofSeconds;
3451
import static org.assertj.core.api.Assertions.assertThat;
3552
import static org.assertj.core.api.Assertions.assertThatThrownBy;
3653

@@ -337,4 +354,74 @@ public void shouldCollectionWorkWithUUIDv7() {
337354
resultsList.getInsertedIds().forEach(id -> assertThat(id).isInstanceOf(UUIDv7.class));
338355
}
339356

357+
// === TABLES ===
358+
359+
@Test
360+
@Order(14)
361+
public void shouldCreateTables() {
362+
// Definition of the table in fluent style
363+
TableDefinition tableDefinition = new TableDefinition()
364+
.addColumnText("match_id")
365+
.addColumnInt("round")
366+
.addColumnVector("m_vector", new ColumnDefinitionVector().dimension(3).metric(COSINE))
367+
.addColumn("score", ColumnTypes.INT)
368+
.addColumn("when", ColumnTypes.TIMESTAMP)
369+
.addColumn("winner", ColumnTypes.TEXT)
370+
.addColumnSet("fighters", ColumnTypes.UUID)
371+
.addPartitionBy("match_id")
372+
.addPartitionSort(ascending("round"));
373+
assertThat(tableDefinition).isNotNull();
374+
375+
// Minimal creation
376+
Table<Row> table1 = getDatabase().createTable("game1", tableDefinition);
377+
assertThat(table1).isNotNull();
378+
assertThat(getDatabase().tableExists("game1")).isTrue();
379+
380+
// Creation with a fully annotated bean
381+
String tableXName = getDatabase().getTableName(TableEntityGameWithAnnotation.class);
382+
Table<TableEntityGameWithAnnotation> tableX = getDatabase().createTable(
383+
TableEntityGameWithAnnotation.class,
384+
CreateTableOptions.IF_NOT_EXISTS);
385+
assertThat(getDatabase().tableExists(tableXName)).isTrue();
386+
387+
// Minimal creation
388+
String tableYName = getDatabase().getTableName(TableEntityGameWithAnnotationAllHints.class);
389+
Table<TableEntityGameWithAnnotationAllHints> tableY = getDatabase().createTable(
390+
TableEntityGameWithAnnotationAllHints.class);
391+
assertThat(getDatabase().tableExists(tableYName)).isTrue();
392+
393+
// -- options --
394+
395+
// One can add options to setup the creation with finer grained:
396+
CreateTableOptions createTableOptions = new CreateTableOptions()
397+
.ifNotExists(true)
398+
.timeout(ofSeconds(5));
399+
// Table<Row> table3 = db.createTable("game3", tableDefinition, createTableOptions);
400+
401+
// One can can tuned the table object returned by the function
402+
TableOptions tableOptions = new TableOptions()
403+
.embeddingAuthProvider(new EmbeddingAPIKeyHeaderProvider("api-key"))
404+
.timeout(ofSeconds(5));
405+
406+
// Change the Type of objects in use instead of default Row
407+
Table<Row> table4 = getDatabase().createTable("game4", tableDefinition,Row.class, createTableOptions, tableOptions);
408+
}
409+
410+
411+
@Test
412+
@Order(15)
413+
public void shouldListTables() {
414+
ListTablesOptions options = new ListTablesOptions().timeout(Duration.ofMillis(1000));
415+
List<String> tableNames = getDatabase().listTableNames();
416+
assertThat(tableNames).isNotEmpty();
417+
assertThat(tableNames).contains("game1");
418+
419+
assertThat(getDatabase().listTableNames(options)).isNotEmpty();
420+
List<TableDescriptor> tables = getDatabase().listTables();
421+
assertThat().isNotEmpty();
422+
assertThat(getDatabase().listTables(options)).isNotEmpty();
423+
424+
}
425+
426+
340427
}

astra-db-java/src/test/java/com/datastax/astra/test/integration/local/LocalDatabaseITTest.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.datastax.astra.client.DataAPIClient;
44
import com.datastax.astra.client.DataAPIClients;
55
import com.datastax.astra.client.DataAPIDestination;
6+
import com.datastax.astra.client.admin.AdminOptions;
67
import com.datastax.astra.client.core.http.HttpClientOptions;
78
import com.datastax.astra.client.core.options.DataAPIClientOptions;
89
import com.datastax.astra.client.databases.Database;
@@ -72,7 +73,7 @@ void shouldInitializeHttpClientWithProxy() throws IOException {
7273
.addHeader("Content-Type", "application/json; charset=utf-8")
7374
.setBody("{\n" +
7475
" \"status\": {\n" +
75-
" \"namespaces\": [\n" +
76+
" \"keyspaces\": [\n" +
7677
" \"mock1\",\n" +
7778
" \"mock2\"\n" +
7879
" ]\n" +
@@ -83,17 +84,16 @@ void shouldInitializeHttpClientWithProxy() throws IOException {
8384
// Start the server
8485
mockWebServer.start();
8586

86-
DataAPIClient otherCallerClient = new DataAPIClient(
87-
new UsernamePasswordTokenProvider().getToken(),
88-
new DataAPIClientOptions()
89-
.destination(DataAPIDestination.CASSANDRA)
90-
.httpClientOptions(new HttpClientOptions()
91-
.httpProxy(new HttpProxy(mockWebServer.getHostName(), mockWebServer.getPort()))
92-
)
93-
);
87+
DataAPIClient otherCallerClient = DataAPIClients.clientCassandra();
9488
Set<String> names = otherCallerClient
9589
.getDatabase(DEFAULT_ENDPOINT_LOCAL)
96-
.getDatabaseAdmin()
90+
// Moving to admin I add a HTTP PROXY
91+
.getDatabaseAdmin(new AdminOptions()
92+
.dataAPIClientOptions(new DataAPIClientOptions()
93+
.httpClientOptions(new HttpClientOptions()
94+
.httpProxy(new HttpProxy(mockWebServer.getHostName(), mockWebServer.getPort()))
95+
)
96+
.logRequests()))
9797
.listKeyspaceNames();
9898
assertThat(names).isNotNull();
9999

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.datastax.astra.test.model;
2+
3+
import com.datastax.astra.client.core.vector.DataAPIVector;
4+
import com.datastax.astra.client.tables.mapping.Column;
5+
import lombok.Data;
6+
import lombok.NoArgsConstructor;
7+
8+
import java.time.Instant;
9+
import java.util.Set;
10+
11+
@Data
12+
@NoArgsConstructor
13+
public class TableEntityGame {
14+
15+
@Column(name ="match_id")
16+
private String matchId;
17+
18+
private Integer round;
19+
20+
private Integer score;
21+
22+
private Instant when;
23+
24+
private String winner;
25+
26+
private Set<java.util.UUID> fighters;
27+
28+
@Column(name ="m_vector")
29+
private DataAPIVector vector;
30+
31+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.datastax.astra.test.model;
2+
3+
import com.datastax.astra.client.core.query.SortOrder;
4+
import com.datastax.astra.client.core.vector.DataAPIVector;
5+
import com.datastax.astra.client.core.vector.SimilarityMetric;
6+
import com.datastax.astra.client.tables.mapping.Column;
7+
import com.datastax.astra.client.tables.mapping.EntityTable;
8+
import com.datastax.astra.client.tables.mapping.PartitionBy;
9+
import com.datastax.astra.client.tables.mapping.PartitionSort;
10+
import lombok.AllArgsConstructor;
11+
import lombok.Data;
12+
import lombok.NoArgsConstructor;
13+
14+
import java.time.Instant;
15+
import java.util.Set;
16+
import java.util.UUID;
17+
18+
@Data
19+
@EntityTable("game_ann2")
20+
@NoArgsConstructor
21+
@AllArgsConstructor
22+
public class TableEntityGameWithAnnotation {
23+
24+
@PartitionBy(0)
25+
@Column(name ="match_id")
26+
private String matchId;
27+
28+
@PartitionSort(position = 0, order = SortOrder.ASCENDING)
29+
private Integer round;
30+
31+
private Integer score;
32+
33+
private Instant when;
34+
35+
private String winner;
36+
37+
private Set<UUID> fighters;
38+
39+
@Column(name ="m_vector", dimension = 3, metric = SimilarityMetric.COSINE)
40+
private DataAPIVector vector;
41+
42+
}

0 commit comments

Comments
 (0)