diff --git a/docs/api-guide.mdx b/docs/api-guide.mdx index 09b28598..7be336f1 100644 --- a/docs/api-guide.mdx +++ b/docs/api-guide.mdx @@ -370,14 +370,14 @@ DistributedTransaction transaction = transactionManager.start(); Alternatively, you can use the `begin` method for a transaction by specifying a transaction ID as follows: ```java -// Begin a transaction with specifying a transaction ID. +// Begin a transaction by specifying a transaction ID. DistributedTransaction transaction = transactionManager.begin(""); ``` Or, you can use the `start` method for a transaction by specifying a transaction ID as follows: ```java -// Start a transaction with specifying a transaction ID. +// Start a transaction by specifying a transaction ID. DistributedTransaction transaction = transactionManager.start(""); ``` @@ -389,6 +389,48 @@ When you specify a transaction ID, make sure you specify a unique ID (for exampl ::: +##### Begin or start a transaction in read-only mode + +You can also begin or start a transaction in read-only mode. In this case, the transaction will not allow any write operations, and it will be optimized for read operations. + +:::note + +Using read-only transactions for read-only operations is strongly recommended to improve performance and reduce resource usage. + +::: + +You can begin or start a transaction in read-only mode as follows: + +```java +// Begin a transaction in read-only mode. +DistributedTransaction transaction = transactionManager.beginReadOnly(); +``` + +```java +// Start a transaction in read-only mode. +DistributedTransaction transaction = transactionManager.startReadOnly(); +``` + +Alternatively, you can use the `beginReadOnly` and `startReadOnly` methods by specifying a transaction ID as follows: + +```java +// Begin a transaction in read-only mode by specifying a transaction ID. +DistributedTransaction transaction = transactionManager.beginReadOnly(""); +``` + +```java +// Start a transaction in read-only mode by specifying a transaction ID. +DistributedTransaction transaction = transactionManager.startReadOnly(""); +``` + +:::note + +Specifying a transaction ID is useful when you want to link external systems to ScalarDB. Otherwise, you should use the `beginReadOnly()` method or the `startReadOnly()` method. + +When you specify a transaction ID, make sure you specify a unique ID (for example, UUID v4) throughout the system since ScalarDB depends on the uniqueness of transaction IDs for correctness. + +::: + #### Join a transaction Joining a transaction is particularly useful in a stateful application where a transaction spans multiple client requests. In such a scenario, the application can start a transaction during the first client request. Then, in subsequent client requests, the application can join the ongoing transaction by using the `join()` method. @@ -629,9 +671,14 @@ If the result has more than one record, `transaction.get()` will throw an except ##### `Scan` operation -`Scan` is an operation to retrieve multiple records within a partition. You can specify clustering-key boundaries and orderings for clustering-key columns in `Scan` operations. +`Scan` is an operation to retrieve multiple records within a partition. You can specify clustering-key boundaries and orderings for clustering-key columns in `Scan` operations. To execute a `Scan` operation, you can use the `transaction.scan()` method or the `transaction.getScanner()` method: + +- `transaction.scan()`: + - This method immediately executes the given `Scan` operation and returns a list of all matching records. It is suitable when the result set is expected to be small enough to fit in memory. +- `transaction.getScanner()`: + - This method returns a `Scanner` object that allows you to iterate over the result set lazily. It is useful when the result set may be large, as it avoids loading all records into memory at once. -You need to create a `Scan` object first, and then you can execute the object by using the `transaction.scan()` method as follows: +You need to create a `Scan` object first, and then you can execute the object by using the `transaction.scan()` method or the `transaction.getScanner()` method as follows: ```java // Create a `Scan` operation. @@ -652,8 +699,17 @@ Scan scan = .limit(10) .build(); -// Execute the `Scan` operation. +// Execute the `Scan` operation by using the `transaction.scan()` method. List results = transaction.scan(scan); + +// Or, execute the `Scan` operation by using the `transaction.getScanner()` method. +try (TransactionCrudOperable.Scanner scanner = transaction.getScanner(scan)) { + // Fetch the next result from the scanner + Optional result = scanner.one(); + + // Fetch all remaining results from the scanner + List allResults = scanner.all(); +} ``` You can omit the clustering-key boundaries or specify either a `start` boundary or an `end` boundary. If you don't specify `orderings`, you will get results ordered by the clustering order that you defined when creating the table. @@ -1292,9 +1348,14 @@ For details about the `Get` operation, see [`Get` operation](#get-operation). #### Execute `Scan` operation -`Scan` is an operation to retrieve multiple records within a partition. You can specify clustering-key boundaries and orderings for clustering-key columns in `Scan` operations. +`Scan` is an operation to retrieve multiple records within a partition. You can specify clustering-key boundaries and orderings for clustering-key columns in `Scan` operations. To execute a `Scan` operation, you can use the `transactionManager.scan()` method or the `transactionManager.getScanner()` method: + +- `transactionManager.scan()`: + - This method immediately executes the given `Scan` operation and returns a list of all matching records. It is suitable when the result set is expected to be small enough to fit in memory. +- `transactionManager.getScanner()`: + - This method returns a `Scanner` object that allows you to iterate over the result set lazily. It is useful when the result set may be large, as it avoids loading all records into memory at once. -You need to create a `Scan` object first, and then you can execute the object by using the `transactionManager.scan()` method as follows: +You need to create a `Scan` object first, and then you can execute the object by using the `transactionManager.scan()` method or the `transactionManager.getScanner()` method as follows: ```java // Create a `Scan` operation. @@ -1314,8 +1375,17 @@ Scan scan = .limit(10) .build(); -// Execute the `Scan` operation. +// Execute the `Scan` operation by using the `transactionManager.scan()` method. List results = transactionManager.scan(scan); + +// Or, execute the `Scan` operation by using the `transactionManager.getScanner()` method. +try (TransactionManagerCrudOperable.Scanner scanner = transactionManager.getScanner(scan)) { + // Fetch the next result from the scanner + Optional result = scanner.one(); + + // Fetch all remaining results from the scanner + List allResults = scanner.all(); +} ``` For details about the `Scan` operation, see [`Scan` operation](#scan-operation). diff --git a/docs/backup-restore.mdx b/docs/backup-restore.mdx index 55db1dbf..0efff032 100644 --- a/docs/backup-restore.mdx +++ b/docs/backup-restore.mdx @@ -66,6 +66,9 @@ The backup methods by database listed below are just examples of some of the dat Clusters are backed up automatically based on the backup policy, and these backups are retained for a specific duration. You can also perform on-demand backups. For details on performing backups, see [YugabyteDB Managed: Back up and restore clusters](https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-clusters/backup-clusters/). + + Use the `backup` command. For details, on performing backups, see [Db2: Backup overview](https://www.ibm.com/docs/en/db2/12.1.0?topic=recovery-backup). + ### Back up with explicit pausing @@ -175,4 +178,7 @@ The restore methods by database listed below are just examples of some of the da You can restore from the scheduled or on-demand backup within the backup retention period. For details on performing backups, see [YugabyteDB Managed: Back up and restore clusters](https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-clusters/backup-clusters/). + + Use the `restore` command. For details, on restoring the database, see [Db2: Restore overview](https://www.ibm.com/docs/en/db2/12.1.0?topic=recovery-restore). + diff --git a/docs/configurations.mdx b/docs/configurations.mdx index 5a05fd51..3e36d53f 100644 --- a/docs/configurations.mdx +++ b/docs/configurations.mdx @@ -23,13 +23,12 @@ If you are using ScalarDB Cluster, please refer to [ScalarDB Cluster Configurati The following configurations are available for the Consensus Commit transaction manager: -| Name | Description | Default | -|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------| -| `scalar.db.transaction_manager` | Transaction manager of ScalarDB. Specify `consensus-commit` to use [Consensus Commit](./consensus-commit.mdx) or `single-crud-operation` to [run non-transactional storage operations](./run-non-transactional-storage-operations-through-library.mdx). Note that the configurations under the `scalar.db.consensus_commit` prefix are ignored if you use `single-crud-operation`. | `consensus-commit` | -| `scalar.db.consensus_commit.isolation_level` | Isolation level used for Consensus Commit. Either `SNAPSHOT` or `SERIALIZABLE` can be specified. | `SNAPSHOT` | -| `scalar.db.consensus_commit.serializable_strategy` | Serializable strategy used for Consensus Commit. Either `EXTRA_READ` or `EXTRA_WRITE` can be specified. If `SNAPSHOT` is specified in the property `scalar.db.consensus_commit.isolation_level`, this configuration will be ignored. | `EXTRA_READ` | -| `scalar.db.consensus_commit.coordinator.namespace` | Namespace name of Coordinator tables. | `coordinator` | -| `scalar.db.consensus_commit.include_metadata.enabled` | If set to `true`, `Get` and `Scan` operations results will contain transaction metadata. To see the transaction metadata columns details for a given table, you can use the `DistributedTransactionAdmin.getTableMetadata()` method, which will return the table metadata augmented with the transaction metadata columns. Using this configuration can be useful to investigate transaction-related issues. | `false` | +| Name | Description | Default | +|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------| +| `scalar.db.transaction_manager` | Transaction manager of ScalarDB. Specify `consensus-commit` to use [Consensus Commit](./consensus-commit.mdx) or `single-crud-operation` to [run non-transactional storage operations](./run-non-transactional-storage-operations-through-library.mdx). Note that the configurations under the `scalar.db.consensus_commit` prefix are ignored if you use `single-crud-operation`. | `consensus-commit` | +| `scalar.db.consensus_commit.isolation_level` | Isolation level used for Consensus Commit. Either `SNAPSHOT`, `SERIALIZABLE`, or `READ_COMMITTED` can be specified. | `SNAPSHOT` | +| `scalar.db.consensus_commit.coordinator.namespace` | Namespace name of Coordinator tables. | `coordinator` | +| `scalar.db.consensus_commit.include_metadata.enabled` | If set to `true`, `Get` and `Scan` operations results will contain transaction metadata. To see the transaction metadata columns details for a given table, you can use the `DistributedTransactionAdmin.getTableMetadata()` method, which will return the table metadata augmented with the transaction metadata columns. Using this configuration can be useful to investigate transaction-related issues. | `false` | ## Performance-related configurations @@ -45,6 +44,8 @@ The following performance-related configurations are available for the Consensus | `scalar.db.consensus_commit.async_commit.enabled` | Whether or not the commit phase is executed asynchronously. | `false` | | `scalar.db.consensus_commit.async_rollback.enabled` | Whether or not the rollback phase is executed asynchronously. | The value of `scalar.db.consensus_commit.async_commit.enabled` | | `scalar.db.consensus_commit.parallel_implicit_pre_read.enabled` | Whether or not implicit pre-read is executed in parallel. | `true` | +| `scalar.db.consensus_commit.one_phase_commit.enabled` | Whether or not the one-phase commit optimization is enabled. | `false` | +| `scalar.db.consensus_commit.coordinator.write_omission_on_read_only.enabled` | Whether or not the write omission optimization is enabled for read-only transactions. This optimization is useful for read-only transactions that do not modify any data, as it avoids unnecessary writes to the Coordinator tables. | `true` | | `scalar.db.consensus_commit.coordinator.group_commit.enabled` | Whether or not committing the transaction state is executed in batch mode. This feature can't be used with a two-phase commit interface. | `false` | | `scalar.db.consensus_commit.coordinator.group_commit.slot_capacity` | Maximum number of slots in a group for the group commit feature. A large value improves the efficiency of group commit, but may also increase latency and the likelihood of transaction conflicts.[^1] | `20` | | `scalar.db.consensus_commit.coordinator.group_commit.group_size_fix_timeout_millis` | Timeout to fix the size of slots in a group. A large value improves the efficiency of group commit, but may also increase latency and the likelihood of transaction conflicts.[^1] | `40` | @@ -63,28 +64,30 @@ Select a database to see the configurations available for each storage. The following configurations are available for JDBC databases: - | Name | Description | Default | - |------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| - | `scalar.db.storage` | `jdbc` must be specified. | - | - | `scalar.db.contact_points` | JDBC connection URL. | | - | `scalar.db.username` | Username to access the database. | | - | `scalar.db.password` | Password to access the database. | | - | `scalar.db.jdbc.connection_pool.min_idle` | Minimum number of idle connections in the connection pool. | `20` | - | `scalar.db.jdbc.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool. | `50` | - | `scalar.db.jdbc.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool. Use a negative value for no limit. | `100` | - | `scalar.db.jdbc.prepared_statements_pool.enabled` | Setting this property to `true` enables prepared-statement pooling. | `false` | - | `scalar.db.jdbc.prepared_statements_pool.max_open` | Maximum number of open statements that can be allocated from the statement pool at the same time. Use a negative value for no limit. | `-1` | - | `scalar.db.jdbc.isolation_level` | Isolation level for JDBC. `READ_UNCOMMITTED`, `READ_COMMITTED`, `REPEATABLE_READ`, or `SERIALIZABLE` can be specified. | Underlying-database specific | - | `scalar.db.jdbc.table_metadata.schema` | Schema name for the table metadata used for ScalarDB. | `scalardb` | - | `scalar.db.jdbc.table_metadata.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for the table metadata. | `5` | - | `scalar.db.jdbc.table_metadata.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for the table metadata. | `10` | - | `scalar.db.jdbc.table_metadata.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for the table metadata. Use a negative value for no limit. | `25` | - | `scalar.db.jdbc.admin.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for admin. | `5` | - | `scalar.db.jdbc.admin.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for admin. | `10` | - | `scalar.db.jdbc.admin.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for admin. Use a negative value for no limit. | `25` | - | `scalar.db.jdbc.mysql.variable_key_column_size` | Column size for TEXT and BLOB columns in MySQL when they are used as a primary key or secondary key. Minimum 64 bytes. | `128` | - | `scalar.db.jdbc.oracle.variable_key_column_size` | Column size for TEXT and BLOB columns in Oracle when they are used as a primary key or secondary key. Minimum 64 bytes. | `128` | - | `scalar.db.jdbc.oracle.time_column.default_date_component` | Value of the date component used for storing `TIME` data in Oracle. Since Oracle has no data type to only store a time without a date component, ScalarDB stores `TIME` data with the same date component value for ease of comparison and sorting. | `1970-01-01` | + | Name | Description | Default | + |------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| + | `scalar.db.storage` | `jdbc` must be specified. | - | + | `scalar.db.contact_points` | JDBC connection URL. | | + | `scalar.db.username` | Username to access the database. | | + | `scalar.db.password` | Password to access the database. | | + | `scalar.db.jdbc.connection_pool.min_idle` | Minimum number of idle connections in the connection pool. | `20` | + | `scalar.db.jdbc.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool. | `50` | + | `scalar.db.jdbc.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool. Use a negative value for no limit. | `100` | + | `scalar.db.jdbc.prepared_statements_pool.enabled` | Setting this property to `true` enables prepared-statement pooling. | `false` | + | `scalar.db.jdbc.prepared_statements_pool.max_open` | Maximum number of open statements that can be allocated from the statement pool at the same time. Use a negative value for no limit. | `-1` | + | `scalar.db.jdbc.isolation_level` | Isolation level for JDBC. `READ_UNCOMMITTED`, `READ_COMMITTED`, `REPEATABLE_READ`, or `SERIALIZABLE` can be specified. | Underlying-database specific | + | `scalar.db.jdbc.table_metadata.schema` | Schema name for the table metadata used for ScalarDB. | `scalardb` | + | `scalar.db.jdbc.table_metadata.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for the table metadata. | `5` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for the table metadata. | `10` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for the table metadata. Use a negative value for no limit. | `25` | + | `scalar.db.jdbc.admin.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for admin. | `5` | + | `scalar.db.jdbc.admin.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for admin. | `10` | + | `scalar.db.jdbc.admin.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for admin. Use a negative value for no limit. | `25` | + | `scalar.db.jdbc.mysql.variable_key_column_size` | Column size for TEXT and BLOB columns in MySQL when they are used as a primary key or secondary key. Minimum 64 bytes. | `128` | + | `scalar.db.jdbc.oracle.variable_key_column_size` | Column size for TEXT and BLOB columns in Oracle when they are used as a primary key or secondary key. Minimum 64 bytes. | `128` | + | `scalar.db.jdbc.oracle.time_column.default_date_component` | Value of the date component used for storing `TIME` data in Oracle. Since Oracle has no data type to only store a time without a date component, ScalarDB stores `TIME` data with the same date component value for ease of comparison and sorting. | `1970-01-01` | + | `scalar.db.jdbc.db2.variable_key_column_size` | Column size for TEXT and BLOB columns in IBM Db2 when they are used as a primary key or secondary key. Minimum 64 bytes. | `128` | + | `scalar.db.jdbc.db2.time_column.default_date_component` | Value of the date component used for storing `TIME` data in IBM Db2. Since the IBM Db2 TIMESTAMP type is used to store ScalarDB `TIME` type data because it provides fractional-second precision, ScalarDB stores `TIME` data with the same date component value for ease of comparison and sorting. | `1970-01-01` | :::note @@ -174,15 +177,23 @@ For non-JDBC databases, transactions could be executed at read-committed snapsho | `scalar.db.cross_partition_scan.filtering.enabled` | Enable filtering in cross-partition scan. | `false` | | `scalar.db.cross_partition_scan.ordering.enabled` | Enable ordering in cross-partition scan. | `false` | +##### Scan fetch size + +You can configure the fetch size for storage scan operations by using the following property: + +| Name | Description | Default | +|-----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `scalar.db.scan_fetch_size` | Specifies the number of records to fetch in a single batch during a storage scan operation. A larger value can improve performance for a large result set by reducing round trips to the storage, but it also increases memory usage. A smaller value uses less memory but may increase latency. | `10` | + ## Other ScalarDB configurations The following are additional configurations available for ScalarDB: -| Name | Description | Default | -|------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| -| `scalar.db.metadata.cache_expiration_time_secs` | ScalarDB has a metadata cache to reduce the number of requests to the database. This setting specifies the expiration time of the cache in seconds. If you specify `-1`, the cache will never expire. | `60` | -| `scalar.db.active_transaction_management.expiration_time_millis` | ScalarDB maintains ongoing transactions, which can be resumed by using a transaction ID. This setting specifies the expiration time of this transaction management feature in milliseconds. | `-1` (no expiration) | -| `scalar.db.default_namespace_name` | The given namespace name will be used by operations that do not already specify a namespace. | | +| Name | Description | Default | +|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| +| `scalar.db.metadata.cache_expiration_time_secs` | ScalarDB has a metadata cache to reduce the number of requests to the database. This setting specifies the expiration time of the cache in seconds. If you specify `-1`, the cache will never expire. | `60` | +| `scalar.db.active_transaction_management.expiration_time_millis` | ScalarDB maintains in-progress transactions, which can be resumed by using a transaction ID. This process expires transactions that have been idle for an extended period to prevent resource leaks. This setting specifies the expiration time of this transaction management feature in milliseconds. | `-1` (no expiration) | +| `scalar.db.default_namespace_name` | The given namespace name will be used by operations that do not already specify a namespace. | | ## Placeholder usage diff --git a/docs/consensus-commit.mdx b/docs/consensus-commit.mdx index d61d31fb..16df6dc7 100644 --- a/docs/consensus-commit.mdx +++ b/docs/consensus-commit.mdx @@ -81,11 +81,14 @@ ScalarDB checks conflicting preparations by using linearizable conditional write ScalarDB then moves on to the validate-records phase as necessary. The validate-records phase is only necessary if the isolation level is set to SERIALIZABLE. In this phase, ScalarDB re-reads all the records in the read set to see if other transactions have written the records that the transaction has read before. If the read set has not been changed, the transaction can go to the commit-state phase since there are no anti-dependencies; otherwise, it aborts the transaction. ##### Commit phase + If all the validations in the prepare phase are done successfully, ScalarDB commits the transaction by writing a COMMITTED state record to the Coordinator table as the commit-state phase. :::note -ScalarDB uses linearizable conditional writes to coordinate concurrent writes to the Coordinator table, creating a state record with a TxID if there is no record for the TxID. Once the COMMITTED state is correctly written to the Coordinator table, the transaction is regarded as committed. +* ScalarDB uses linearizable conditional writes to coordinate concurrent writes to the Coordinator table, creating a state record with a TxID if there is no record for the TxID. Once the COMMITTED state is correctly written to the Coordinator table, the transaction is regarded as committed. +* By default, if a transaction contains only read operations, ScalarDB skips the commit-state phase. However, you can configure ScalarDB to write a COMMITTED state record to the Coordinator table even for read-only transactions by setting the following parameter to `false`: + * `scalar.db.consensus_commit.coordinator.write_omission_on_read_only.enabled` ::: @@ -113,7 +116,7 @@ A transaction expires after a certain amount of time (currently 15 seconds). Whe ## Isolation levels -The Consensus Commit protocol supports two isolation levels: a weaker variant of snapshot isolation, read-committed snapshot isolation, and serializable, each of which has the following characteristics: +The Consensus Commit protocol supports three isolation levels: read-committed snapshot isolation (a weaker variant of snapshot isolation), serializable, and read-committed, each of which has the following characteristics: * Read-committed snapshot isolation (SNAPSHOT - default) * Possible anomalies: read skew, write skew, read only @@ -121,8 +124,11 @@ The Consensus Commit protocol supports two isolation levels: a weaker variant of * Serializable (SERIALIZABLE) * Possible anomalies: None * Slower than read-committed snapshot isolation, but guarantees stronger (strongest) correctness. +* Read-committed (READ_COMMITTED) + * Possible anomalies: read skew, write skew, read only + * Faster than read-committed snapshot isolation because it could return non-latest committed records. -As described above, serializable is preferable from a correctness perspective, but slower than read-committed snapshot isolation. Choose the appropriate one based on your application requirements and workload. For details on how to configure read-committed snapshot isolation and serializable, see [ScalarDB Configuration](configurations.mdx#basic-configurations). +As described above, serializable is preferable from a correctness perspective, but slower than read-committed snapshot isolation. Choose the appropriate one based on your application requirements and workload. For details on how to configure read-committed snapshot isolation, serializable, and read-committed, see [ScalarDB Configuration](configurations.mdx#basic-configurations). :::note @@ -186,6 +192,14 @@ You can enable respective asynchronous execution by using the following paramete * Rollback processing * `scalar.db.consensus_commit.async_rollback.enabled` +### One-phase commit + +With one-phase commit optimization, ScalarDB can omit the prepare-records and commit-state phases without sacrificing correctness, provided that the transaction only updates records that the underlying database can atomically update. + +You can enable one-phase commit optimization by using the following parameter: + +* `scalar.db.consensus_commit.one_phase_commit.enabled` + ### Group commit Consensus Commit provides a group-commit feature to execute the commit-state phase of multiple transactions in a batch, reducing the number of writes for the commit-state phase. It is especially useful when writing to a Coordinator table is slow, for example, when the Coordinator table is deployed in a multi-region environment for high availability. diff --git a/docs/getting-started-with-scalardb.mdx b/docs/getting-started-with-scalardb.mdx index 2e21cefc..0c7bcd8f 100644 --- a/docs/getting-started-with-scalardb.mdx +++ b/docs/getting-started-with-scalardb.mdx @@ -143,6 +143,29 @@ For a list of databases that ScalarDB supports, see [Databases](requirements.mdx scalar.db.password=SqlServer22 ``` + +

Run Db2 locally

+ + You can run IBM Db2 in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start IBM Db2, run the following command: + + ```console + docker compose up -d db2 + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Db2 in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Db2 + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:db2://localhost:50000/sample + scalar.db.username=db2inst1 + scalar.db.password=db2inst1 + ``` +

Run Amazon DynamoDB Local

diff --git a/docs/index.mdx b/docs/index.mdx index 8924cb93..7e7c22df 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -9,6 +9,6 @@ hide_table_of_contents: true title: "" --- -import CategoryGrid from '/src/components/Cards/3.15'; +import CategoryGrid from '/src/components/Cards/3.16'; diff --git a/docs/overview.mdx b/docs/overview.mdx index e7a2532e..b51df6be 100644 --- a/docs/overview.mdx +++ b/docs/overview.mdx @@ -18,7 +18,7 @@ ScalarDB is a universal hybrid transaction/analytical processing (HTAP) engine f As a versatile solution, ScalarDB supports a range of databases, including: -- Relational databases that support JDBC, such as MariaDB, Microsoft SQL Server, MySQL, Oracle Database, PostgreSQL, SQLite, and their compatible databases, like Amazon Aurora and YugabyteDB. +- Relational databases that support JDBC, such as IBM Db2, MariaDB, Microsoft SQL Server, MySQL, Oracle Database, PostgreSQL, SQLite, and their compatible databases, like Amazon Aurora and YugabyteDB. - NoSQL databases like Amazon DynamoDB, Apache Cassandra, and Azure Cosmos DB. For details on which databases ScalarDB supports, refer to [Databases](requirements.mdx#databases). diff --git a/docs/releases/release-notes.mdx b/docs/releases/release-notes.mdx index b3a4ebaf..06412c5a 100644 --- a/docs/releases/release-notes.mdx +++ b/docs/releases/release-notes.mdx @@ -6,88 +6,78 @@ tags: displayed_sidebar: docsEnglish --- -# ScalarDB 3.15 Release Notes +# ScalarDB 3.16 Release Notes -This page includes a list of release notes for ScalarDB 3.15. +This page includes a list of release notes for ScalarDB 3.16. -## v3.15.4 +## v3.16.0 -**Release date:** June 21, 2025 +**Release date:** June 20, 2025 ### Summary -This release includes fixes for vulnerabilities and bugs. +This release includes many enhancements, improvements, bug fixes, and performance optimizations. ### Community edition -#### Bug fixes - -- Add exception handling for DateTimeParseException on column value conversion. ([#2662](https://github.com/scalar-labs/scalardb/pull/2662)) -- Upgraded the PostgreSQL driver to fix security issues. [CVE-2025-49146](https://github.com/advisories/GHSA-hq9p-pm7w-8p54 "CVE-2025-49146") ([#2772](https://github.com/scalar-labs/scalardb/pull/2772)) -- Fixed potential connection leak when using `jdbc` storage and Scan operation fails because the target table doesn't exist. ([#2766](https://github.com/scalar-labs/scalardb/pull/2766)) - -### Enterprise edition - -#### Bug fixes - -##### ScalarDB Cluster - -- Fixed a memory leak issue when the coordinator group commit feature is enabled. -- Upgraded the OpenSearch Java client to fix a security issue. [CVE-2025-27820](https://github.com/advisories/GHSA-73m2-qfq3-56cx "CVE-2025-27820") - -## v3.15.3 +#### Enhancements -**Release date:** May 15, 2025 +- Added support for IBM Db2 LUV 11 and 12. ([#2598](https://github.com/scalar-labs/scalardb/pull/2598)) +- Added a scanner API to the transaction abstraction for iteratively retrieving results. ([#2729](https://github.com/scalar-labs/scalardb/pull/2729)) +- Added support for scan fetch size in the storage adapters. You can control the number of records fetched by the scan API in the storage layer by configuring the `scalar.db.scan_fetch_size` property. ([#2731](https://github.com/scalar-labs/scalardb/pull/2731)) +- Added `replication-tables` option to the Schema Loader. ([#2747](https://github.com/scalar-labs/scalardb/pull/2747)) +- Added support for beginning transactions in read-only mode. ([#2749](https://github.com/scalar-labs/scalardb/pull/2749)) +- Fixed warnings for Javadoc and errorprone. ([#2614](https://github.com/scalar-labs/scalardb/pull/2614)) +- Introduced `StorageInfo`, which provides metadata about the storage. You can obtain a `StorageInfo` instance via the `DistributedStorageAdmin.getStorageInfo()` method. ([#2756](https://github.com/scalar-labs/scalardb/pull/2756)) +- Added Docker support for the ScalarDB Data Loader CLI, enabling containerized deployment of the data loading functionality. ([#2758](https://github.com/scalar-labs/scalardb/pull/2758)) +- Added a CI workflow for the Data Loader CLI build. ([#2761](https://github.com/scalar-labs/scalardb/pull/2761)) +- Added the `READ_COMMITTED` isolation level, which offers better performance, especially for low-contention workloads. ([#2803](https://github.com/scalar-labs/scalardb/pull/2803)) +- Added support for one-phase commit optimization in Consensus Commit, significantly improving performance by skipping prepare-records and commit-state when all mutations can be committed atomically. Enable this optimization with the `scalar.db.consensus_commit.one_phase_commit.enabled` property. ([#2811](https://github.com/scalar-labs/scalardb/pull/2811)) -### Summary - -This release includes fixes for vulnerabilities and bugs, and adds support for running ScalarDB Cluster on the Omnistrate service. +#### Improvements -### Community edition +- Made changes so that the ScalarDB BIGINT data type will now be mapped to Oracle's `NUMBER(16)`. ([#2566](https://github.com/scalar-labs/scalardb/pull/2566)) +- Removed the `EXTRA_WRITE` strategy from Consensus Commit. After this change, if the `EXTRA_WRITE` strategy is specified when using Consensus Commit, the `EXTRA_READ` strategy will be used instead. ([#2597](https://github.com/scalar-labs/scalardb/pull/2597)) +- Changed to disallow scan operations after a delete on the same record in Consensus Commit to prevent inconsistent behavior and align with the existing restriction on scans after writes. ([#2610](https://github.com/scalar-labs/scalardb/pull/2610)) +- Changed to omit commit-state for read-only transactions in Consensus Commit to improve performance. This behavior is enabled by default but can be disabled by setting the property `scalar.db.consensus_commit.coordinator.write_omission_on_read_only.enabled` to `false`. ([#2765](https://github.com/scalar-labs/scalardb/pull/2765)) +- Updated the code to remove before images after committing or rolling back records in Consensus Commit to reduce disk usage. ([#2787](https://github.com/scalar-labs/scalardb/pull/2787)) +- Improved the read algorithm in Consensus Commit to reduce unnecessary retries. ([#2798](https://github.com/scalar-labs/scalardb/pull/2798)) #### Bug fixes +- Upgraded the Netty library to fix a security issue. [CVE-2025-24970](https://github.com/advisories/GHSA-4g8c-wm8x-jfhw "CVE-2025-24970") ([#2552](https://github.com/scalar-labs/scalardb/pull/2552)) +- Fixed a bug in Consensus Commit with `SERIALIZABLE` isolation level where a transaction consistently aborts if a record was inserted into the scan range after executing a scan with a limit. ([#2621](https://github.com/scalar-labs/scalardb/pull/2621)) - Fixed an issue with `DistributedStorageAdmin.getNamespaceNames()` API when using the DynamoDB storage with the namespace prefix setting `scalar.db.dynamo.namespace.prefix`. The namespace names returned by this method wrongly contained the prefix. ([#2641](https://github.com/scalar-labs/scalardb/pull/2641)) +- Added exception handling for `DateTimeParseException` on column value conversion ([#2662](https://github.com/scalar-labs/scalardb/pull/2662)) +- Fixed an issue where `Get` operations using secondary indexes could throw `IllegalArgumentException` in `SERIALIZABLE` transactions by converting them to `Scan` operations during validation. ([#2683](https://github.com/scalar-labs/scalardb/pull/2683)) +- Fixed a bug that caused unnecessary implicit pre-reads when updating records retrieved by a secondary-index `Get` operation within a transaction. ([#2700](https://github.com/scalar-labs/scalardb/pull/2700)) +- Fixed minor bugs and issues in Data Loader core. ([#2752](https://github.com/scalar-labs/scalardb/pull/2752)) +- Fixed a bug where records could be missed when executing `Get` or `Scan` with conjunctions in Consensus Commit. ([#2786](https://github.com/scalar-labs/scalardb/pull/2786)) +- Fixed an issue in Consensus Commit where reading the same record multiple times from storage could cause anomalies like lost updates. The read set is no longer updated on repeated reads to resolve this issue. ([#2797](https://github.com/scalar-labs/scalardb/pull/2797)) +- Fixed potential connection leak when using `jdbc` storage and `Scan` operation fails because the target table doesn't exist ([#2766](https://github.com/scalar-labs/scalardb/pull/2766)) ### Enterprise edition -#### Improvements - -##### ScalarDB Cluster - -- Added support for the Omnistrate service. Now, you can run ScalarDB Cluster in the Omnistrate service. - -#### Bug fixes +#### Enhancements ##### ScalarDB Cluster -- Upgraded `grpc_health_probe` to fix a security issue. [CVE-2025-22869](https://github.com/advisories/GHSA-hcg3-q754-cr77) - -## v3.15.2 - -**Release date:** March 24, 2025 - -### Summary +- Added a configuration option (`scalar.db.transaction.enabled`) to enable or disable the transaction feature in ScalarDB Cluster. The default value is `true`. +- Added support for the scanner API in the transaction abstraction to iteratively retrieve results in ScalarDB Cluster. +- Added support for beginning transactions in read-only mode in ScalarDB Cluster. +- Added support for beginning transactions in read-only mode using SQL in ScalarDB Cluster. +- Added the remote replication feature in ScalarDB Cluster. -This release has several improvements and bug fixes. +##### ScalarDB SQL -### Community edition +- Added support for beginning transactions in read-only mode in ScalarDB SQL. #### Improvements -- ScalarDB BIGINT datatype will now be mapped to Oracle's NUMBER(16). ([#2566](https://github.com/scalar-labs/scalardb/pull/2566)) - -#### Bug fixes - -- Upgraded the Netty library to fix a security issue. [CVE-2025-24970](https://github.com/advisories/GHSA-4g8c-wm8x-jfhw "CVE-2025-24970") ([#2552](https://github.com/scalar-labs/scalardb/pull/2552)) - -### Enterprise edition - -#### Enhancements - ##### ScalarDB Cluster -- Added a configuration option (`scalar.db.transaction.enabled`) to enable or disable the transaction feature in ScalarDB Cluster. The default value is `true`. +- Added support for the Omnistrate service. Now, you can run ScalarDB Cluster in the Omnistrate service. +- Made changes to prevent pausing of read-only transactions when a pause command is issued to ScalarDB Cluster. #### Bug fixes @@ -97,61 +87,4 @@ This release has several improvements and bug fixes. - Fixed configurations for the embedding feature. - Fixed a bug that allowed superusers to execute ABAC administrative operations for non-existing users. - Fixed a bug a table-not-found error occurs when dropping empty ABAC system tables. - -## v3.15.1 - -**Release date:** February 20, 2025 - -### Summary - -This release includes numerous enhancements, improvements, and bug fixes. The [3.15.0 release](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.0) has been discarded, making this the first official release for 3.15. - -### Community edition - -#### Enhancements - -- Introduced operation attributes, providing the capability to include additional key-value information in operations. ([#2333](https://github.com/scalar-labs/scalardb/pull/2333)) -- Add the new time-related data types DATE, TIME, TIMESTAMP, and TIMESTAMPTZ. ([#2468](https://github.com/scalar-labs/scalardb/pull/2468) [#2491](https://github.com/scalar-labs/scalardb/pull/2491)) - -#### Improvements - -- ScalarDB now supports MySQL 8.4, 8.0; PostgreSQL 17, 16, 15, 14, and 13; Amazon Aurora PostgreSQL 16, 15, 14, and 13; Amazon Aurora MySQL 3, and 2. ([#2302](https://github.com/scalar-labs/scalardb/pull/2302)) -- Use the MariaDB Connector/J JDBC driver for any connection URL starting with `jdbc:mariadb` ([#2391](https://github.com/scalar-labs/scalardb/pull/2391)) -- Removed unnecessary loggings in the statement handlers for Cassandra and Cosmos DB. ([#2469](https://github.com/scalar-labs/scalardb/pull/2469)) - -#### Bug fixes - -- Added validation for primary key columns in the Cosmos DB adapter. The validation ensures that the text values of the primary key columns do not contain illegal characters (`:`, `/`, `\`, `#`, and `?`). ([#2292](https://github.com/scalar-labs/scalardb/pull/2292)) -- Fixed the behavior of multiple mutations for the same record in a transaction in Consensus Commit. ([#2340](https://github.com/scalar-labs/scalardb/pull/2340)) -- Fixed the behavior when deleting a non-existing record in the Cosmos adapter. ([#2341](https://github.com/scalar-labs/scalardb/pull/2341)) -- Fixed bugs in GetBuilder and ScanBuilder. ([#2352](https://github.com/scalar-labs/scalardb/pull/2352)) - -### Enterprise edition - -#### Enhancements - -##### ScalarDB Cluster - -- Added support for operation attributes introduced in [#2333](https://github.com/scalar-labs/scalardb/pull/2333) to ScalarDB Cluster. -- Added the attribute-based access control feature. -- Added support for the time-related types introduced in [#2468](https://github.com/scalar-labs/scalardb/pull/2468) to ScalarDB Cluster. -- Added support for the metadata API for ABAC introduced in [scalar-labs/scalardb-sql#708](https://github.com/scalar-labs/scalardb-sql/pull/708). -- Added vector search capability to ScalarDB Cluster by integrating LangChain4j. - -##### ScalarDB SQL - -- Added support for operation attributes to DMLs. Also added support for read tags and write tags in ABAC to DMSs. -- Support the time-related types DATE, TIME, TIMESTAMP, and TIMESTAMPTZ. -- Added metadata API for ABAC. -- Added SQL statements for ABAC. - -#### Bug fixes - -##### ScalarDB Cluster - -- Upgraded `grpc_health_probe` to fix security issues. [CVE-2024-45337](https://github.com/advisories/GHSA-v778-237x-gjrc "CVE-2024-45337") [CVE-2024-45338](https://github.com/advisories/GHSA-w32m-9786-jp63 "CVE-2024-45338") - -##### ScalarDB SQL - -- [Spring Data JDBC For ScalarDB] Fixed a bug `existsById()` API not working -- Fix an issue causing the SQL statement parser to reject negative numeric literal for columns of type INT and BIGINT. +- Fixed a memory leak issue when the coordinator group commit feature is enabled. diff --git a/docs/releases/release-support-policy.mdx b/docs/releases/release-support-policy.mdx index e6874fab..79df3da4 100644 --- a/docs/releases/release-support-policy.mdx +++ b/docs/releases/release-support-policy.mdx @@ -29,14 +29,21 @@ This page describes Scalar's support policy for major and minor version releases - 3.15 - 2025-02-20 + 3.16 + 2025-06-23 TBD* TBD* Contact us - 3.14 + 3.15 + 2025-02-20 + 2026-06-23 + 2026-12-20 + Contact us + + + 3.14 2024-11-22 2026-02-20 2026-08-18 diff --git a/docs/requirements.mdx b/docs/requirements.mdx index 838b9715..a5fdb19b 100644 --- a/docs/requirements.mdx +++ b/docs/requirements.mdx @@ -51,6 +51,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | Oracle Database 23ai | Oracle Database 21c | Oracle Database 19c | |:------------------|:--------------------|:------------------|:------------------| +| **ScalarDB 3.16** | ✅ | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | ✅ | @@ -61,11 +62,34 @@ ScalarDB is middleware that runs on top of the following databases and their ver | **ScalarDB 3.8** | ✅ | ✅ | ✅ | | **ScalarDB 3.7** | ✅ | ✅ | ✅ | +
+ + +| Version | Db2 12.1 | Db2 11.5 | +|:------------------|:---------|:---------| +| **ScalarDB 3.16** | ✅ | ✅ | +| **ScalarDB 3.15** | ❌ | ❌ | +| **ScalarDB 3.14** | ❌ | ❌ | +| **ScalarDB 3.13** | ❌ | ❌ | +| **ScalarDB 3.12** | ❌ | ❌ | +| **ScalarDB 3.11** | ❌ | ❌ | +| **ScalarDB 3.10** | ❌ | ❌ | +| **ScalarDB 3.9** | ❌ | ❌ | +| **ScalarDB 3.8** | ❌ | ❌ | +| **ScalarDB 3.7** | ❌ | ❌ | + +:::note + +Only Linux, UNIX, and Windows versions of Db2 are supported. The z/OS version is not currently supported. + +::: + | Version | MySQL 8.4 | MySQL 8.0 | |:------------------|:----------|:-----------| +| **ScalarDB 3.16** | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | @@ -81,6 +105,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | PostgreSQL 17 | PostgreSQL 16 | PostgreSQL 15 | PostgreSQL 14 | PostgreSQL 13 | |:------------------|:--------------|:--------------|:--------------|:--------------|---------------| +| **ScalarDB 3.16** | ✅ | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | ✅ | ✅ | ✅ | @@ -96,6 +121,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | Aurora MySQL 3 | Aurora MySQL 2 | |:------------------|:----------------|:----------------| +| **ScalarDB 3.16** | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | @@ -111,6 +137,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | Aurora PostgreSQL 16 | Aurora PostgreSQL 15 | Aurora PostgreSQL 14 | Aurora PostgreSQL 13 | |:------------------|:---------------------|:---------------------|:---------------------|:---------------------| +| **ScalarDB 3.16** | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | ✅ | ✅ | @@ -126,6 +153,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | MariaDB 11.4 | MariaDB 10.11 | |:------------------|:--------------|:--------------| +| **ScalarDB 3.16** | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | @@ -141,6 +169,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | SQL Server 2022 | SQL Server 2019 | SQL Server 2017 | |:------------------|:-----------------|:-----------------|:-----------------| +| **ScalarDB 3.16** | ✅ | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | ✅ | @@ -156,6 +185,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | SQLite 3 | |:------------------|:----------| +| **ScalarDB 3.16** | ✅ | | **ScalarDB 3.15** | ✅ | | **ScalarDB 3.14** | ✅ | | **ScalarDB 3.13** | ✅ | @@ -171,6 +201,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | YugabyteDB 2 | |:------------------|:-------------| +| **ScalarDB 3.16** | ✅ | | **ScalarDB 3.15** | ✅ | | **ScalarDB 3.14** | ✅ | | **ScalarDB 3.13** | ✅ | @@ -191,6 +222,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | DynamoDB | |:------------------|:----------| +| **ScalarDB 3.16** | ✅ | | **ScalarDB 3.15** | ✅ | | **ScalarDB 3.14** | ✅ | | **ScalarDB 3.13** | ✅ | @@ -206,6 +238,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | Cassandra 4.1 | Cassandra 4.0 | Cassandra 3.11 | Cassandra 3.0 | |:------------------|:---------------|:---------------|:----------------|:---------------| +| **ScalarDB 3.16** | ❌ | ❌ | ✅ | ✅ | | **ScalarDB 3.15** | ❌ | ❌ | ✅ | ✅ | | **ScalarDB 3.14** | ❌ | ❌ | ✅ | ✅ | | **ScalarDB 3.13** | ❌ | ❌ | ✅ | ✅ | @@ -221,6 +254,7 @@ ScalarDB is middleware that runs on top of the following databases and their ver | Version | Cosmos DB for NoSQL | |:------------------|:---------------------| +| **ScalarDB 3.16** | ✅ | | **ScalarDB 3.15** | ✅ | | **ScalarDB 3.14** | ✅ | | **ScalarDB 3.13** | ✅ | diff --git a/docs/run-non-transactional-storage-operations-through-library.mdx b/docs/run-non-transactional-storage-operations-through-library.mdx index 4bee033f..ea97ee58 100644 --- a/docs/run-non-transactional-storage-operations-through-library.mdx +++ b/docs/run-non-transactional-storage-operations-through-library.mdx @@ -130,6 +130,29 @@ For a list of databases that ScalarDB supports, see [Databases](requirements.mdx scalar.db.password=SqlServer22 ``` + +

Run Db2 locally

+ + You can run IBM Db2 in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start IBM Db2, run the following command: + + ```console + docker compose up -d db2 + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Db2 in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Db2 + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:db2://localhost:50000/sample + scalar.db.username=db2inst1 + scalar.db.password=db2inst1 + ``` +

Run Amazon DynamoDB Local

@@ -237,7 +260,7 @@ Select your build tool, and follow the instructions to add the build dependency ```gradle dependencies { - implementation 'com.scalar-labs:scalardb:3.15.4' + implementation 'com.scalar-labs:scalardb:3.16.0' } ```
@@ -248,7 +271,7 @@ Select your build tool, and follow the instructions to add the build dependency com.scalar-labs scalardb - 3.15.4 + 3.16.0 ``` @@ -269,4 +292,4 @@ The following limitations apply to non-transactional storage operations: ### Learn more -- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.15.4/index.html) +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.16.0/index.html) diff --git a/docs/run-transactions-through-scalardb-core-library.mdx b/docs/run-transactions-through-scalardb-core-library.mdx index d6579d15..b448d61f 100644 --- a/docs/run-transactions-through-scalardb-core-library.mdx +++ b/docs/run-transactions-through-scalardb-core-library.mdx @@ -130,6 +130,29 @@ For a list of databases that ScalarDB supports, see [Databases](requirements.mdx scalar.db.password=SqlServer22 ``` + +

Run Db2 locally

+ + You can run IBM Db2 in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start IBM Db2, run the following command: + + ```console + docker compose up -d db2 + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Db2 in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Db2 + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:db2://localhost:50000/sample + scalar.db.username=db2inst1 + scalar.db.password=db2inst1 + ``` +

Run Amazon DynamoDB Local

diff --git a/docs/scalardb-analytics/run-analytical-queries.mdx b/docs/scalardb-analytics/run-analytical-queries.mdx index d13b86cc..4f4b26aa 100644 --- a/docs/scalardb-analytics/run-analytical-queries.mdx +++ b/docs/scalardb-analytics/run-analytical-queries.mdx @@ -449,6 +449,5 @@ The following is a list of Spark and Scalar versions supported by each version o | ScalarDB Analytics Version | ScalarDB Version | Spark Versions Supported | Scala Versions Supported | Minimum Java Version | |:---------------------------|:-----------------|:-------------------------|:-------------------------|:---------------------| +| 3.16 | 3.16 | 3.5, 3.4 | 2.13, 2.12 | 8 | | 3.15 | 3.15 | 3.5, 3.4 | 2.13, 2.12 | 8 | -| 3.14 | 3.14 | 3.5, 3.4 | 2.13, 2.12 | 8 | -| 3.12 | 3.12 | 3.5, 3.4 | 2.13, 2.12 | 8 | diff --git a/docs/scalardb-cluster/compatibility.mdx b/docs/scalardb-cluster/compatibility.mdx index 0b469206..5aafdca9 100644 --- a/docs/scalardb-cluster/compatibility.mdx +++ b/docs/scalardb-cluster/compatibility.mdx @@ -13,6 +13,7 @@ This document shows the compatibility of ScalarDB Cluster versions among client | ScalarDB Cluster version | ScalarDB Cluster Java Client SDK version | ScalarDB Cluster .NET Client SDK version | |:-------------------------|:-----------------------------------------|:-----------------------------------------| +| 3.16 | 3.9 - 3.16 | 3.12* - 3.16 | | 3.15 | 3.9 - 3.15 | 3.12* - 3.15 | | 3.14 | 3.9 - 3.14 | 3.12* - 3.14 | | 3.13 | 3.9 - 3.13 | 3.12* - 3.13 | diff --git a/docs/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx b/docs/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx index 964f3316..b4b0830a 100644 --- a/docs/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx +++ b/docs/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx @@ -18,7 +18,7 @@ To add a dependency on the ScalarDB Cluster Java Client SDK by using Gradle, use ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -28,7 +28,7 @@ To add a dependency by using Maven, use the following: com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -94,17 +94,17 @@ The following section describes the Schema Loader for ScalarDB Cluster. To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). Using the Schema Loader for Cluster is basically the same as using the [ScalarDB Schema Loader](../schema-loader.mdx) except the name of the JAR file is different. -You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). +You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0). After downloading the JAR file, you can run Schema Loader for Cluster with the following command: ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config --schema-file --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config --schema-file --coordinator ``` You can also pull the Docker image from the [Scalar container registry](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-schema-loader) by running the following command, replacing the contents in the angle brackets as described: ```console -docker run --rm -v :/scalardb.properties -v :/schema.json ghcr.io/scalar-labs/scalardb-cluster-schema-loader:3.15.4 --config /scalardb.properties --schema-file /schema.json --coordinator +docker run --rm -v :/scalardb.properties -v :/schema.json ghcr.io/scalar-labs/scalardb-cluster-schema-loader:3.16.0 --config /scalardb.properties --schema-file /schema.json --coordinator ``` ## ScalarDB Cluster SQL @@ -144,8 +144,8 @@ To add the dependencies on the ScalarDB Cluster JDBC driver by using Gradle, use ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-sql-jdbc:3.15.4' - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-sql-jdbc:3.16.0' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -156,12 +156,12 @@ To add the dependencies by using Maven, use the following: com.scalar-labs scalardb-sql-jdbc - 3.15.4 + 3.16.0 com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -179,8 +179,8 @@ To add the dependencies by using Gradle, use the following: ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-sql-spring-data:3.15.4' - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-sql-spring-data:3.16.0' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -191,12 +191,12 @@ To add the dependencies by using Maven, use the following: com.scalar-labs scalardb-sql-spring-data - 3.15.4 + 3.16.0 com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -208,16 +208,16 @@ For details about Spring Data JDBC for ScalarDB, see [Guide of Spring Data JDBC Like other SQL databases, ScalarDB SQL also provides a CLI tool where you can issue SQL statements interactively in a command-line shell. -You can download the SQL CLI for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can run the SQL CLI with the following command: +You can download the SQL CLI for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0). After downloading the JAR file, you can run the SQL CLI with the following command: ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config ``` You can also pull the Docker image from the [Scalar container registry](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-sql-cli) by running the following command, replacing the contents in the angle brackets as described: ```console -docker run --rm -it -v :/scalardb-sql.properties ghcr.io/scalar-labs/scalardb-cluster-sql-cli:3.15.4 --config /scalardb-sql.properties +docker run --rm -it -v :/scalardb-sql.properties ghcr.io/scalar-labs/scalardb-cluster-sql-cli:3.16.0 --config /scalardb-sql.properties ``` #### Usage @@ -225,7 +225,7 @@ docker run --rm -it -v :/scalar You can see the CLI usage with the `-h` option as follows: ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar -h +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar -h Usage: scalardb-sql-cli [-hs] -c=PROPERTIES_FILE [-e=COMMAND] [-f=FILE] [-l=LOG_FILE] [-o=] [-p=PASSWORD] [-u=USERNAME] @@ -256,6 +256,6 @@ For details about the ScalarDB Cluster gRPC API, refer to the following: JavaDocs are also available: -* [ScalarDB Cluster Java Client SDK](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-java-client-sdk/3.15.4/index.html) -* [ScalarDB Cluster Common](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-common/3.15.4/index.html) -* [ScalarDB Cluster RPC](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-rpc/3.15.4/index.html) +* [ScalarDB Cluster Java Client SDK](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-java-client-sdk/3.16.0/index.html) +* [ScalarDB Cluster Common](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-common/3.16.0/index.html) +* [ScalarDB Cluster RPC](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-rpc/3.16.0/index.html) diff --git a/docs/scalardb-cluster/encrypt-data-at-rest.mdx b/docs/scalardb-cluster/encrypt-data-at-rest.mdx index ea2389fa..e7e49d7e 100644 --- a/docs/scalardb-cluster/encrypt-data-at-rest.mdx +++ b/docs/scalardb-cluster/encrypt-data-at-rest.mdx @@ -183,7 +183,7 @@ services: scalardb-cluster-standalone: container_name: "scalardb-cluster-node" - image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.16.0" ports: - 60053:60053 - 9080:9080 @@ -241,7 +241,7 @@ scalar.db.sql.cluster_mode.contact_points=indirect:localhost Then, start the SQL CLI by running the following command. ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` To begin, create the Coordinator tables required for ScalarDB transaction execution. diff --git a/docs/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx b/docs/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx index 1234c270..30bf1fb3 100644 --- a/docs/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx +++ b/docs/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx @@ -108,11 +108,11 @@ For details about the client modes, see [Developer Guide for ScalarDB Cluster wi To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). Using the Schema Loader for Cluster is basically the same as using the [Schema Loader for ScalarDB](../schema-loader.mdx) except the name of the JAR file is different. -You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). +You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0). After downloading the JAR file, you can run the Schema Loader for Cluster with the following command: ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config database.properties -f schema.json --coordinator ``` ## Step 4. Run operations from GraphiQL diff --git a/docs/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx b/docs/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx index d0910d07..5ed6d41c 100644 --- a/docs/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx +++ b/docs/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx @@ -86,10 +86,10 @@ For details about the client modes, see [Developer Guide for ScalarDB Cluster wi ## Step 3. Load a schema -To load a schema, you need to use [the SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli). You can download the SQL CLI from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can use SQL CLI for Cluster by running the following command: +To load a schema, you need to use [the SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli). You can download the SQL CLI from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0). After downloading the JAR file, you can use SQL CLI for Cluster by running the following command: ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-sql.properties --file schema.sql +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-sql.properties --file schema.sql ``` ## Step 4. Load the initial data diff --git a/docs/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx b/docs/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx index 2fa48c23..076b66c0 100644 --- a/docs/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx +++ b/docs/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx @@ -86,10 +86,10 @@ For details about the client modes, see [Developer Guide for ScalarDB Cluster wi ## Step 3. Load a schema -To load a schema, you need to use [the SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli). You can download the SQL CLI from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can use SQL CLI for Cluster by running the following command: +To load a schema, you need to use [the SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli). You can download the SQL CLI from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0). After downloading the JAR file, you can use SQL CLI for Cluster by running the following command: ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-sql.properties --file schema.sql +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-sql.properties --file schema.sql ``` ## Step 4. Modify `application.properties` diff --git a/docs/scalardb-cluster/getting-started-with-scalardb-cluster.mdx b/docs/scalardb-cluster/getting-started-with-scalardb-cluster.mdx index 140afe2b..d8f1db4f 100644 --- a/docs/scalardb-cluster/getting-started-with-scalardb-cluster.mdx +++ b/docs/scalardb-cluster/getting-started-with-scalardb-cluster.mdx @@ -120,7 +120,7 @@ To use ScalarDB Cluster, open `build.gradle` in your preferred text editor. Then dependencies { ... - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -166,12 +166,12 @@ For details about the client modes, see [Developer Guide for ScalarDB Cluster wi The database schema (the method in which the data will be organized) for the sample application has already been defined in [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sample/schema.json). -To apply the schema, go to [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) and download the ScalarDB Cluster Schema Loader to the `scalardb-samples/scalardb-sample` folder. +To apply the schema, go to [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0) and download the ScalarDB Cluster Schema Loader to the `scalardb-samples/scalardb-sample` folder. Then, run the following command: ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config database.properties -f schema.json --coordinator ``` #### Schema details diff --git a/docs/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx b/docs/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx index 718b951e..780a30c0 100644 --- a/docs/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx +++ b/docs/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx @@ -73,10 +73,10 @@ For details about the client modes, see [Developer Guide for ScalarDB Cluster wi ## Step 3. Load a schema -To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). Using the Schema Loader for Cluster is basically the same as using the [Schema Loader for ScalarDB](../schema-loader.mdx) except the name of the JAR file is different. You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can run the Schema Loader for Cluster with the following command: +To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). Using the Schema Loader for Cluster is basically the same as using the [Schema Loader for ScalarDB](../schema-loader.mdx) except the name of the JAR file is different. You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0). After downloading the JAR file, you can run the Schema Loader for Cluster with the following command: ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config database.properties -f schema.json --coordinator ``` ## Step 4. Set up a Go environment diff --git a/docs/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx b/docs/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx index f51d3ba0..868b3c9d 100644 --- a/docs/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx +++ b/docs/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx @@ -73,10 +73,10 @@ For details about the client modes, see [Developer Guide for ScalarDB Cluster wi ## Step 3. Load a schema -To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). Using the Schema Loader for Cluster is basically the same as using the [Schema Loader for ScalarDB](../schema-loader.mdx) except the name of the JAR file is different. You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can run the Schema Loader for Cluster with the following command: +To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). Using the Schema Loader for Cluster is basically the same as using the [Schema Loader for ScalarDB](../schema-loader.mdx) except the name of the JAR file is different. You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0). After downloading the JAR file, you can run the Schema Loader for Cluster with the following command: ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config database.properties -f schema.json --coordinator ``` ## Step 4. Set up a Python environment diff --git a/docs/scalardb-cluster/getting-started-with-vector-search.mdx b/docs/scalardb-cluster/getting-started-with-vector-search.mdx index 3432ceb2..b30b51e1 100644 --- a/docs/scalardb-cluster/getting-started-with-vector-search.mdx +++ b/docs/scalardb-cluster/getting-started-with-vector-search.mdx @@ -331,7 +331,7 @@ Create the following configuration file as `docker-compose.yaml`. services: scalardb-cluster-standalone: container_name: "scalardb-cluster-node" - image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.16.0" ports: - 60053:60053 - 9080:9080 @@ -361,7 +361,7 @@ Select your build tool, and follow the instructions to add the build dependency ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-cluster-embedding-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-embedding-java-client-sdk:3.16.0' } ```
@@ -372,7 +372,7 @@ Select your build tool, and follow the instructions to add the build dependency com.scalar-labs scalardb-cluster-embedding-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -460,4 +460,4 @@ The `ScalarDbEmbeddingClientFactory` instance should be closed after use to rele The vector search feature is currently in Private Preview. For more details, please [contact us](https://www.scalar-labs.com/contact) or wait for this feature to become publicly available in a future version. -- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-embedding-java-client-sdk/3.15.4/index.html) +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-embedding-java-client-sdk/3.16.0/index.html) diff --git a/docs/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx b/docs/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx index 9261de2a..3fcdeffd 100644 --- a/docs/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx +++ b/docs/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx @@ -141,6 +141,29 @@ For a list of databases that ScalarDB supports, see [Databases](../requirements. scalar.db.password=SqlServer22 ``` + +

Run Db2 locally

+ + You can run IBM Db2 in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start IBM Db2, run the following command: + + ```console + docker compose up -d db2 + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Db2 in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Db2 + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:db2://db2-1:50000/sample + scalar.db.username=db2inst1 + scalar.db.password=db2inst1 + ``` +

Run Amazon DynamoDB Local

@@ -271,7 +294,7 @@ Select your build tool, and follow the instructions to add the build dependency ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ```
@@ -282,7 +305,7 @@ Select your build tool, and follow the instructions to add the build dependency com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -307,5 +330,5 @@ The following limitations apply to non-transactional storage operations: ### Learn more -- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.15.4/index.html) +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.16.0/index.html) - [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) diff --git a/docs/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx b/docs/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx index 9479c41f..71249c3b 100644 --- a/docs/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx +++ b/docs/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx @@ -276,8 +276,8 @@ Also, for a list of supported DDLs, see [ScalarDB SQL Grammar](../scalardb-sql/g ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-sql-jdbc:3.15.4' - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-sql-jdbc:3.16.0' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -289,12 +289,12 @@ Also, for a list of supported DDLs, see [ScalarDB SQL Grammar](../scalardb-sql/g com.scalar-labs scalardb-sql-jdbc - 3.15.4 + 3.16.0 com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -341,8 +341,8 @@ The following limitations apply to non-transactional storage operations: ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-sql:3.15.4' - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-sql:3.16.0' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -354,12 +354,12 @@ The following limitations apply to non-transactional storage operations: com.scalar-labs scalardb-sql - 3.15.4 + 3.16.0 com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -387,7 +387,7 @@ The following limitations apply to non-transactional storage operations:

Learn more

- - [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.15.4/index.html) + - [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.16.0/index.html) diff --git a/docs/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx b/docs/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx index f3677a25..d4504ac0 100644 --- a/docs/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx +++ b/docs/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx @@ -140,6 +140,29 @@ For a list of databases that ScalarDB supports, see [Databases](../requirements. scalar.db.password=SqlServer22 ``` + +

Run Db2 locally

+ + You can run IBM Db2 in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start IBM Db2, run the following command: + + ```console + docker compose up -d db2 + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Db2 in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Db2 + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:db2://db2-1:50000/sample + scalar.db.username=db2inst1 + scalar.db.password=db2inst1 + ``` +

Run Amazon DynamoDB Local

diff --git a/docs/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx b/docs/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx index 1d9ed0c1..c4e7fb10 100644 --- a/docs/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx +++ b/docs/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx @@ -141,6 +141,29 @@ For a list of databases that ScalarDB supports, see [Databases](../requirements. scalar.db.password=SqlServer22 ```
+ +

Run Db2 locally

+ + You can run IBM Db2 in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start IBM Db2, run the following command: + + ```console + docker compose up -d db2 + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Db2 in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Db2 + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:db2://db2-1:50000/sample + scalar.db.username=db2inst1 + scalar.db.password=db2inst1 + ``` +

Run Amazon DynamoDB Local

diff --git a/docs/scalardb-cluster/scalardb-abac-status-codes.mdx b/docs/scalardb-cluster/scalardb-abac-status-codes.mdx index 35df2526..22aa089a 100644 --- a/docs/scalardb-cluster/scalardb-abac-status-codes.mdx +++ b/docs/scalardb-cluster/scalardb-abac-status-codes.mdx @@ -381,6 +381,14 @@ The namespace policy for the policy and namespace already exists. Policy: %s; Na The table policy for the policy and table already exists. Policy: %s; Table: %s ``` +### `DB-ABAC-10045` + +**Message** + +```markdown +The user does not exist. Username: %s +``` + ## `DB-ABAC-2xxxx` status codes The following are status codes and messages for the concurrency error category. diff --git a/docs/scalardb-cluster/scalardb-auth-with-sql.mdx b/docs/scalardb-cluster/scalardb-auth-with-sql.mdx index afeb17f5..953e97a8 100644 --- a/docs/scalardb-cluster/scalardb-auth-with-sql.mdx +++ b/docs/scalardb-cluster/scalardb-auth-with-sql.mdx @@ -208,7 +208,7 @@ services: scalardb-cluster-standalone: container_name: "scalardb-cluster-node" - image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.16.0" ports: - 60053:60053 - 9080:9080 @@ -246,7 +246,7 @@ scalar.db.cluster.auth.enabled=true Then, start the SQL CLI by running the following command. ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` Enter the username and password as `admin` and `admin`, respectively. @@ -335,7 +335,7 @@ You can see that `user1` has been granted the `SELECT`, `INSERT`, and `UPDATE` p Log in as `user1` and execute SQL statements. ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` Enter the username and password as `user1` and `user1`, respectively. diff --git a/docs/scalardb-cluster/scalardb-cluster-configurations.mdx b/docs/scalardb-cluster/scalardb-cluster-configurations.mdx index 87051421..4575bad3 100644 --- a/docs/scalardb-cluster/scalardb-cluster-configurations.mdx +++ b/docs/scalardb-cluster/scalardb-cluster-configurations.mdx @@ -22,32 +22,32 @@ The following general configurations are available for ScalarDB Cluster. #### Transaction management configurations -| Name | Description | Default | +| Name | Description | Default. | |-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------| | `scalar.db.transaction_manager` | Transaction manager of ScalarDB. Specify `consensus-commit` to use [Consensus Commit](../consensus-commit.mdx) or `single-crud-operation` to [run non-transactional storage operations](./run-non-transactional-storage-operations-through-scalardb-cluster.mdx). Note that the configurations under the `scalar.db.consensus_commit` prefix are ignored if you use `single-crud-operation`. | `consensus-commit` | -| `scalar.db.consensus_commit.isolation_level` | Isolation level used for Consensus Commit. Either `SNAPSHOT` or `SERIALIZABLE` can be specified. | `SNAPSHOT` | -| `scalar.db.consensus_commit.serializable_strategy` | Serializable strategy used for Consensus Commit. Either `EXTRA_READ` or `EXTRA_WRITE` can be specified. If `SNAPSHOT` is specified in the property `scalar.db.consensus_commit.isolation_level`, this configuration will be ignored. | `EXTRA_READ` | +| `scalar.db.consensus_commit.isolation_level` | Isolation level used for Consensus Commit. Either `SNAPSHOT`, `SERIALIZABLE`, or `READ_COMMITTED` can be specified. | `SNAPSHOT` | | `scalar.db.consensus_commit.coordinator.namespace` | Namespace name of Coordinator tables. | `coordinator` | | `scalar.db.consensus_commit.include_metadata.enabled` | If set to `true`, `Get` and `Scan` operations results will contain transaction metadata. To see the transaction metadata columns details for a given table, you can use the `DistributedTransactionAdmin.getTableMetadata()` method, which will return the table metadata augmented with the transaction metadata columns. Using this configuration can be useful to investigate transaction-related issues. | `false` | #### Node configurations -| Name | Description | Default | -|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------| -| `scalar.db.cluster.membership.type` | Membership type. Currently, only `KUBERNETES` can be specified. | `KUBERNETES` | -| `scalar.db.cluster.membership.kubernetes.endpoint.namespace_name` | This configuration is for the `KUBERNETES` membership type. Namespace name for the [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints). | `default` | -| `scalar.db.cluster.membership.kubernetes.endpoint.name` | This configuration is for the `KUBERNETES` membership type. Name of the [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) to get the membership info. | | -| `scalar.db.cluster.node.decommissioning_duration_secs` | Decommissioning duration in seconds. | `30` | -| `scalar.db.cluster.node.grpc.max_inbound_message_size` | Maximum message size allowed to be received. | The gRPC default value | -| `scalar.db.cluster.node.grpc.max_inbound_metadata_size` | Maximum size of metadata allowed to be received. | The gRPC default value | -| `scalar.db.cluster.node.port` | Port number of the ScalarDB Cluster node. | `60053` | -| `scalar.db.cluster.node.prometheus_exporter_port` | Port number of the Prometheus exporter. | `9080` | -| `scalar.db.cluster.grpc.deadline_duration_millis` | Deadline duration for gRPC in milliseconds. | `60000` (60 seconds) | -| `scalar.db.cluster.node.standalone_mode.enabled` | Whether standalone mode is enabled. Note that if standalone mode is enabled, the membership configurations (`scalar.db.cluster.membership.*`) will be ignored. | `false` | -| `scalar.db.metadata.cache_expiration_time_secs` | ScalarDB has a metadata cache to reduce the number of requests to the database. This setting specifies the expiration time of the cache in seconds. If you specify `-1`, the cache will never expire. | `60` | -| `scalar.db.active_transaction_management.expiration_time_millis` | ScalarDB Cluster nodes maintain ongoing transactions, which can be resumed by using a transaction ID. This configuration specifies the expiration time of this transaction management feature in milliseconds. | `60000` (60 seconds) | -| `scalar.db.system_namespace_name` | The given namespace name will be used by ScalarDB internally. | `scalardb` | -| `scalar.db.transaction.enabled` | Whether the transaction feature is enabled. For example, if you use only the embedding feature, you can set this property to `false`. | `true` | +| Name | Description   | Default | +|--------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------| +| `scalar.db.cluster.membership.type` | Membership type. Currently, only `KUBERNETES` can be specified. | `KUBERNETES` | +| `scalar.db.cluster.membership.kubernetes.endpoint.namespace_name` | This configuration is for the `KUBERNETES` membership type. Namespace name for the [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints). | `default` | +| `scalar.db.cluster.membership.kubernetes.endpoint.name` | This configuration is for the `KUBERNETES` membership type. Name of the [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) to get the membership info. | | +| `scalar.db.cluster.node.decommissioning_duration_secs` | Decommissioning duration in seconds. | `30` | +| `scalar.db.cluster.node.grpc.max_inbound_message_size` | Maximum message size allowed to be received. | The gRPC default value | +| `scalar.db.cluster.node.grpc.max_inbound_metadata_size` | Maximum size of metadata allowed to be received. | The gRPC default value | +| `scalar.db.cluster.node.port` | Port number of the ScalarDB Cluster node. | `60053` | +| `scalar.db.cluster.node.prometheus_exporter_port` | Port number of the Prometheus exporter. | `9080` | +| `scalar.db.cluster.grpc.deadline_duration_millis` | Deadline duration for gRPC in milliseconds. | `60000` (60 seconds) | +| `scalar.db.cluster.node.standalone_mode.enabled` | Whether standalone mode is enabled. Note that if standalone mode is enabled, the membership configurations (`scalar.db.cluster.membership.*`) will be ignored. | `false` | +| `scalar.db.metadata.cache_expiration_time_secs` | ScalarDB has a metadata cache to reduce the number of requests to the database. This setting specifies the expiration time of the cache in seconds. If you specify `-1`, the cache will never expire. | `60` | +| `scalar.db.active_transaction_management.expiration_time_millis` | ScalarDB Cluster nodes maintain in-progress transactions, which can be resumed by using a transaction ID. This process expires transactions that have been idle for an extended period to prevent resource leaks. This configuration specifies the expiration time of this transaction management feature in milliseconds. | `60000` (60 seconds) | +| `scalar.db.system_namespace_name` | The given namespace name will be used by ScalarDB internally. | `scalardb` | +| `scalar.db.transaction.enabled` | Whether the transaction feature is enabled. For example, if you use only the embedding feature, you can set this property to `false`. | `true` | +| `scalar.db.cluster.node.scanner_management.expiration_time_millis` | ScalarDB Cluster nodes maintain in-progress scanners. This process expires scanners that have been idle for an extended period to prevent resource leaks. This configuration specifies the expiration time of this scanner management feature in milliseconds. | `60000` (60 seconds) | ### Performance-related configurations @@ -63,6 +63,8 @@ The following performance-related configurations are available for the Consensus | `scalar.db.consensus_commit.async_commit.enabled` | Whether or not the commit phase is executed asynchronously. | `false` | | `scalar.db.consensus_commit.async_rollback.enabled` | Whether or not the rollback phase is executed asynchronously. | The value of `scalar.db.consensus_commit.async_commit.enabled` | | `scalar.db.consensus_commit.parallel_implicit_pre_read.enabled` | Whether or not implicit pre-read is executed in parallel. | `true` | +| `scalar.db.consensus_commit.one_phase_commit.enabled` | Whether or not the one-phase commit optimization is enabled. | `false` | +| `scalar.db.consensus_commit.coordinator.write_omission_on_read_only.enabled` | Whether or not the write omission optimization is enabled for read-only transactions. This optimization is useful for read-only transactions that do not modify any data, as it avoids unnecessary writes to the Coordinator tables. | `true` | | `scalar.db.consensus_commit.coordinator.group_commit.enabled` | Whether or not committing the transaction state is executed in batch mode. This feature can't be used with a two-phase commit interface. | `false` | | `scalar.db.consensus_commit.coordinator.group_commit.slot_capacity` | Maximum number of slots in a group for the group commit feature. A large value improves the efficiency of group commit, but may also increase latency and the likelihood of transaction conflicts.[^1] | `20` | | `scalar.db.consensus_commit.coordinator.group_commit.group_size_fix_timeout_millis` | Timeout to fix the size of slots in a group. A large value improves the efficiency of group commit, but may also increase latency and the likelihood of transaction conflicts.[^1] | `40` | @@ -81,25 +83,26 @@ Select a database to see the configurations available for each storage. The following configurations are available for JDBC databases: - | Name | Description | Default | - |-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| - | `scalar.db.storage` | `jdbc` must be specified. | - | - | `scalar.db.contact_points` | JDBC connection URL. | | - | `scalar.db.username` | Username to access the database. | | - | `scalar.db.password` | Password to access the database. | | - | `scalar.db.jdbc.connection_pool.min_idle` | Minimum number of idle connections in the connection pool. | `20` | - | `scalar.db.jdbc.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool. | `50` | - | `scalar.db.jdbc.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool. Use a negative value for no limit. | `100` | - | `scalar.db.jdbc.prepared_statements_pool.enabled` | Setting this property to `true` enables prepared-statement pooling. | `false` | - | `scalar.db.jdbc.prepared_statements_pool.max_open` | Maximum number of open statements that can be allocated from the statement pool at the same time. Use a negative value for no limit. | `-1` | - | `scalar.db.jdbc.isolation_level` | Isolation level for JDBC. `READ_UNCOMMITTED`, `READ_COMMITTED`, `REPEATABLE_READ`, or `SERIALIZABLE` can be specified. | Underlying-database specific | - | `scalar.db.jdbc.table_metadata.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for the table metadata. | `5` | - | `scalar.db.jdbc.table_metadata.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for the table metadata. | `10` | - | `scalar.db.jdbc.table_metadata.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for the table metadata. Use a negative value for no limit. | `25` | - | `scalar.db.jdbc.admin.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for admin. | `5` | - | `scalar.db.jdbc.admin.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for admin. | `10` | - | `scalar.db.jdbc.admin.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for admin. Use a negative value for no limit. | `25` | - + | Name | Description | Default | + |-----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| + | `scalar.db.storage` | `jdbc` must be specified. | - | + | `scalar.db.contact_points` | JDBC connection URL. | | + | `scalar.db.username` | Username to access the database. | | + | `scalar.db.password` | Password to access the database. | | + | `scalar.db.jdbc.connection_pool.min_idle` | Minimum number of idle connections in the connection pool. | `20` | + | `scalar.db.jdbc.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool. | `50` | + | `scalar.db.jdbc.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool. Use a negative value for no limit. | `100` | + | `scalar.db.jdbc.prepared_statements_pool.enabled` | Setting this property to `true` enables prepared-statement pooling. | `false` | + | `scalar.db.jdbc.prepared_statements_pool.max_open` | Maximum number of open statements that can be allocated from the statement pool at the same time. Use a negative value for no limit. | `-1` | + | `scalar.db.jdbc.isolation_level` | Isolation level for JDBC. `READ_UNCOMMITTED`, `READ_COMMITTED`, `REPEATABLE_READ`, or `SERIALIZABLE` can be specified. | Underlying-database specific | + | `scalar.db.jdbc.table_metadata.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for the table metadata. | `5` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for the table metadata. | `10` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for the table metadata. Use a negative value for no limit. | `25` | + | `scalar.db.jdbc.admin.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for admin. | `5` | + | `scalar.db.jdbc.admin.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for admin. | `10` | + | `scalar.db.jdbc.admin.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for admin. Use a negative value for no limit. | `25` | + | `scalar.db.jdbc.db2.variable_key_column_size` | Column size for TEXT and BLOB columns in IBM Db2 when they are used as a primary key or secondary key. Minimum 64 bytes. | `128` | + | `scalar.db.jdbc.db2.time_column.default_date_component` | Value of the date component used for storing `TIME` data in IBM Db2. Since the IBM Db2 TIMESTAMP type is used to store ScalarDB `TIME` type data because it provides fractional-second precision, ScalarDB stores `TIME` data with the same date component value for ease of comparison and sorting. | `1970-01-01` | :::note If you're using SQLite3 as a JDBC database, you must set `scalar.db.contact_points` as follows: @@ -172,6 +175,14 @@ For non-JDBC databases, we do not recommend enabling cross-partition scan with t | `scalar.db.cross_partition_scan.filtering.enabled` | Enable filtering in cross-partition scan. | `false` | | `scalar.db.cross_partition_scan.ordering.enabled` | Enable ordering in cross-partition scan. | `false` | +#### Scan fetch size + +You can configure the fetch size for storage scan operations by using the following property: + +| Name | Description | Default | +|-----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `scalar.db.scan_fetch_size` | Specifies the number of records to fetch in a single batch during a storage scan operation. A larger value can improve performance for a large result set by reducing round trips to the storage, but it also increases memory usage. A smaller value uses less memory but may increase latency. | `10` | + ### GraphQL-related configurations The configurations for ScalarDB Cluster GraphQL are as follows: @@ -233,6 +244,7 @@ The following table shows the general configurations for the ScalarDB Cluster cl | `scalar.db.cluster.grpc.deadline_duration_millis` | Deadline duration for gRPC in millis. | `60000` (60 seconds) | | `scalar.db.cluster.grpc.max_inbound_message_size` | Maximum message size allowed for a single gRPC frame. | The gRPC default value | | `scalar.db.cluster.grpc.max_inbound_metadata_size` | Maximum size of metadata allowed to be received. | The gRPC default value | +| `scalar.db.cluster.client.scan_fetch_size` | The fetch size used for `Scanner` to fetch data from the cluster. This is the number of records that `Scanner` fetches at once from the cluster. A larger value can improve performance by reducing the number of round trips to the cluster, but it may also increase memory usage. | `10` | For example, if you use the `indirect` client mode and the load balancer IP address is `192.168.10.1`, you can configure the client as follows: diff --git a/docs/scalardb-cluster/scalardb-cluster-status-codes.mdx b/docs/scalardb-cluster/scalardb-cluster-status-codes.mdx index 0005c1fa..01693c3b 100644 --- a/docs/scalardb-cluster/scalardb-cluster-status-codes.mdx +++ b/docs/scalardb-cluster/scalardb-cluster-status-codes.mdx @@ -45,14 +45,6 @@ The table does not exist. Table: %s The user does not exist. User: %s ``` -### `DB-CLUSTER-10003` - -**Message** - -```markdown -ClusterConfig is not specified -``` - ### `DB-CLUSTER-10004` **Message** @@ -293,14 +285,6 @@ The property 'scalar.db.sql.cluster_mode.contact_points' must be prefixed with ' The format of the property 'scalar.db.sql.cluster_mode.contact_points' for direct-kubernetes client mode is 'direct-kubernetes:/' or 'direct-kubernetes:' ``` -### `DB-CLUSTER-10034` - -**Message** - -```markdown -ClusterNodeManagerFactory is not specified -``` - ### `DB-CLUSTER-10035` **Message** @@ -325,14 +309,6 @@ The update condition type is unrecognized The two-phase commit interface is not supported ``` -### `DB-CLUSTER-10038` - -**Message** - -```markdown -Membership is not specified -``` - ### `DB-CLUSTER-10039` **Message** @@ -497,6 +473,14 @@ The hop limit is exceeded A transaction associated with the specified transaction ID is not found. The transaction might have expired, or the cluster node that handled the transaction might have been restarted. Transaction ID: %s ``` +### `DB-CLUSTER-20002` + +**Message** + +```markdown +A scanner associated with the specified scanner ID is not found. The scanner might have expired, or the cluster node that handled the scanner might have been restarted. Transaction ID: %s; Scanner ID: %s +``` + ## `DB-CLUSTER-3xxxx` status codes The following are status codes and messages for the internal error category. diff --git a/docs/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx b/docs/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx index a62e6578..bb4294e1 100644 --- a/docs/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx +++ b/docs/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx @@ -170,7 +170,7 @@ You can deploy PostgreSQL on the Kubernetes cluster as follows. 5. Set the chart version of ScalarDB Cluster. ```console - SCALAR_DB_CLUSTER_VERSION=3.15.4 + SCALAR_DB_CLUSTER_VERSION=3.16.0 SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) ``` diff --git a/docs/scalardb-core-status-codes.mdx b/docs/scalardb-core-status-codes.mdx index 1bac0c42..bbb3a1f6 100644 --- a/docs/scalardb-core-status-codes.mdx +++ b/docs/scalardb-core-status-codes.mdx @@ -180,7 +180,7 @@ The mutations are empty **Message** ```markdown -Mutations that span multiple partitions are not supported. Mutations: %s +The storage does not support mutations across multiple partitions. Storage: %s; Mutations: %s ``` ### `DB-CORE-10020` @@ -324,7 +324,7 @@ This operation is supported only when no conditions are specified. If you want t **Message** ```markdown -One or more columns must be specified. +One or more columns must be specified ``` ### `DB-CORE-10039` @@ -332,7 +332,7 @@ One or more columns must be specified. **Message** ```markdown -One or more partition keys must be specified. +One or more partition keys must be specified ``` ### `DB-CORE-10040` @@ -372,7 +372,7 @@ The transaction is not active. Status: %s **Message** ```markdown -The transaction has already been committed or rolled back. Status: %s +The transaction has already been committed. Status: %s ``` ### `DB-CORE-10045` @@ -828,15 +828,7 @@ Put cannot have a condition when the target record is unread and implicit pre-re **Message** ```markdown -Writing already-deleted data is not allowed -``` - -### `DB-CORE-10105` - -**Message** - -```markdown -Getting data neither in the read set nor the delete set is not allowed +Writing data already-deleted by the same transaction is not allowed ``` ### `DB-CORE-10106` @@ -844,7 +836,7 @@ Getting data neither in the read set nor the delete set is not allowed **Message** ```markdown -Reading already-written data is not allowed +Scanning data already-written or already-deleted by the same transaction is not allowed ``` ### `DB-CORE-10107` @@ -852,7 +844,7 @@ Reading already-written data is not allowed **Message** ```markdown -The transaction is not validated. When using the EXTRA_READ serializable strategy, you need to call validate() before calling commit() +The transaction is not validated. When using the SERIALIZABLE isolation level, you need to call validate() before calling commit() ``` ### `DB-CORE-10108` @@ -863,142 +855,6 @@ The transaction is not validated. When using the EXTRA_READ serializable strateg DynamoDB cannot batch more than 100 mutations at once ``` -### `DB-CORE-10109` - -**Message** - -```markdown -The partition keys of the table %s.%s were modified, but altering partition keys is not supported -``` - -### `DB-CORE-10110` - -**Message** - -```markdown -The clustering keys of the table %s.%s were modified, but altering clustering keys is not supported -``` - -### `DB-CORE-10111` - -**Message** - -```markdown -The clustering ordering of the table %s.%s were modified, but altering clustering ordering is not supported -``` - -### `DB-CORE-10112` - -**Message** - -```markdown -The column %s of the table %s.%s has been deleted. Column deletion is not supported when altering a table -``` - -### `DB-CORE-10113` - -**Message** - -```markdown -The data type of the column %s of the table %s.%s was modified, but altering data types is not supported -``` - -### `DB-CORE-10114` - -**Message** - -```markdown -Specifying the '--schema-file' option is required when using the '--repair-all' option -``` - -### `DB-CORE-10115` - -**Message** - -```markdown -Specifying the '--schema-file' option is required when using the '--alter' option -``` - -### `DB-CORE-10116` - -**Message** - -```markdown -Specifying the '--schema-file' option is required when using the '--import' option -``` - -### `DB-CORE-10117` - -**Message** - -```markdown -Specifying the '--coordinator' option with the '--import' option is not allowed. Create Coordinator tables separately -``` - -### `DB-CORE-10118` - -**Message** - -```markdown -Reading the configuration file failed. File: %s -``` - -### `DB-CORE-10119` - -**Message** - -```markdown -Reading the schema file failed. File: %s -``` - -### `DB-CORE-10120` - -**Message** - -```markdown -Parsing the schema JSON failed. Details: %s -``` - -### `DB-CORE-10121` - -**Message** - -```markdown -The table name must contain the namespace and the table. Table: %s -``` - -### `DB-CORE-10122` - -**Message** - -```markdown -The partition key must be specified. Table: %s -``` - -### `DB-CORE-10123` - -**Message** - -```markdown -Invalid clustering-key format. The clustering key must be in the format of 'column_name' or 'column_name ASC/DESC'. Table: %s; Clustering key: %s -``` - -### `DB-CORE-10124` - -**Message** - -```markdown -Columns must be specified. Table: %s -``` - -### `DB-CORE-10125` - -**Message** - -```markdown -Invalid column type. Table: %s; Column: %s; Type: %s -``` - ### `DB-CORE-10126` **Message** @@ -1039,46 +895,6 @@ Cross-partition scan with ordering is not supported in Cosmos DB Cross-partition scan with ordering is not supported in DynamoDB ``` -### `DB-CORE-10131` - -**Message** - -```markdown -The directory '%s' does not have write permissions. Please ensure that the current user has write access to the directory. -``` - -### `DB-CORE-10132` - -**Message** - -```markdown -Failed to create the directory '%s'. Please check if you have sufficient permissions and if there are any file system restrictions. Details: %s -``` - -### `DB-CORE-10133` - -**Message** - -```markdown -Directory path cannot be null or empty. -``` - -### `DB-CORE-10134` - -**Message** - -```markdown -No file extension was found on the provided file name %s. -``` - -### `DB-CORE-10135` - -**Message** - -```markdown -Invalid file extension: %s. Allowed extensions are: %s -``` - ### `DB-CORE-10136` **Message** @@ -1164,7 +980,7 @@ The value of the column %s in the primary key contains an illegal character. Pri **Message** ```markdown -Inserting already-written data is not allowed +Inserting data already-written by the same transaction is not allowed ``` ### `DB-CORE-10147` @@ -1172,39 +988,7 @@ Inserting already-written data is not allowed **Message** ```markdown -Deleting already-inserted data is not allowed -``` - -### `DB-CORE-10148` - -**Message** - -```markdown -Invalid key: Column %s does not exist in the table %s in namespace %s. -``` - -### `DB-CORE-10149` - -**Message** - -```markdown -Invalid base64 encoding for blob value for column %s in table %s in namespace %s -``` - -### `DB-CORE-10150` - -**Message** - -```markdown -Invalid number specified for column %s in table %s in namespace %s -``` - -### `DB-CORE-10151` - -**Message** - -```markdown -Method null argument not allowed +Deleting data already-inserted by the same transaction is not allowed ``` ### `DB-CORE-10152` @@ -1215,46 +999,6 @@ Method null argument not allowed The attribute-based access control feature is not enabled. To use this feature, you must enable it. Note that this feature is supported only in the ScalarDB Enterprise edition ``` -### `DB-CORE-10153` - -**Message** - -```markdown -The provided clustering key %s was not found -``` - -### `DB-CORE-10154` - -**Message** - -```markdown -The column '%s' was not found -``` - -### `DB-CORE-10155` - -**Message** - -```markdown -The provided partition key is incomplete. Required key: %s -``` - -### `DB-CORE-10156` - -**Message** - -```markdown -The provided clustering key order does not match the table schema. Required order: %s -``` - -### `DB-CORE-10157` - -**Message** - -```markdown -The provided partition key order does not match the table schema. Required order: %s -``` - ### `DB-CORE-10158` **Message** @@ -1311,100 +1055,68 @@ This TIMESTAMPTZ column value precision cannot be shorter than one millisecond. The underlying-storage data type %s is not supported as the ScalarDB %s data type: %s ``` -### `DB-CORE-10165` - -**Message** - -```markdown -Missing namespace or table: %s, %s -``` - -### `DB-CORE-10166` - -**Message** - -```markdown -Failed to retrieve table metadata. Details: %s -``` - -### `DB-CORE-10167` - -**Message** - -```markdown -Duplicate data mappings found for table '%s' in the control file -``` - -### `DB-CORE-10168` - -**Message** - -```markdown -No mapping found for column '%s' in table '%s' in the control file. Control file validation set at 'FULL'. All columns need to be mapped. -``` - -### `DB-CORE-10169` +### `DB-CORE-10188` **Message** ```markdown -The control file is missing data mappings +The replication feature is not enabled. To use this feature, you must enable it. Note that this feature is supported only in the ScalarDB Enterprise edition ``` -### `DB-CORE-10170` +### `DB-CORE-10205` **Message** ```markdown -The target column '%s' for source field '%s' could not be found in table '%s' +Some scanners were not closed. All scanners must be closed before committing the transaction ``` -### `DB-CORE-10171` +### `DB-CORE-10206` **Message** ```markdown -The required partition key '%s' is missing in the control file mapping for table '%s' +Some scanners were not closed. All scanners must be closed before preparing the transaction ``` -### `DB-CORE-10172` +### `DB-CORE-10211` **Message** ```markdown -The required clustering key '%s' is missing in the control file mapping for table '%s' +Mutations are not allowed in read-only transactions. Transaction ID: %s ``` -### `DB-CORE-10173` +### `DB-CORE-10212` **Message** ```markdown -Duplicated data mappings found for column '%s' in table '%s' +The storage does not support mutations across multiple records. Storage: %s; Mutations: %s ``` -### `DB-CORE-10174` +### `DB-CORE-10213` **Message** ```markdown -Missing required field or column mapping for clustering key %s +The storage does not support mutations across multiple tables. Storage: %s; Mutations: %s ``` -### `DB-CORE-10175` +### `DB-CORE-10214` **Message** ```markdown -Missing required field or column mapping for partition key %s +The storage does not support mutations across multiple namespaces. Storage: %s; Mutations: %s ``` -### `DB-CORE-10176` +### `DB-CORE-10215` **Message** ```markdown -Missing field or column mapping for %s +Mutations across multiple storages are not allowed. Mutations: %s ``` ## `DB-CORE-2xxxx` status codes @@ -1579,14 +1291,6 @@ The record exists, so the %s condition is not satisfied The condition on the column '%s' is not satisfied ``` -### `DB-CORE-20021` - -**Message** - -```markdown -Reading empty records might cause a write skew anomaly, so the transaction has been aborted for safety purposes -``` - ### `DB-CORE-20022` **Message** @@ -1619,6 +1323,14 @@ The %s condition of the %s operation is not satisfied. Targeting column(s): %s A transaction conflict occurred in the Insert operation ``` +### `DB-CORE-20026` + +**Message** + +```markdown +A conflict occurred when committing records +``` + ## `DB-CORE-3xxxx` status codes The following are status codes and messages for the internal error category. @@ -1852,7 +1564,7 @@ An error occurred in the selection. Details: %s **Message** ```markdown -Fetching the next result failed +Fetching the next result failed. Details: %s ``` ### `DB-CORE-30029` @@ -1999,20 +1711,44 @@ The Update operation failed. Details: %s Handling the before-preparation snapshot hook failed. Details: %s ``` -### `DB-CORE-30047` +### `DB-CORE-30054` + +**Message** + +```markdown +Getting the scanner failed. Details: %s +``` + +### `DB-CORE-30055` + +**Message** + +```markdown +Closing the scanner failed. Details: %s +``` + +### `DB-CORE-30056` + +**Message** + +```markdown +Getting the storage information failed. Namespace: %s +``` + +### `DB-CORE-30057` **Message** ```markdown -Something went wrong while trying to save the data. Details: %s +Recovering records failed. Details: %s ``` -### `DB-CORE-30048` +### `DB-CORE-30058` **Message** ```markdown -Something went wrong while scanning. Are you sure you are running in the correct transaction mode? Details: %s +Committing records failed ``` ## `DB-CORE-4xxxx` status codes diff --git a/docs/scalardb-data-loader-status-codes.mdx b/docs/scalardb-data-loader-status-codes.mdx new file mode 100644 index 00000000..67b0012d --- /dev/null +++ b/docs/scalardb-data-loader-status-codes.mdx @@ -0,0 +1,538 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Data Loader Error Codes + +This page provides a list of error codes in ScalarDB Data Loader. + +## Error code classes and descriptions + +| Class | Description | +|:-----------------------|:---------------------------------------| +| `DB-DATA-LOADER-1xxxx` | Errors for the user error category | +| `DB-DATA-LOADER-3xxxx` | Errors for the internal error category | + +## `DB-DATA-LOADER-1xxxx` status codes + +The following are status codes and messages for the user error category. + +### `DB-DATA-LOADER-10000` + +**Message** + +```markdown +Data chunk queue size must be greater than 0 +``` + +### `DB-DATA-LOADER-10001` + +**Message** + +```markdown +The directory '%s' does not have write permissions. Please ensure that the current user has write access to the directory +``` + +### `DB-DATA-LOADER-10002` + +**Message** + +```markdown +Failed to create the directory '%s'. Please check if you have sufficient permissions and if there are any file system restrictions. Details: %s +``` + +### `DB-DATA-LOADER-10003` + +**Message** + +```markdown +Directory path cannot be null or empty +``` + +### `DB-DATA-LOADER-10004` + +**Message** + +```markdown +No file extension was found in the provided file name %s +``` + +### `DB-DATA-LOADER-10005` + +**Message** + +```markdown +Invalid file extension: %s. Allowed extensions are: %s +``` + +### `DB-DATA-LOADER-10006` + +**Message** + +```markdown +Invalid key: Column %s does not exist in the table %s in namespace %s +``` + +### `DB-DATA-LOADER-10007` + +**Message** + +```markdown +Invalid base64 encoding for blob value '%s' for column %s in table %s in namespace %s +``` + +### `DB-DATA-LOADER-10008` + +**Message** + +```markdown +Invalid number '%s' specified for column %s in table %s in namespace %s +``` + +### `DB-DATA-LOADER-10009` + +**Message** + +```markdown +Method null argument not allowed +``` + +### `DB-DATA-LOADER-10010` + +**Message** + +```markdown +The provided clustering key %s was not found +``` + +### `DB-DATA-LOADER-10011` + +**Message** + +```markdown +The column '%s' was not found +``` + +### `DB-DATA-LOADER-10012` + +**Message** + +```markdown +The provided partition key is incomplete. Required key: %s +``` + +### `DB-DATA-LOADER-10013` + +**Message** + +```markdown +The provided clustering-key order does not match the table schema. Required order: %s +``` + +### `DB-DATA-LOADER-10014` + +**Message** + +```markdown +The provided partition-key order does not match the table schema. Required order: %s +``` + +### `DB-DATA-LOADER-10015` + +**Message** + +```markdown +Missing namespace or table: %s, %s +``` + +### `DB-DATA-LOADER-10016` + +**Message** + +```markdown +Failed to retrieve table metadata. Details: %s +``` + +### `DB-DATA-LOADER-10017` + +**Message** + +```markdown +Duplicate data mappings found for table '%s' in the control file +``` + +### `DB-DATA-LOADER-10018` + +**Message** + +```markdown +No mapping found for column '%s' in table '%s' in the control file. Control file validation set at 'FULL'. All columns need to be mapped +``` + +### `DB-DATA-LOADER-10019` + +**Message** + +```markdown +The control file is missing data mappings +``` + +### `DB-DATA-LOADER-10020` + +**Message** + +```markdown +The target column '%s' for source field '%s' could not be found in table '%s' +``` + +### `DB-DATA-LOADER-10021` + +**Message** + +```markdown +The required partition key '%s' is missing in the control file mapping for table '%s' +``` + +### `DB-DATA-LOADER-10022` + +**Message** + +```markdown +The required clustering key '%s' is missing in the control file mapping for table '%s' +``` + +### `DB-DATA-LOADER-10023` + +**Message** + +```markdown +Duplicated data mappings found for column '%s' in table '%s' +``` + +### `DB-DATA-LOADER-10024` + +**Message** + +```markdown +Missing required field or column mapping for clustering key %s +``` + +### `DB-DATA-LOADER-10025` + +**Message** + +```markdown +Missing required field or column mapping for partition key %s +``` + +### `DB-DATA-LOADER-10026` + +**Message** + +```markdown +Missing field or column mapping for %s +``` + +### `DB-DATA-LOADER-10027` + +**Message** + +```markdown +Something went wrong while converting the ScalarDB values to strings. The table metadata and Value datatype probably do not match. Details: %s +``` + +### `DB-DATA-LOADER-10028` + +**Message** + +```markdown +The provided file format is not supported : %s +``` + +### `DB-DATA-LOADER-10029` + +**Message** + +```markdown +Could not find the partition key +``` + +### `DB-DATA-LOADER-10030` + +**Message** + +```markdown +The source record needs to contain all fields if the UPSERT turns into an INSERT +``` + +### `DB-DATA-LOADER-10031` + +**Message** + +```markdown +Record already exists +``` + +### `DB-DATA-LOADER-10032` + +**Message** + +```markdown +Record was not found +``` + +### `DB-DATA-LOADER-10033` + +**Message** + +```markdown +Could not find the clustering key +``` + +### `DB-DATA-LOADER-10034` + +**Message** + +```markdown +No table metadata found +``` + +### `DB-DATA-LOADER-10035` + +**Message** + +```markdown +The data mapping source field '%s' for table '%s' is missing in the JSON data record +``` + +### `DB-DATA-LOADER-10036` + +**Message** + +```markdown +The CSV row: %s does not match header: %s +``` + +### `DB-DATA-LOADER-10037` + +**Message** + +```markdown +Expected JSON file content to be an array +``` + +### `DB-DATA-LOADER-10038` + +**Message** + +```markdown +Missing option: either the '--namespace' and '--table' options or the '--control-file' option must be specified +``` + +### `DB-DATA-LOADER-10039` + +**Message** + +```markdown +The file '%s' specified by the argument '%s' does not exist +``` + +### `DB-DATA-LOADER-10040` + +**Message** + +```markdown +Cannot write to the log directory: %s +``` + +### `DB-DATA-LOADER-10041` + +**Message** + +```markdown +Failed to create the log directory: %s +``` + +### `DB-DATA-LOADER-10042` + +**Message** + +```markdown +Failed to parse the control file: %s +``` + +### `DB-DATA-LOADER-10043` + +**Message** + +```markdown +No permission to create or write files in the directory: %s +``` + +### `DB-DATA-LOADER-10044` + +**Message** + +```markdown +Failed to create the directory: %s +``` + +### `DB-DATA-LOADER-10045` + +**Message** + +```markdown +Path exists but is not a directory: %s +``` + +### `DB-DATA-LOADER-10046` + +**Message** + +```markdown +File path must not be blank +``` + +### `DB-DATA-LOADER-10047` + +**Message** + +```markdown +File not found: %s +``` + +### `DB-DATA-LOADER-10048` + +**Message** + +```markdown +Invalid date time value '%s' specified for column %s in table %s in namespace %s +``` + +### `DB-DATA-LOADER-10049` + +**Message** + +```markdown +Key value cannot be null or empty +``` + +### `DB-DATA-LOADER-10050` + +**Message** + +```markdown +Invalid key-value format: %s +``` + +### `DB-DATA-LOADER-10051` + +**Message** + +```markdown +Value must not be null +``` + +### `DB-DATA-LOADER-10052` + +**Message** + +```markdown +Delimiter must not be null +``` + +### `DB-DATA-LOADER-10053` + +**Message** + +```markdown +Config file path must not be blank +``` + +### `DB-DATA-LOADER-10054` + +**Message** + +```markdown +Data chunk size must be greater than 0 +``` + +### `DB-DATA-LOADER-10055` + +**Message** + +```markdown +Transaction size must be greater than 0 +``` + +### `DB-DATA-LOADER-10056` + +**Message** + +```markdown +Number of max threads must be greater than 0 +``` + +## `DB-DATA-LOADER-3xxxx` status codes + +The following are status codes and messages for the internal error category. + +### `DB-DATA-LOADER-30000` + +**Message** + +```markdown +A problem occurred while trying to save the data. Details: %s +``` + +### `DB-DATA-LOADER-30001` + +**Message** + +```markdown +A problem occurred while scanning. Are you sure you are running in the correct transaction mode? Details: %s +``` + +### `DB-DATA-LOADER-30002` + +**Message** + +```markdown +Failed to read CSV file. Details: %s +``` + +### `DB-DATA-LOADER-30003` + +**Message** + +```markdown +Failed to CSV read header line. Details: %s +``` + +### `DB-DATA-LOADER-30004` + +**Message** + +```markdown +Data chunk processing was interrupted. Details: %s +``` + +### `DB-DATA-LOADER-30005` + +**Message** + +```markdown +Failed to read JSON file. Details: %s +``` + +### `DB-DATA-LOADER-30006` + +**Message** + +```markdown +Failed to read JSON Lines file. Details: %s +``` diff --git a/docs/scalardb-schema-loader-status-codes.mdx b/docs/scalardb-schema-loader-status-codes.mdx new file mode 100644 index 00000000..23c452e1 --- /dev/null +++ b/docs/scalardb-schema-loader-status-codes.mdx @@ -0,0 +1,165 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Schema Loader Error Codes + +This page provides a list of error codes in ScalarDB Schema Loader. + +## Error code classes and descriptions + +| Class | Description | +|:-------------------------|:---------------------------------------| +| `DB-SCHEMA-LOADER-1xxxx` | Errors for the user error category. | + +## `DB-SCHEMA-LOADER-1xxxx` status codes + +The following are status codes and messages for the user error category. + +### `DB-SCHEMA-LOADER-10000` + +**Message** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-SCHEMA-LOADER-10001` + +**Message** + +```markdown +The partition keys for the table %s.%s were modified, but altering partition keys is not supported +``` + +### `DB-SCHEMA-LOADER-10002` + +**Message** + +```markdown +The clustering keys for the table %s.%s were modified, but altering clustering keys is not supported +``` + +### `DB-SCHEMA-LOADER-10003` + +**Message** + +```markdown +The clustering order of the table %s.%s were modified, but altering the clustering order is not supported +``` + +### `DB-SCHEMA-LOADER-10004` + +**Message** + +```markdown +The column %s in the table %s.%s has been deleted. Column deletion is not supported when altering a table +``` + +### `DB-SCHEMA-LOADER-10005` + +**Message** + +```markdown +The data type for the column %s in the table %s.%s was modified, but altering data types is not supported +``` + +### `DB-SCHEMA-LOADER-10006` + +**Message** + +```markdown +Specifying the '--schema-file' option is required when using the '--repair-all' option +``` + +### `DB-SCHEMA-LOADER-10007` + +**Message** + +```markdown +Specifying the '--schema-file' option is required when using the '--alter' option +``` + +### `DB-SCHEMA-LOADER-10008` + +**Message** + +```markdown +Specifying the '--schema-file' option is required when using the '--import' option +``` + +### `DB-SCHEMA-LOADER-10009` + +**Message** + +```markdown +Specifying the '--coordinator' option with the '--import' option is not allowed. Create Coordinator tables separately +``` + +### `DB-SCHEMA-LOADER-10010` + +**Message** + +```markdown +Reading the configuration file failed. File: %s +``` + +### `DB-SCHEMA-LOADER-10011` + +**Message** + +```markdown +Reading the schema file failed. File: %s +``` + +### `DB-SCHEMA-LOADER-10012` + +**Message** + +```markdown +Parsing the schema JSON failed. Details: %s +``` + +### `DB-SCHEMA-LOADER-10013` + +**Message** + +```markdown +The table name must contain the namespace and the table. Table: %s +``` + +### `DB-SCHEMA-LOADER-10014` + +**Message** + +```markdown +The partition key must be specified. Table: %s +``` + +### `DB-SCHEMA-LOADER-10015` + +**Message** + +```markdown +Invalid clustering-key format. The clustering key must be in the format of 'column_name' or 'column_name ASC/DESC'. Table: %s; Clustering key: %s +``` + +### `DB-SCHEMA-LOADER-10016` + +**Message** + +```markdown +Columns must be specified. Table: %s +``` + +### `DB-SCHEMA-LOADER-10017` + +**Message** + +```markdown +Invalid column type. Table: %s; Column: %s; Type: %s +``` diff --git a/docs/scalardb-sql/grammar.mdx b/docs/scalardb-sql/grammar.mdx index c7d5045f..b0a19b4d 100644 --- a/docs/scalardb-sql/grammar.mdx +++ b/docs/scalardb-sql/grammar.mdx @@ -569,11 +569,11 @@ Examples of building statement objects for `ALTER TABLE` are as follows: ```java // Add a new column "new_col" to "ns.tbl" -AlterTableAddColumnStatement statement = +AlterTableAddColumnStatement statement1 = StatementBuilder.alterTable("ns", "tbl").addColumn("new_col", DataType.INT).build(); // Add a new encrypted column "new_col" to "ns.tbl" -AlterTableAddColumnStatement statement = +AlterTableAddColumnStatement statement2 = StatementBuilder.alterTable("ns", "tbl").addColumn("new_col", DataType.TEXT, true).build(); ``` @@ -2039,16 +2039,26 @@ This command returns the following column: #### Grammar ```sql -BEGIN +BEGIN [READ ONLY | READ WRITE] ``` +- If you specify `READ ONLY`, the transaction will be started in read-only mode. +- If you specify `READ WRITE`, the transaction will be started in read-write mode. +- If you omit the `READ ONLY` or `READ WRITE` option, the transaction will be started as a read-write transaction by default. + #### Examples An example of building statement objects for `BEGIN` is as follows: ```java -// Begin a transaction -BeginStatement statement = StatementBuilder.begin().build(); +// Begin a transaction. +BeginStatement statement1 = StatementBuilder.begin().build(); + +// Begin a transaction in read-only mode. +BeginStatement statement2 = StatementBuilder.begin().readOnly().build(); + +// Begin a transaction in read-write mode. +BeginStatement statement3 = StatementBuilder.begin().readWrite().build(); ``` ### START TRANSACTION @@ -2062,16 +2072,26 @@ This command returns the following column: #### Grammar ```sql -START TRANSACTION +START TRANSACTION [READ ONLY | READ WRITE] ``` +- If you specify `READ ONLY`, the transaction will be started in read-only mode. +- If you specify `READ WRITE`, the transaction will be started in read-write mode. +- If you omit the `READ ONLY` or `READ WRITE` option, the transaction will be started as a read-write transaction by default. + #### Examples An example of building statement objects for `START TRANSACTION` is as follows: ```java // Start a transaction. -StartTransactionStatement statement = StatementBuilder.startTransaction().build(); +StartTransactionStatement statement1 = StatementBuilder.startTransaction().build(); + +// Start a transaction in read-only mode. +StartTransactionStatement statement2 = StatementBuilder.startTransaction().readOnly().build(); + +// Start a transaction in read-write mode. +StartTransactionStatement statement3 = StatementBuilder.startTransaction().readWrite().build(); ``` ### JOIN diff --git a/docs/scalardb-sql/jdbc-guide.mdx b/docs/scalardb-sql/jdbc-guide.mdx index ef8180e2..4e285c32 100644 --- a/docs/scalardb-sql/jdbc-guide.mdx +++ b/docs/scalardb-sql/jdbc-guide.mdx @@ -71,10 +71,11 @@ Please see [ScalarDB Cluster SQL client configurations](../scalardb-cluster/deve In addition, the ScalarDB JDBC specific configurations are as follows: -| name | description | default | -|---------------------------------------------------------------------|------------------------------------------------------------------------------|---------| -| scalar.db.sql.jdbc.default_auto_commit | The default connection's auto-commit mode. | true | -| scalar.db.sql.jdbc.sql_session_factory_cache.expiration_time_millis | The expiration time in milliseconds for the cache of SQL session factories. | 10000 | +| name | description | default | +|---------------------------------------------------------------------|-----------------------------------------------------------------------------|---------| +| scalar.db.sql.jdbc.default_auto_commit | The default auto-commit mode for connections. | true | +| scalar.db.sql.jdbc.default_read_only | The default read-only state for connections. | false | +| scalar.db.sql.jdbc.sql_session_factory_cache.expiration_time_millis | The expiration time in milliseconds for the cache of SQL session factories. | 10000 | ## Data type mapping between ScalarDB and JDBC @@ -220,4 +221,4 @@ Please see also [ScalarDB SQL API Guide](sql-api-guide.mdx) for more details on - [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) - [ScalarDB SQL API Guide](sql-api-guide.mdx) -- [Javadoc for ScalarDB JDBC](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-jdbc/3.15.4/index.html) +- [Javadoc for ScalarDB JDBC](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-jdbc/3.16.0/index.html) diff --git a/docs/scalardb-sql/scalardb-sql-status-codes.mdx b/docs/scalardb-sql/scalardb-sql-status-codes.mdx index 8dbe6bf5..62cfd0f6 100644 --- a/docs/scalardb-sql/scalardb-sql-status-codes.mdx +++ b/docs/scalardb-sql/scalardb-sql-status-codes.mdx @@ -641,3 +641,27 @@ Unmatched column type. The type of the column %s should be %s, but a TIMESTAMPTZ ```markdown The policy %s does not exist ``` + +### `DB-SQL-10078` + +**Message** + +```markdown +Beginning a transaction in read-only mode is not supported in two-phase commit transaction mode +``` + +### `DB-SQL-10079` + +**Message** + +```markdown +Starting a transaction in read-only mode is not supported in two-phase commit transaction mode +``` + +### `DB-SQL-10080` + +**Message** + +```markdown +Cannot change read-only mode while a transaction is in progress +``` diff --git a/docs/scalardb-sql/spring-data-guide.mdx b/docs/scalardb-sql/spring-data-guide.mdx index 970251c8..040e412a 100644 --- a/docs/scalardb-sql/spring-data-guide.mdx +++ b/docs/scalardb-sql/spring-data-guide.mdx @@ -820,4 +820,4 @@ In order to use Spring Data JDBC for ScalarDB, the following features are implem - [Spring Data JDBC - Reference Documentation](https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/) - [ScalarDB JDBC Guide](jdbc-guide.mdx) -- [Javadoc for Spring Data JDBC for ScalarDB](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-spring-data/3.15.4/index.html) +- [Javadoc for Spring Data JDBC for ScalarDB](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-spring-data/3.16.0/index.html) diff --git a/docs/scalardb-sql/sql-api-guide.mdx b/docs/scalardb-sql/sql-api-guide.mdx index d2203aad..9301191a 100644 --- a/docs/scalardb-sql/sql-api-guide.mdx +++ b/docs/scalardb-sql/sql-api-guide.mdx @@ -374,4 +374,4 @@ For more details, see the + | Db2 | ScalarDB | Notes | + |-----------------------|----------------------------------------|----------------------------| + | BIGINT | BIGINT | See warning [1](#1) below. | + | BINARY | BLOB | | + | BLOB | BLOB | | + | BOOLEAN | BOOLEAN | | + | CHAR | TEXT | | + | CHAR FOR BIT DATA | BLOB | | + | CLOB | TEXT | | + | DATE | DATE | | + | DOUBLE | DOUBLE | See warning [2](#2) below. | + | FLOAT(p), with p ≤ 24 | FLOAT | See warning [2](#2) below. | + | FLOAT(p), with p ≥ 25 | DOUBLE | See warning [2](#2) below. | + | GRAPHIC | TEXT | | + | INT | INT | | + | NCHAR | TEXT | | + | NCLOB | TEXT | | + | NVARCHAR | TEXT | | + | REAL | FLOAT | See warning [2](#2) below. | + | SMALLINT | INT | | + | TIME | TIME | | + | TIMESTAMP | TIMESTAMP (default), TIME, TIMESTAMPTZ | See warning [6](#6) below. | + | VARBINARY | BLOB | | + | VARCHAR | TEXT | | + | VARCHAR FOR BIT DATA | BLOB | | + | VARGRAPHIC | TEXT | | + + Data types not listed above are not supported. The following are some common data types that are not supported: + + - decimal + - decfloat + - xml + :::warning diff --git a/docs/schema-loader.mdx b/docs/schema-loader.mdx index 6cf21a18..5270bb5e 100644 --- a/docs/schema-loader.mdx +++ b/docs/schema-loader.mdx @@ -38,7 +38,7 @@ Select your preferred method to set up Schema Loader, and follow the instruction You can pull the Docker image from the [Scalar container registry](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-schema-loader) by running the following command, replacing the contents in the angle brackets as described: ```console - docker run --rm -v :/scalardb.properties -v :/schema.json ghcr.io/scalar-labs/scalardb-schema-loader: --config /scalardb.properties --schema-file /schema.json + docker run --rm -v :/scalardb.properties -v :/schema.json ghcr.io/scalar-labs/scalardb-schema-loader: --config /scalardb.properties --schema-file /schema.json ``` :::note @@ -532,19 +532,19 @@ Auto-scaling for Cosmos DB for NoSQL is enabled only when this option is set to The following table shows the supported data types in ScalarDB and their mapping to the data types of other databases. -| ScalarDB | Cassandra | Cosmos DB for NoSQL | DynamoDB | MySQL/MariaDB | PostgreSQL/YugabyteDB | Oracle | SQL Server | SQLite | -|-------------|----------------------|---------------------|----------|---------------|--------------------------|--------------------------|-----------------|---------| -| BOOLEAN | boolean | boolean (JSON) | BOOL | boolean | boolean | number(1) | bit | boolean | -| INT | int | number (JSON) | N | int | int | number(10) | int | int | -| BIGINT | bigint | number (JSON) | N | bigint | bigint | number(16) | bigint | bigint | -| FLOAT | float | number (JSON) | N | real | real | binary_float | float(24) | float | -| DOUBLE | double | number (JSON) | N | double | double precision | binary_double | float | double | -| TEXT | text | string (JSON) | S | longtext | text | varchar2(4000) | varchar(8000) | text | -| BLOB | blob | string (JSON) | B | longblob | bytea | RAW(2000) | varbinary(8000) | blob | -| DATE | date | number (JSON) | N | date | date | date | date | int | -| TIME | time | number (JSON) | N | time | time | timestamp | time | bigint | -| TIMESTAMP | Unsupported | number (JSON) | N | datetime | timestamp | timestamp | datetime2 | bigint | -| TIMESTAMPTZ | timestamp | number (JSON) | N | datetime | timestamp with time zone | timestamp with time zone | datetimeoffset | bigint | +| ScalarDB | Cassandra | Cosmos DB for NoSQL | Db2 | DynamoDB | MySQL/MariaDB | PostgreSQL/YugabyteDB | Oracle | SQL Server | SQLite | +|-------------|----------------------|---------------------|------------------|----------|---------------|--------------------------|--------------------------|-----------------|---------| +| BOOLEAN | boolean | boolean (JSON) | BOOLEAN | BOOL | boolean | boolean | number(1) | bit | boolean | +| INT | int | number (JSON) | INT | N | int | int | number(10) | int | int | +| BIGINT | bigint | number (JSON) | BIGINT | N | bigint | bigint | number(16) | bigint | bigint | +| FLOAT | float | number (JSON) | REAL | N | real | real | binary_float | float(24) | float | +| DOUBLE | double | number (JSON) | DOUBLE | N | double | double precision | binary_double | float | double | +| TEXT | text | string (JSON) | VARCHAR(32672) | S | longtext | text | varchar2(4000) | varchar(8000) | text | +| BLOB | blob | string (JSON) | VARBINARY(32672) | B | longblob | bytea | RAW(2000) | varbinary(8000) | blob | +| DATE | date | number (JSON) | DATE | N | date | date | date | date | int | +| TIME | time | number (JSON) | TIMESTAMP | N | time | time | timestamp | time | bigint | +| TIMESTAMP | Unsupported | number (JSON) | TIMESTAMP | N | datetime | timestamp | timestamp | datetime2 | bigint | +| TIMESTAMPTZ | timestamp | number (JSON) | TIMESTAMP | N | datetime | timestamp with time zone | timestamp with time zone | datetimeoffset | bigint | :::note @@ -554,10 +554,10 @@ TIMESTAMP represents a date-time without time zone information, while TIMESTAMPT However, the following data types in JDBC databases are converted differently when they are used as a primary key or a secondary index key. This is due to the limitations of RDB data types. For MySQL and Oracle, you can change the column size (minimum 64 bytes) as long as it meets the limitation of the total size of key columns. For details, see [Underlying storage or database configurations](configurations.mdx#underlying-storage-or-database-configurations). -| ScalarDB | MySQL/MariaDB | PostgreSQL/YugabyteDB | Oracle | -|----------|----------------|-----------------------|---------------| -| TEXT | VARCHAR(128) | VARCHAR(10485760) | VARCHAR2(128) | -| BLOB | VARBINARY(128) | | RAW(128) | +| ScalarDB | MySQL/MariaDB | PostgreSQL/YugabyteDB | Oracle | Db2 | +|----------|----------------|-----------------------|---------------|----------------| +| TEXT | VARCHAR(128) | VARCHAR(10485760) | VARCHAR2(128) | VARCHAR(128) | +| BLOB | VARBINARY(128) | | RAW(128) | VARBINARY(128) | The following data types have a value range and precision regardless of the underlying database. diff --git a/docusaurus.config.js b/docusaurus.config.js index aa7825d4..2b7a1b07 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -75,9 +75,15 @@ const config = { }, */ current: { // When a new version is released and this is no longer the current version, change this to the version number and then delete this comment. - label: '3.15', + label: '3.16', path: 'latest', // When a new version is released and this is no longer the current version, change this to the version number and then delete this comment. banner: 'none', + className: '3.16.0', + }, + "3.15": { // When a new version is released and this is no longer the current version, change this to the version number and then delete this comment. + label: '3.15', + path: '3.15', // When a new version is released and this is no longer the current version, change this to the version number and then delete this comment. + banner: 'none', className: '3.15.4', }, "3.14": { // When a new version is released and this is no longer the current version, change this to the version number and then delete this comment. @@ -163,7 +169,7 @@ const config = { // The following versions have Japanese docs, so the language dropdown should be displayed only when visitors are reading these versions of docs. customFields: { - allowedLanguageDropdownVersions: ["current", "latest", "3.14", "3.13"], + allowedLanguageDropdownVersions: ["current", "latest", "3.15", "3.14", "3.13"], }, plugins: [ @@ -530,14 +536,15 @@ const config = { darkTheme: prismThemes.dracula, additionalLanguages: ['csharp', 'docker', 'gradle', 'java', 'json', 'log', 'properties', 'python', 'scala', 'shell-session', 'sql', 'toml'], }, - // announcementBar: { - // id: 'new_version', - // content: - // // 'Announcing the release of ScalarDB X.X!🚀 For details on what\'s included in this new version, see the release notes.', - // backgroundColor: '#2673BB', - // textColor: '#FFFFFF', - // isCloseable: false, - // }, + announcementBar: { + id: 'new_version', + content: + 'Announcing the release of ScalarDB 3.16!🚀 For details on what\'s included in this new version, see the release notes', + // 'Announcing the release of ScalarDB X.X!🚀 For details on what\'s included in this new version, see the release notes', + backgroundColor: '#2673BB', + textColor: '#FFFFFF', + isCloseable: false, + }, zoom: { selector: '.markdown :not(em) > img', background: { diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current.json b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current.json index c38fe261..58d3daca 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current.json +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current.json @@ -1,6 +1,6 @@ { "version.label": { - "message": "3.15", + "message": "3.16", "description": "The label for version current" } } diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/api-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/api-guide.mdx index bf8463ea..bf31fd5a 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/api-guide.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/api-guide.mdx @@ -410,6 +410,48 @@ DistributedTransaction transaction = transactionManager.start("" ::: +##### 読み取り専用モードでトランザクションを開始またはスタートする + +読み取り専用モードでトランザクションを開始またはスタートすることもできます。この場合、トランザクションでは書き込み操作は許可されず、読み取り操作に最適化されます。 + +:::note + +パフォーマンスを向上させ、リソース使用量を削減するために、読み取り専用操作には読み取り専用トランザクションを使用することを強く推奨します。 + +::: + +次のように読み取り専用モードでトランザクションを開始またはスタートできます。 + +```java +// Begin a transaction in read-only mode. +DistributedTransaction transaction = transactionManager.beginReadOnly(); +``` + +```java +// Start a transaction in read-only mode. +DistributedTransaction transaction = transactionManager.startReadOnly(); +``` + +または、次のようにトランザクション ID を指定して、`beginReadOnly` メソッドと `startReadOnly` メソッドを使用することもできます。 + +```java +// Begin a transaction in read-only mode by specifying a transaction ID. +DistributedTransaction transaction = transactionManager.beginReadOnly(""); +``` + +```java +// Start a transaction in read-only mode by specifying a transaction ID. +DistributedTransaction transaction = transactionManager.startReadOnly(""); +``` + +:::note + +トランザクション ID を指定する方法は、外部システムを ScalarDB にリンクしたい場合に利用できます。それ以外の場合は、`beginReadOnly()` メソッドまたは `startReadOnly()` メソッドを使用する必要があります。 + +トランザクション ID を指定する場合は、ScalarDB の正確性はトランザクション ID の一意性に依存するため、システム全体で一意の ID (UUID v4など) を指定してください。 + +::: + #### トランザクションに参加する トランザクションに参加することは、トランザクションが複数のクライアントリクエストにまたがるステートフルアプリケーションで特に便利です。このようなシナリオでは、アプリケーションは最初のクライアントリクエスト中にトランザクションを開始できます。その後、後続のクライアントリクエストで、アプリケーションは `join()` メソッドを使用して進行中のトランザクションに参加できます。 @@ -492,7 +534,7 @@ Key key3 = Key.of("col1", 1, "col2", 100L, "col3", 1.3d, "col4", "value"); Key key4 = Key.of("col1", 1, "col2", 100L, "col3", 1.3d, "col4", "value", "col5", false); ``` -5列を超えるキーの場合は、ビルダーを使用して次のようにキーを構築できます。 +5列を超えるキーの場合、ビルダーを使用して次のようにキーを構築できます。 ```java // For a key that consists of more than five columns. diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/index.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/index.mdx index 31a0f4cf..79ffc786 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/index.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/index.mdx @@ -9,6 +9,6 @@ hide_table_of_contents: true title: "" --- -import CategoryGrid from '/src/components/Cards/ja-jp/3.15'; +import CategoryGrid from '/src/components/Cards/ja-jp/3.16'; diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/releases/release-notes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/releases/release-notes.mdx index 7e376041..1e87bef8 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/releases/release-notes.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/releases/release-notes.mdx @@ -6,84 +6,59 @@ tags: displayed_sidebar: docsJapanese --- -# ScalarDB 3.15 リリースノート +# ScalarDB 3.16 リリースノート import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; -このページには、ScalarDB 3.15 のリリースノートのリストが含まれています。 +このページには、ScalarDB 3.16 のリリースノートのリストが含まれています。 -## v3.15.4 +## v3.16.0 -**発売日:** 2025年06月21日 +**発売日:** 2025年06月20日 ### まとめ -このリリースには脆弱性とバグの修正が含まれています。 +このリリースには、多くの機能強化、改善、バグ修正、およびパフォーマンスの最適化が含まれています。 ### Community edition -#### バグの修正 - -- カラム値変換におけるDateTimeParseExceptionの例外処理を追加しました。([#2662](https://github.com/scalar-labs/scalardb/pull/2662)) -- セキュリティ問題を修正するためにPostgreSQLドライバーをアップグレードしました。[CVE-2025-49146](https://github.com/advisories/GHSA-hq9p-pm7w-8p54 "CVE-2025-49146") ([#2772](https://github.com/scalar-labs/scalardb/pull/2772)) -- `jdbc`ストレージを使用し、対象テーブルが存在しないためにスキャン操作が失敗した場合の潜在的な接続リークを修正しました。([#2766](https://github.com/scalar-labs/scalardb/pull/2766)) - -### Enterprise edition - -#### バグの修正 - -##### ScalarDB Cluster - -- コーディネーターのグループコミット機能が有効になっている場合のメモリリーク問題を修正しました。 -- セキュリティ問題を修正するためにOpenSearch Javaクライアントをアップグレードしました。[CVE-2025-27820](https://github.com/advisories/GHSA-73m2-qfq3-56cx "CVE-2025-27820") - -## v3.15.3 - -**発売日:** 2025年05月15日 - -### まとめ - -このリリースには、脆弱性とバグの修正が含まれており、Omnistrate サービス上で ScalarDB Cluster を実行するためのサポートが追加されています。 - -### Community edition - -#### バグの修正 - -- 名前空間プレフィックス設定 `scalar.db.dynamo.namespace.prefix` を使用して DynamoDB ストレージを使用する場合の `DistributedStorageAdmin.getNamespaceNames()` API の問題を修正しました。このメソッドによって返される名前空間名に誤ってプレフィックスが含まれていました。([#2641](https://github.com/scalar-labs/scalardb/pull/2641)) - -### Enterprise edition - -#### 改善点 - -##### ScalarDB Cluster - -- Omnistrate サービスのサポートを追加しました。これにより、Omnistrate サービス上で ScalarDB Cluster を実行できるようになりました。 - -#### バグの修正 - -##### ScalarDB Cluster - -- セキュリティの問題を修正するために `grpc_health_probe` をアップグレードしました。[CVE-2025-22869](https://github.com/advisories/GHSA-hcg3-q754-cr77) - -## v3.15.2 - -**発売日:** 2025年03月24日 - -### まとめ - -このリリースには、いくつかの改善とバグ修正が含まれています。 +#### 機能強化 -### Community edition +- IBM Db2 LUV 11 および 12 のサポートを追加しました。([#2598](https://github.com/scalar-labs/scalardb/pull/2598)) +- 結果を反復的に取得するためのトランザクション抽象にスキャナー API を追加しました。([#2729](https://github.com/scalar-labs/scalardb/pull/2729)) +- ストレージアダプターにおけるスキャンフェッチサイズのサポートを追加しました。`scalar.db.scan_fetch_size` プロパティを設定することで、ストレージ層でスキャン API によってフェッチされるレコード数を制御できます。([#2731](https://github.com/scalar-labs/scalardb/pull/2731)) +- Schema Loader に `replication-tables` オプションを追加しました。([#2747](https://github.com/scalar-labs/scalardb/pull/2747)) +- 読み取り専用モードでトランザクションを開始するサポートを追加しました。([#2749](https://github.com/scalar-labs/scalardb/pull/2749)) +- Javadoc および errorprone に関する警告を修正しました。([#2614](https://github.com/scalar-labs/scalardb/pull/2614)) +- ストレージに関するメタデータを提供する `StorageInfo` を導入しました。`DistributedStorageAdmin.getStorageInfo()` メソッドを介して `StorageInfo` インスタンスを取得できます。([#2756](https://github.com/scalar-labs/scalardb/pull/2756)) +- ScalarDB Data Loader CLI の Docker サポートを追加し、データロード機能のコンテナ化されたデプロイメントを可能にしました。([#2758](https://github.com/scalar-labs/scalardb/pull/2758)) +- Data Loader CLI ビルドのCIワークフローを追加しました。([#2761](https://github.com/scalar-labs/scalardb/pull/2761)) +- より良いパフォーマンスを提供する `READ_COMMITTED` 分離レベルを追加しました。特に低競合のワークロードに対して効果的です。([#2803](https://github.com/scalar-labs/scalardb/pull/2803)) +- Consensus Commit における1フェーズコミット最適化のサポートを追加し、すべての変更が原子的にコミットできる場合にプレパレコードとコミットステートをスキップすることでパフォーマンスを大幅に向上させます。この最適化は `scalar.db.consensus_commit.one_phase_commit.enabled` プロパティで有効にできます。([#2811](https://github.com/scalar-labs/scalardb/pull/2811)) #### 改善点 -- ScalarDB BIGINT データ型が Oracle の NUMBER(16) にマッピングされるようになりました。([#2566](https://github.com/scalar-labs/scalardb/pull/2566)) +- ScalarDB BIGINT データ型が Oracle の `NUMBER(16)` にマッピングされるように変更しました。([#2566](https://github.com/scalar-labs/scalardb/pull/2566)) +- Consensus Commit から `EXTRA_WRITE` 戦略を削除しました。この変更により、Consensus Commit を使用する際に `EXTRA_WRITE` 戦略が指定された場合、代わりに `EXTRA_READ` 戦略が使用されます。([#2597](https://github.com/scalar-labs/scalardb/pull/2597)) +- Consensus Commit において、削除後に同じレコードに対してスキャン操作を不許可にするように変更し、一貫性のない動作を防ぎ、書き込み後のスキャンに関する既存の制限と整合させました。([#2610](https://github.com/scalar-labs/scalardb/pull/2610)) +- Consensus Commit において、読み取り専用トランザクションのコミットステートを省略するように変更し、パフォーマンスを向上させました。この動作はデフォルトで有効ですが、`scalar.db.consensus_commit.coordinator.write_omission_on_read_only.enabled` プロパティを `false` に設定することで無効にできます。([#2765](https://github.com/scalar-labs/scalardb/pull/2765)) +- Consensus Commit において、レコードのコミットまたはロールバック後に前の画像を削除するようにコードを更新し、ディスク使用量を削減しました。([#2787](https://github.com/scalar-labs/scalardb/pull/2787)) +- Consensus Commit における読み取りアルゴリズムを改善し、不必要な再試行を減少させました。([#2798](https://github.com/scalar-labs/scalardb/pull/2798)) #### バグの修正 - セキュリティ問題を修正するために Netty ライブラリをアップグレードしました。 [CVE-2025-24970](https://github.com/advisories/GHSA-4g8c-wm8x-jfhw "CVE-2025-24970") ([#2552](https://github.com/scalar-labs/scalardb/pull/2552)) +- スキャンに制限をかけた後にトランザクションが常に中断される `SERIALIZABLE` 分離レベルにおける Consensus Commit のバグを修正しました。([#2621](https://github.com/scalar-labs/scalardb/pull/2621)) +- DynamoDB ストレージを使用している際に、名前空間プレフィックス設定 `scalar.db.dynamo.namespace.prefix` を用いた場合の `DistributedStorageAdmin.getNamespaceNames()` API の問題を修正しました。このメソッドによって返される名前空間名に誤ってプレフィックスが含まれていました。([#2641](https://github.com/scalar-labs/scalardb/pull/2641)) +- 列値変換時の `DateTimeParseException` に対する例外処理を追加しました。([#2662](https://github.com/scalar-labs/scalardb/pull/2662)) +- `SERIALIZABLE` トランザクション内での二次インデックスを使用した `Get` 操作が、検証中に `Scan` 操作に変換されることにより `IllegalArgumentException` をスローする問題を修正しました。([#2683](https://github.com/scalar-labs/scalardb/pull/2683)) +- トランザクション内で二次インデックスの `Get` 操作によって取得されたレコードを更新する際に、不必要な暗黙のプレリードが発生するバグを修正しました。([#2700](https://github.com/scalar-labs/scalardb/pull/2700)) +- データローダーコアのマイナーなバグと問題を修正しました。([#2752](https://github.com/scalar-labs/scalardb/pull/2752)) +- Consensus Commit において、結合を伴う `Get` または `Scan` を実行する際にレコードが見逃されるバグを修正しました。([#2786](https://github.com/scalar-labs/scalardb/pull/2786)) +- Consensus Commit において、ストレージから同じレコードを複数回読み取ることが、更新の喪失などの異常を引き起こす可能性がある問題を修正しました。この問題を解決するために、読み取りセットは繰り返し読み取り時に更新されなくなりました。([#2797](https://github.com/scalar-labs/scalardb/pull/2797)) +- `jdbc` ストレージを使用している際に、ターゲットテーブルが存在しないために `Scan` 操作が失敗した場合の潜在的な接続リークを修正しました。([#2766](https://github.com/scalar-labs/scalardb/pull/2766)) ### Enterprise edition @@ -91,71 +66,29 @@ import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; ##### ScalarDB Cluster -- ScalarDB Cluster のトランザクション機能を有効または無効にする設定オプション (`scalar.db.transaction.enabled`) を追加しました。デフォルト値は `true` です。 - -#### バグ修正 - -##### ScalarDB Cluster - -- SQL インターフェースで認証を使用する場合のメタデータキャッシュの動作に関連するバグを修正しました。 -- 埋め込み機能の設定を修正しました。 -- スーパーユーザーが存在しないユーザーに対して ABAC 管理操作を実行できるバグを修正しました。 -- 空の ABAC システムテーブルを削除するときにテーブルが見つからないというエラーが発生するバグを修正しました。 +- ScalarDB Cluster におけるトランザクション機能の有効または無効を設定するための構成オプション(`scalar.db.transaction.enabled`)を追加しました。デフォルト値は `true` です。 +- ScalarDB Cluster におけるトランザクション抽象にスキャナー API のサポートを追加し、結果を反復的に取得できるようにしました。 +- ScalarDB Cluster において、読み取り専用モードでトランザクションを開始するサポートを追加しました。 +- ScalarDB Cluster において、SQL を使用して読み取り専用モードでトランザクションを開始するサポートを追加しました。 +- ScalarDB Cluster において、セミ同期レプリケーション機能を追加しました。 -## v3.15.1 - -**発売日:** 2025年02月20日 - -### まとめ - -このリリースには、多数の機能強化、改善、バグ修正が含まれています。[3.15.0 リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.0)は破棄され、これが 3.15 の最初の公式リリースとなります。 - -### Community edition - -#### 機能強化 +##### ScalarDB SQL -- 操作属性が導入され、操作に追加のキー値情報を含める機能が提供されました。([#2333](https://github.com/scalar-labs/scalardb/pull/2333)) -- 新しい時間関連のデータ型 DATE、TIME、TIMESTAMP、および TIMESTAMPTZ が追加されました。 ([#2468](https://github.com/scalar-labs/scalardb/pull/2468) [#2491](https://github.com/scalar-labs/scalardb/pull/2491)) +- ScalarDB SQL において、読み取り専用モードでトランザクションを開始するサポートを追加しました。 #### 改善点 -- ScalarDB は、MySQL 8.4、8.0、PostgreSQL 17、16、15、14、13、Amazon Aurora PostgreSQL 16、15、14、13 をサポートするようになりました。 Amazon Aurora MySQL 3、および 2。([#2302](https://github.com/scalar-labs/scalardb/pull/2302)) -- `jdbc:mariadb` で始まる接続 URL には MariaDB Connector/J JDBC ドライバーを使用します。([#2391](https://github.com/scalar-labs/scalardb/pull/2391)) -- Cassandra および Cosmos DB のステートメントハンドラーで不要なログ記録を削除しました。([#2469](https://github.com/scalar-labs/scalardb/pull/2469)) - -#### バグの修正 - -- Cosmos DB アダプターの主キー列の検証を追加しました。検証により、主キー列のテキスト値に不正な文字 (`:`、`/`、`\`、`#`、および `?`) が含まれていないことが保証されます。 ([#2292](https://github.com/scalar-labs/scalardb/pull/2292)) -- Consensus Commit のトランザクションで同じレコードに対して複数のミューテーションが発生する動作を修正しました。([#2340](https://github.com/scalar-labs/scalardb/pull/2340)) -- Cosmos アダプターで存在しないレコードを削除するときの動作を修正しました。([#2341](https://github.com/scalar-labs/scalardb/pull/2341)) -- GetBuilder と ScanBuilder のバグを修正しました。([#2352](https://github.com/scalar-labs/scalardb/pull/2352)) - -### Enterprise edition - -#### 機能強化 - ##### ScalarDB Cluster -- [#2333](https://github.com/scalar-labs/scalardb/pull/2333) で導入された操作属性のサポートを ScalarDB Cluster に追加しました。 -- 属性ベースのアクセス制御機能を追加しました。 -- [#2468](https://github.com/scalar-labs/scalardb/pull/2468) で導入された時間関連の型のサポートを ScalarDB Cluster に追加しました。 -- [scalar-labs/scalardb-sql#708](https://github.com/scalar-labs/scalardb-sql/pull/708) で導入された ABAC のメタデータ API のサポートを追加しました。 -- LangChain4j を統合することで、ScalarDB Cluster にベクトル検索機能を追加しました。 - -##### ScalarDB SQL - -- DML に操作属性のサポートを追加しました。また、ABAC の読み取りタグと書き込みタグを DMS にサポートしました。 -- 時間関連の型である DATE、TIME、TIMESTAMP、および TIMESTAMPTZ をサポートします。 -- ABAC のメタデータ API を追加しました。 -- ABAC の SQL ステートメントを追加しました。 +- Omnistrate サービスのサポートを追加しました。これにより、ScalarDB Cluster を Omnistrate サービス内で実行できるようになりました。 +- ScalarDB Cluster に対してポーズコマンドが発行された際に、読み取り専用トランザクションが一時停止しないように変更しました。 #### バグの修正 ##### ScalarDB Cluster -- セキュリティ問題を修正するために `grpc_health_probe` をアップグレードしました。 [CVE-2024-45337](https://github.com/advisories/GHSA-v778-237x-gjrc "CVE-2024-45337") [CVE-2024-45338](https://github.com/advisories/GHSA-w32m-9786-jp63 "CVE-2024-45338") - -##### ScalarDB SQL - -- [Spring Data JDBC For ScalarDB] `existsById()` API が動作しないバグを修正しました -- SQL ステートメントパーサーが INT 型および BIGINT 型の列の負の数値リテラルを拒否する問題を修正しました。 +- SQL インターフェースで認証を使用する際のメタデータキャッシュの動作に関するバグを修正しました。 +- 埋め込み機能の設定を修正しました。 +- スーパーユーザーが存在しないユーザーに対して ABAC 管理操作を実行できるバグを修正しました。 +- 空の ABAC システムテーブルを削除する際にテーブルが見つからないエラーが発生するバグを修正しました。 +- コーディネーターグループコミット機能が有効なときのメモリリークの問題を修正しました。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/releases/release-support-policy.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/releases/release-support-policy.mdx index 70f86183..141db014 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/releases/release-support-policy.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/releases/release-support-policy.mdx @@ -33,21 +33,28 @@ import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; - 3.15 - 2025-02-20 + 3.16 + 2026-06-23 TBD* TBD* お問い合わせ - 3.14 + 3.15 + 2025-02-20 + 2026-06-23 + 2026-12-20 + お問い合わせ + + + 3.14 2024-11-22 2026-02-20 2026-08-18 お問い合わせ - 3.13 + 3.13 2024-07-08 2025-11-22 2026-05-21 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/requirements.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/requirements.mdx index a2bc5c3d..42c96b5e 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/requirements.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/requirements.mdx @@ -54,6 +54,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | Oracle Database 23ai | Oracle Database 21c | Oracle Database 19c | |:------------------|:---------------------|:--------------------|:--------------------| +| **ScalarDB 3.16** | ✅ | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | ✅ | @@ -69,6 +70,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | MySQL 8.4 | MySQL 8.0 | |:------------------|:----------|:----------| +| **ScalarDB 3.16** | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | @@ -84,6 +86,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | PostgreSQL 17 | PostgreSQL 16 | PostgreSQL 15 | PostgreSQL 14 | PostgreSQL 13 | |:------------------|:--------------|:--------------|:--------------|:--------------|---------------| +| **ScalarDB 3.16** | ✅ | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | ✅ | ✅ | ✅ | @@ -99,6 +102,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | Aurora MySQL 3 | Aurora MySQL 2 | |:------------------|:---------------|:---------------| +| **ScalarDB 3.16** | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | @@ -114,6 +118,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | Aurora PostgreSQL 16 | Aurora PostgreSQL 15 | Aurora PostgreSQL 14 | Aurora PostgreSQL 13 | |:------------------|:---------------------|:---------------------|:---------------------|:---------------------| +| **ScalarDB 3.16** | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | ✅ | ✅ | @@ -129,6 +134,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | MariaDB 11.4 | MariaDB 10.11 | |:------------------|:-------------|:--------------| +| **ScalarDB 3.16** | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | @@ -144,6 +150,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | SQL Server 2022 | SQL Server 2019 | SQL Server 2017 | |:------------------|:----------------|:----------------|:----------------| +| **ScalarDB 3.16** | ✅ | ✅ | ✅ | | **ScalarDB 3.15** | ✅ | ✅ | ✅ | | **ScalarDB 3.14** | ✅ | ✅ | ✅ | | **ScalarDB 3.13** | ✅ | ✅ | ✅ | @@ -159,6 +166,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | SQLite 3 | |:------------------|:---------| +| **ScalarDB 3.16** | ✅ | | **ScalarDB 3.15** | ✅ | | **ScalarDB 3.14** | ✅ | | **ScalarDB 3.13** | ✅ | @@ -174,6 +182,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | YugabyteDB 2 | |:------------------|:-------------| +| **ScalarDB 3.16** | ✅ | | **ScalarDB 3.15** | ✅ | | **ScalarDB 3.14** | ✅ | | **ScalarDB 3.13** | ✅ | @@ -194,6 +203,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | DynamoDB | |:------------------|:---------| +| **ScalarDB 3.16** | ✅ | | **ScalarDB 3.15** | ✅ | | **ScalarDB 3.14** | ✅ | | **ScalarDB 3.13** | ✅ | @@ -209,6 +219,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | Cassandra 4.1 | Cassandra 4.0 | Cassandra 3.11 | Cassandra 3.0 | |:------------------|:--------------|:--------------|:---------------|:--------------| +| **ScalarDB 3.16** | ❌ | ❌ | ✅ | ✅ | | **ScalarDB 3.15** | ❌ | ❌ | ✅ | ✅ | | **ScalarDB 3.14** | ❌ | ❌ | ✅ | ✅ | | **ScalarDB 3.13** | ❌ | ❌ | ✅ | ✅ | @@ -224,6 +235,7 @@ ScalarDB は、次のデータベースとそのバージョン上で実行さ | バージョン | Cosmos DB for NoSQL | |:------------------|:--------------------| +| **ScalarDB 3.16** | ✅ | | **ScalarDB 3.15** | ✅ | | **ScalarDB 3.14** | ✅ | | **ScalarDB 3.13** | ✅ | diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/run-non-transactional-storage-operations-through-library.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/run-non-transactional-storage-operations-through-library.mdx index ea0259aa..5db57b05 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/run-non-transactional-storage-operations-through-library.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/run-non-transactional-storage-operations-through-library.mdx @@ -240,7 +240,7 @@ ScalarDB ライブラリは、[Maven Central Repository](https://mvnrepository.c ```gradle dependencies { - implementation 'com.scalar-labs:scalardb:3.15.4' + implementation 'com.scalar-labs:scalardb:3.16.0' } ```
@@ -251,7 +251,7 @@ ScalarDB ライブラリは、[Maven Central Repository](https://mvnrepository.c com.scalar-labs scalardb - 3.15.4 + 3.16.0 ``` @@ -272,4 +272,4 @@ Java API の詳細については、[ScalarDB Java API ガイド](api-guide.mdx) ### 詳細はこちら -- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.15.4/index.html) +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.16.0/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics/run-analytical-queries.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics/run-analytical-queries.mdx index afff7813..04d7a99f 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics/run-analytical-queries.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics/run-analytical-queries.mdx @@ -451,6 +451,5 @@ Java バージョンに関しては、ScalarDB Analytics は Java 8以降をサ | ScalarDB Analytics バージョン | ScalarDB バージョン | サポートされている Spark バージョン | サポートされている Scala バージョン | 最小 Java バージョン | |:----------------------------|:------------------|:-------------------------------|:-------------------------------|:-------------------| +| 3.16 | 3.16 | 3.5, 3.4 | 2.13, 2.12 | 8 | | 3.15 | 3.15 | 3.5, 3.4 | 2.13, 2.12 | 8 | -| 3.14 | 3.14 | 3.5, 3.4 | 2.13, 2.12 | 8 | -| 3.12 | 3.12 | 3.5, 3.4 | 2.13, 2.12 | 8 | diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/authorize-with-abac.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/authorize-with-abac.mdx index c9a639a0..91ffc4e8 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/authorize-with-abac.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/authorize-with-abac.mdx @@ -521,7 +521,7 @@ services: scalardb-cluster-standalone: container_name: "scalardb-cluster-node" - image: "ghcr.io/scalar-labs/scalardb-cluster-node-with-abac-byol-premium:3.15.4" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-with-abac-byol-premium:3.16.0" ports: - 60053:60053 - 9080:9080 @@ -565,7 +565,7 @@ scalar.db.cluster.auth.enabled=true 次に、以下のコマンドを実行して SQL CLI を起動します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` ユーザー名とパスワードとして、それぞれ `admin` と `admin` を入力します。 @@ -757,7 +757,7 @@ SELECT id, col, data_tag FROM n.t; SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` ユーザー名とパスワードとして、それぞれ `user1` と `user1` を入力します。 @@ -777,7 +777,7 @@ SELECT id, col, data_tag FROM n.t; SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` ユーザー名とパスワードとして、それぞれ `user2` と `user2` を入力します。 @@ -797,7 +797,7 @@ SELECT id, col, data_tag FROM n.t; SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` ユーザー名とパスワードとして、それぞれ `user3` と `user3` を入力します。 @@ -817,7 +817,7 @@ SELECT id, col, data_tag FROM n.t; SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` ユーザー名とパスワードとして、それぞれ `user2` と `user2` を入力します。 @@ -837,7 +837,7 @@ UPDATE n.t SET col = 10 WHERE id = 3; SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` ユーザー名とパスワードとして、それぞれ `user3` と `user3` を入力します。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/compatibility.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/compatibility.mdx index 589d2714..b21e60d1 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/compatibility.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/compatibility.mdx @@ -17,6 +17,7 @@ import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; | ScalarDB Cluster バージョン | ScalarDB Cluster Java Client SDK バージョン | ScalarDB Cluster .NET Client SDK バージョン | |:--------------------------|:------------------------------------------|:------------------------------------------| +| 3.16 | 3.9 - 3.16 | 3.12* - 3.16 | | 3.15 | 3.9 - 3.15 | 3.12* - 3.15 | | 3.14 | 3.9 - 3.14 | 3.12* - 3.14 | | 3.13 | 3.9 - 3.13 | 3.12* - 3.13 | diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx index d4bc52a9..a9f6a084 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx @@ -21,7 +21,7 @@ Gradle を使用して ScalarDB Cluster Java Client SDK への依存関係を追 ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -31,7 +31,7 @@ Maven を使用して依存関係を追加するには、以下を使用しま com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -118,10 +118,16 @@ scalar.db.contact_points=direct-kubernetes:ns/scalardb-cluster ### クラスター用 Schema Loader -ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (クラスター用 Schema Loader) を使用する必要があります。クラスター用Schema Loader の使用方法は、JAR ファイルの名前が異なることを除いて、[ScalarDB Schema Loader](../schema-loader.mdx) の使用方法と基本的に同じです。クラスター用 Schema Loader は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドでクラスター用 Schema Loader を実行できます。 +ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (クラスター用 Schema Loader) を使用する必要があります。クラスター用Schema Loader の使用方法は、JAR ファイルの名前が異なることを除いて、[ScalarDB Schema Loader](../schema-loader.mdx) の使用方法と基本的に同じです。クラスター用 Schema Loader は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドでクラスター用 Schema Loader を実行できます。 ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config -f --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config --schema-file --coordinator +``` + +次のコマンドを実行して、[Scalar コンテナレジストリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-schema-loader) から Docker イメージを取得することもできます。山括弧内の内容は説明に従って置き換えてください: + +```console +docker run --rm -v :/scalardb.properties -v :/schema.json ghcr.io/scalar-labs/scalardb-cluster-schema-loader:3.16.0 --config /scalardb.properties --schema-file /schema.json --coordinator ``` ## ScalarDB Cluster SQL @@ -161,8 +167,8 @@ Gradle を使用して ScalarDB Cluster JDBC ドライバーへの依存関係 ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-sql-jdbc:3.15.4' - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-sql-jdbc:3.16.0' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -173,12 +179,12 @@ Maven を使用して依存関係を追加するには、以下を使用しま com.scalar-labs scalardb-sql-jdbc - 3.15.4 + 3.16.0 com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -195,8 +201,8 @@ Gradle を使用して依存関係を追加するには、以下を使用しま ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-sql-spring-data:3.15.4' - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-sql-spring-data:3.16.0' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -207,12 +213,12 @@ Maven を使用して依存関係を追加するには、以下を使用しま com.scalar-labs scalardb-sql-spring-data - 3.15.4 + 3.16.0 com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -256,10 +262,16 @@ Spring Data JDBC for ScalarDB の設定方法の詳細については、[設定] 他の SQL データベースと同様に、ScalarDB SQL にも、コマンドラインシェルで対話的に SQL ステートメントを発行できる CLI ツールが用意されています。 -Cluster 用の SQL CLI は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで SQL CLI を実行できます。 +Cluster 用の SQL CLI は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで SQL CLI を実行できます。 + +```console +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config +``` + +次のコマンドを実行して、[Scalar コンテナレジストリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-sql-cli) から Docker イメージを取得することもできます。山括弧内の内容は説明に従って置き換えてください: ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config +docker run --rm -it -v :/scalardb-sql.properties ghcr.io/scalar-labs/scalardb-cluster-sql-cli:3.16.0 --config /scalardb-sql.properties ``` #### 使用方法 @@ -267,7 +279,7 @@ java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config CLI の使用方法は、次のように `-h` オプションを使用して確認できます。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar -h +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar -h Usage: scalardb-sql-cli [-hs] -c=PROPERTIES_FILE [-e=COMMAND] [-f=FILE] [-l=LOG_FILE] [-o=] [-p=PASSWORD] [-u=USERNAME] @@ -298,6 +310,6 @@ ScalarDB Cluster gRPC API の詳細については、以下を参照してくだ Javadocs も利用可能です: -* [ScalarDB Cluster Java Client SDK](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-java-client-sdk/3.15.4/index.html) -* [ScalarDB Cluster Common](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-common/3.15.4/index.html) -* [ScalarDB Cluster RPC](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-rpc/3.15.4/index.html) +* [ScalarDB Cluster Java Client SDK](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-java-client-sdk/3.16.0/index.html) +* [ScalarDB Cluster Common](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-common/3.16.0/index.html) +* [ScalarDB Cluster RPC](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-rpc/3.16.0/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/encrypt-data-at-rest.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/encrypt-data-at-rest.mdx index fc93bd83..7a5288a3 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/encrypt-data-at-rest.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/encrypt-data-at-rest.mdx @@ -186,7 +186,7 @@ services: scalardb-cluster-standalone: container_name: "scalardb-cluster-node" - image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.16.0" ports: - 60053:60053 - 9080:9080 @@ -244,7 +244,7 @@ scalar.db.sql.cluster_mode.contact_points=indirect:localhost 次に、次のコマンドを実行して SQL CLI を起動します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` まず、ScalarDB トランザクション実行に必要な Coordinator テーブルを作成します。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx index d6d1695b..a4e4dc5c 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx @@ -112,10 +112,10 @@ ScalarDB Cluster に接続するには、`scalar.db.transaction_manager` プロ ## ステップ 3. スキーマをロードする -ScalarDB Cluster 経由でスキーマをロードするには、ScalarDB Cluster 専用の Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Cluster 用の Schema Loader は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Cluster 用の Schema Loader を実行できます。 +ScalarDB Cluster 経由でスキーマをロードするには、ScalarDB Cluster 専用の Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Cluster 用の Schema Loader は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Cluster 用の Schema Loader を実行できます。 ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config database.properties -f schema.json --coordinator ``` ## ステップ 4. GraphiQL から操作を実行する diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx index 3a17c976..2009c5ec 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx @@ -87,10 +87,10 @@ ScalarDB Cluster に接続するには、`scalar.db.sql.connection_mode` プロ ## ステップ 3. スキーマをロードする -スキーマをロードするには、[SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli) を使用する必要があります。SQL CLI は [ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドを実行して Cluster 用の SQL CLI を使用できます。 +スキーマをロードするには、[SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli) を使用する必要があります。SQL CLI は [ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドを実行して Cluster 用の SQL CLI を使用できます。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-sql.properties --file schema.sql +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-sql.properties --file schema.sql ``` ## ステップ 4. 初期データをロードする diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx index 4bb1053f..7a37b5f8 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx @@ -91,10 +91,10 @@ ScalarDB Cluster に接続するには、`scalar.db.sql.connection_mode` プロ ## ステップ 3. スキーマをロードする -スキーマをロードするには、[SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli) を使用する必要があります。SQL CLI は [ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドを実行して Cluster 用の SQL CLI を使用できます。 +スキーマをロードするには、[SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli) を使用する必要があります。SQL CLI は [ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドを実行して Cluster 用の SQL CLI を使用できます。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-sql.properties --file schema.sql +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-sql.properties --file schema.sql ``` ## ステップ 4.`application.properties`を変更する diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster.mdx index 9471668e..557db685 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-scalardb-cluster.mdx @@ -124,7 +124,7 @@ ScalarDB Cluster を使用するには、任意のテキストエディターで dependencies { ... - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -170,12 +170,12 @@ scalar.db.contact_points=indirect:localhost サンプルアプリケーションのデータベーススキーマ (データを整理する方法) は、[`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sample/schema.json) ですでに定義されています。 -スキーマを適用するには、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4)に移動し、ScalarDB Cluster Schema Loader を `scalardb-samples/scalardb-sample` フォルダーにダウンロードします。 +スキーマを適用するには、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0)に移動し、ScalarDB Cluster Schema Loader を `scalardb-samples/scalardb-sample` フォルダーにダウンロードします。 次に、次のコマンドを実行します。 ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config database.properties -f schema.json --coordinator ``` #### スキーマの詳細 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx index 75267990..c3117a18 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx @@ -73,10 +73,10 @@ ScalarDB Cluster に接続するには、`scalar.db.transaction_manager` プロ ## ステップ 3. スキーマをロードする -ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Schema Loader for Cluster は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Schema Loader for Cluster を実行できます。 +ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Schema Loader for Cluster は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Schema Loader for Cluster を実行できます。 ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config database.properties -f schema.json --coordinator ``` ## ステップ 4. Go 環境をセットアップする diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx index 9d5bec16..d6b6a278 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx @@ -73,10 +73,10 @@ ScalarDB Cluster に接続するには、`scalar.db.transaction_manager` プロ ## ステップ 3. スキーマをロードする -ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Schema Loader for Cluster は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Schema Loader for Cluster を実行できます。 +ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Schema Loader for Cluster は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.16.0)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Schema Loader for Cluster を実行できます。 ```console -java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +java -jar scalardb-cluster-schema-loader-3.16.0-all.jar --config database.properties -f schema.json --coordinator ``` ## ステップ 4. Python 環境をセットアップする diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-vector-search.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-vector-search.mdx index c5a38590..8349820f 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-vector-search.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/getting-started-with-vector-search.mdx @@ -335,7 +335,7 @@ services: scalardb-cluster-standalone: container_name: "scalardb-cluster-node" - image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.16.0" ports: - 60053:60053 - 9080:9080 @@ -365,7 +365,7 @@ ScalarDB Cluster Embedding Java Client SDK ライブラリは [Maven Central Rep ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-cluster-embedding-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-embedding-java-client-sdk:3.16.0' } ``` @@ -376,7 +376,7 @@ ScalarDB Cluster Embedding Java Client SDK ライブラリは [Maven Central Rep com.scalar-labs scalardb-cluster-embedding-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -464,4 +464,4 @@ EmbeddingModel scalarDbEmbeddingModel = scalarDbEmbeddingClientFactory.createEmb ベクター検索機能は現在、プライベートプレビュー中です。詳細については、[お問い合わせ](https://www.scalar-labs.com/contact)いただくか、この機能が将来のバージョンで一般公開されるまでお待ちください。 -- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-embedding-java-client-sdk/3.15.4/index.html) +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-embedding-java-client-sdk/3.16.0/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx index e568f104..a00af035 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx @@ -274,7 +274,7 @@ ScalarDB Cluster Java Client SDK は、[Maven Central Repository](https://mvnrep ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -285,7 +285,7 @@ ScalarDB Cluster Java Client SDK は、[Maven Central Repository](https://mvnrep com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -310,5 +310,5 @@ Java API の詳細については、[ScalarDB Java API ガイド](../api-guide.m ### 詳細 -- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.15.4/index.html) +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.16.0/index.html) - [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx index 01e0d1e6..3892bfe6 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx @@ -279,8 +279,8 @@ ScalarDB には、実装固有のデータモデルとスキーマにマップ ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-sql-jdbc:3.15.4' - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-sql-jdbc:3.16.0' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -292,12 +292,12 @@ ScalarDB には、実装固有のデータモデルとスキーマにマップ com.scalar-labs scalardb-sql-jdbc - 3.15.4 + 3.16.0 com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -344,8 +344,8 @@ ScalarDB には、実装固有のデータモデルとスキーマにマップ ```gradle dependencies { - implementation 'com.scalar-labs:scalardb-sql:3.15.4' - implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + implementation 'com.scalar-labs:scalardb-sql:3.16.0' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.16.0' } ``` @@ -357,12 +357,12 @@ ScalarDB には、実装固有のデータモデルとスキーマにマップ com.scalar-labs scalardb-sql - 3.15.4 + 3.16.0 com.scalar-labs scalardb-cluster-java-client-sdk - 3.15.4 + 3.16.0 ``` @@ -389,7 +389,7 @@ ScalarDB には、実装固有のデータモデルとスキーマにマップ

詳細

- - [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.15.4/index.html) + - [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.16.0/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-abac-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-abac-status-codes.mdx index 7236722d..037446cd 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-abac-status-codes.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-abac-status-codes.mdx @@ -385,6 +385,14 @@ The namespace policy for the policy and namespace already exists. Policy: %s; Na The table policy for the policy and table already exists. Policy: %s; Table: %s ``` +### `DB-ABAC-10045` + +**メッセージ** + +```markdown +The user does not exist. Username: %s +``` + ## `DB-ABAC-2xxxx` ステータスコード 以下は、同時実行エラーカテゴリのステータスコードとメッセージです。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-auth-with-sql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-auth-with-sql.mdx index d3aec54f..e5139961 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-auth-with-sql.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-auth-with-sql.mdx @@ -211,7 +211,7 @@ services: scalardb-cluster-standalone: container_name: "scalardb-cluster-node" - image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.16.0" ports: - 60053:60053 - 9080:9080 @@ -247,7 +247,7 @@ scalar.db.cluster.auth.enabled=true 次に、次のコマンドを実行して SQL CLI を起動します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` ユーザー名とパスワードをそれぞれ `admin` と `admin` と入力します。 @@ -336,7 +336,7 @@ SHOW GRANTS FOR user1; `user1` としてログインし、SQL ステートメントを実行します。 ```console -java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +java -jar scalardb-cluster-sql-cli-3.16.0-all.jar --config scalardb-cluster-sql-cli.properties ``` ユーザー名とパスワードをそれぞれ `user1` と `user1` として入力します。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-cluster-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-cluster-status-codes.mdx index 7b68f95e..17b8700d 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-cluster-status-codes.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/scalardb-cluster-status-codes.mdx @@ -49,14 +49,6 @@ The table does not exist. Table: %s The user does not exist. User: %s ``` -### `DB-CLUSTER-10003` - -**メッセージ** - -```markdown -ClusterConfig is not specified -``` - ### `DB-CLUSTER-10004` **メッセージ** @@ -297,14 +289,6 @@ The property 'scalar.db.sql.cluster_mode.contact_points' must be prefixed with ' The format of the property 'scalar.db.sql.cluster_mode.contact_points' for direct-kubernetes client mode is 'direct-kubernetes:/' or 'direct-kubernetes:' ``` -### `DB-CLUSTER-10034` - -**メッセージ** - -```markdown -ClusterNodeManagerFactory is not specified -``` - ### `DB-CLUSTER-10035` **メッセージ** @@ -329,14 +313,6 @@ The update condition type is unrecognized The two-phase commit interface is not supported ``` -### `DB-CLUSTER-10038` - -**メッセージ** - -```markdown -Membership is not specified -``` - ### `DB-CLUSTER-10039` **メッセージ** @@ -501,6 +477,14 @@ The hop limit is exceeded A transaction associated with the specified transaction ID is not found. The transaction might have expired, or the cluster node that handled the transaction might have been restarted. Transaction ID: %s ``` +### `DB-CLUSTER-20002` + +**メッセージ** + +```markdown +A scanner associated with the specified scanner ID is not found. The scanner might have expired, or the cluster node that handled the scanner might have been restarted. Transaction ID: %s; Scanner ID: %s +``` + ## `DB-CLUSTER-3xxxx` ステータスコード 以下は、内部エラーカテゴリのステータスコードとメッセージです。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx index 1f276e3c..9bdcc3f9 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx @@ -172,7 +172,7 @@ ScalarDB Cluster は、バックエンドデータベースとして何らかの 5. ScalarDB Cluster のチャートバージョンを設定します。 ```console - SCALAR_DB_CLUSTER_VERSION=3.15.4 + SCALAR_DB_CLUSTER_VERSION=3.16.0 SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) ``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-core-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-core-status-codes.mdx index adf41c2b..9a7547c3 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-core-status-codes.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-core-status-codes.mdx @@ -16,12 +16,12 @@ import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; ## エラーコードのクラスと説明 -| クラス | 説明 | -|:----------------|:---------------------------------------------------------| -| `DB-CORE-1xxxx` | ユーザーエラーカテゴリのエラー | -| `DB-CORE-2xxxx` | 同時実行エラーカテゴリのエラー | -| `DB-CORE-3xxxx` | 内部エラーカテゴリのエラー | -| `DB-CORE-4xxxx` | 不明なトランザクションステータスエラーカテゴリのエラー | +| クラス | 説明 | +|:----------------|:----------------------------------------------| +| `DB-CORE-1xxxx` | ユーザーエラーカテゴリのエラー | +| `DB-CORE-2xxxx` | 同時実行エラーカテゴリのエラー | +| `DB-CORE-3xxxx` | 内部エラーカテゴリのエラー | +| `DB-CORE-4xxxx` | 不明なトランザクションステータスエラーカテゴリのエラー | ## `DB-CORE-1xxxx` ステータスコード @@ -184,7 +184,7 @@ The mutations are empty **メッセージ** ```markdown -Mutations that span multiple partitions are not supported. Mutations: %s +The storage does not support mutations across multiple partitions. Storage: %s; Mutations: %s ``` ### `DB-CORE-10020` @@ -328,7 +328,7 @@ This operation is supported only when no conditions are specified. If you want t **メッセージ** ```markdown -One or more columns must be specified. +One or more columns must be specified ``` ### `DB-CORE-10039` @@ -336,7 +336,7 @@ One or more columns must be specified. **メッセージ** ```markdown -One or more partition keys must be specified. +One or more partition keys must be specified ``` ### `DB-CORE-10040` @@ -376,7 +376,7 @@ The transaction is not active. Status: %s **メッセージ** ```markdown -The transaction has already been committed or rolled back. Status: %s +The transaction has already been committed. Status: %s ``` ### `DB-CORE-10045` @@ -832,15 +832,7 @@ Put cannot have a condition when the target record is unread and implicit pre-re **メッセージ** ```markdown -Writing already-deleted data is not allowed -``` - -### `DB-CORE-10105` - -**メッセージ** - -```markdown -Getting data neither in the read set nor the delete set is not allowed +Writing data already-deleted by the same transaction is not allowed ``` ### `DB-CORE-10106` @@ -848,7 +840,7 @@ Getting data neither in the read set nor the delete set is not allowed **メッセージ** ```markdown -Reading already-written data is not allowed +Scanning data already-written or already-deleted by the same transaction is not allowed ``` ### `DB-CORE-10107` @@ -856,7 +848,7 @@ Reading already-written data is not allowed **メッセージ** ```markdown -The transaction is not validated. When using the EXTRA_READ serializable strategy, you need to call validate() before calling commit() +The transaction is not validated. When using the SERIALIZABLE isolation level, you need to call validate() before calling commit() ``` ### `DB-CORE-10108` @@ -867,142 +859,6 @@ The transaction is not validated. When using the EXTRA_READ serializable strateg DynamoDB cannot batch more than 100 mutations at once ``` -### `DB-CORE-10109` - -**メッセージ** - -```markdown -The partition keys of the table %s.%s were modified, but altering partition keys is not supported -``` - -### `DB-CORE-10110` - -**メッセージ** - -```markdown -The clustering keys of the table %s.%s were modified, but altering clustering keys is not supported -``` - -### `DB-CORE-10111` - -**メッセージ** - -```markdown -The clustering ordering of the table %s.%s were modified, but altering clustering ordering is not supported -``` - -### `DB-CORE-10112` - -**メッセージ** - -```markdown -The column %s of the table %s.%s has been deleted. Column deletion is not supported when altering a table -``` - -### `DB-CORE-10113` - -**メッセージ** - -```markdown -The data type of the column %s of the table %s.%s was modified, but altering data types is not supported -``` - -### `DB-CORE-10114` - -**メッセージ** - -```markdown -Specifying the '--schema-file' option is required when using the '--repair-all' option -``` - -### `DB-CORE-10115` - -**メッセージ** - -```markdown -Specifying the '--schema-file' option is required when using the '--alter' option -``` - -### `DB-CORE-10116` - -**メッセージ** - -```markdown -Specifying the '--schema-file' option is required when using the '--import' option -``` - -### `DB-CORE-10117` - -**メッセージ** - -```markdown -Specifying the '--coordinator' option with the '--import' option is not allowed. Create Coordinator tables separately -``` - -### `DB-CORE-10118` - -**メッセージ** - -```markdown -Reading the configuration file failed. File: %s -``` - -### `DB-CORE-10119` - -**メッセージ** - -```markdown -Reading the schema file failed. File: %s -``` - -### `DB-CORE-10120` - -**メッセージ** - -```markdown -Parsing the schema JSON failed. Details: %s -``` - -### `DB-CORE-10121` - -**メッセージ** - -```markdown -The table name must contain the namespace and the table. Table: %s -``` - -### `DB-CORE-10122` - -**メッセージ** - -```markdown -The partition key must be specified. Table: %s -``` - -### `DB-CORE-10123` - -**メッセージ** - -```markdown -Invalid clustering-key format. The clustering key must be in the format of 'column_name' or 'column_name ASC/DESC'. Table: %s; Clustering key: %s -``` - -### `DB-CORE-10124` - -**メッセージ** - -```markdown -Columns must be specified. Table: %s -``` - -### `DB-CORE-10125` - -**メッセージ** - -```markdown -Invalid column type. Table: %s; Column: %s; Type: %s -``` - ### `DB-CORE-10126` **メッセージ** @@ -1043,46 +899,6 @@ Cross-partition scan with ordering is not supported in Cosmos DB Cross-partition scan with ordering is not supported in DynamoDB ``` -### `DB-CORE-10131` - -**メッセージ** - -```markdown -The directory '%s' does not have write permissions. Please ensure that the current user has write access to the directory. -``` - -### `DB-CORE-10132` - -**メッセージ** - -```markdown -Failed to create the directory '%s'. Please check if you have sufficient permissions and if there are any file system restrictions. Details: %s -``` - -### `DB-CORE-10133` - -**メッセージ** - -```markdown -Directory path cannot be null or empty. -``` - -### `DB-CORE-10134` - -**メッセージ** - -```markdown -No file extension was found on the provided file name %s. -``` - -### `DB-CORE-10135` - -**メッセージ** - -```markdown -Invalid file extension: %s. Allowed extensions are: %s -``` - ### `DB-CORE-10136` **メッセージ** @@ -1168,7 +984,7 @@ The value of the column %s in the primary key contains an illegal character. Pri **メッセージ** ```markdown -Inserting already-written data is not allowed +Inserting data already-written by the same transaction is not allowed ``` ### `DB-CORE-10147` @@ -1176,39 +992,7 @@ Inserting already-written data is not allowed **メッセージ** ```markdown -Deleting already-inserted data is not allowed -``` - -### `DB-CORE-10148` - -**メッセージ** - -```markdown -Invalid key: Column %s does not exist in the table %s in namespace %s. -``` - -### `DB-CORE-10149` - -**メッセージ** - -```markdown -Invalid base64 encoding for blob value for column %s in table %s in namespace %s -``` - -### `DB-CORE-10150` - -**メッセージ** - -```markdown -Invalid number specified for column %s in table %s in namespace %s -``` - -### `DB-CORE-10151` - -**メッセージ** - -```markdown -Method null argument not allowed +Deleting data already-inserted by the same transaction is not allowed ``` ### `DB-CORE-10152` @@ -1219,46 +1003,6 @@ Method null argument not allowed The attribute-based access control feature is not enabled. To use this feature, you must enable it. Note that this feature is supported only in the ScalarDB Enterprise edition ``` -### `DB-CORE-10153` - -**メッセージ** - -```markdown -The provided clustering key %s was not found -``` - -### `DB-CORE-10154` - -**メッセージ** - -```markdown -The column '%s' was not found -``` - -### `DB-CORE-10155` - -**メッセージ** - -```markdown -The provided partition key is incomplete. Required key: %s -``` - -### `DB-CORE-10156` - -**メッセージ** - -```markdown -The provided clustering key order does not match the table schema. Required order: %s -``` - -### `DB-CORE-10157` - -**メッセージ** - -```markdown -The provided partition key order does not match the table schema. Required order: %s -``` - ### `DB-CORE-10158` **メッセージ** @@ -1315,100 +1059,68 @@ This TIMESTAMPTZ column value precision cannot be shorter than one millisecond. The underlying-storage data type %s is not supported as the ScalarDB %s data type: %s ``` -### `DB-CORE-10165` - -**メッセージ** - -```markdown -Missing namespace or table: %s, %s -``` - -### `DB-CORE-10166` - -**メッセージ** - -```markdown -Failed to retrieve table metadata. Details: %s -``` - -### `DB-CORE-10167` - -**メッセージ** - -```markdown -Duplicate data mappings found for table '%s' in the control file -``` - -### `DB-CORE-10168` - -**メッセージ** - -```markdown -No mapping found for column '%s' in table '%s' in the control file. Control file validation set at 'FULL'. All columns need to be mapped. -``` - -### `DB-CORE-10169` +### `DB-CORE-10188` **メッセージ** ```markdown -The control file is missing data mappings +The replication feature is not enabled. To use this feature, you must enable it. Note that this feature is supported only in the ScalarDB Enterprise edition ``` -### `DB-CORE-10170` +### `DB-CORE-10205` **メッセージ** ```markdown -The target column '%s' for source field '%s' could not be found in table '%s' +Some scanners were not closed. All scanners must be closed before committing the transaction ``` -### `DB-CORE-10171` +### `DB-CORE-10206` **メッセージ** ```markdown -The required partition key '%s' is missing in the control file mapping for table '%s' +Some scanners were not closed. All scanners must be closed before preparing the transaction ``` -### `DB-CORE-10172` +### `DB-CORE-10211` **メッセージ** ```markdown -The required clustering key '%s' is missing in the control file mapping for table '%s' +Mutations are not allowed in read-only transactions. Transaction ID: %s ``` -### `DB-CORE-10173` +### `DB-CORE-10212` **メッセージ** ```markdown -Duplicated data mappings found for column '%s' in table '%s' +The storage does not support mutations across multiple records. Storage: %s; Mutations: %s ``` -### `DB-CORE-10174` +### `DB-CORE-10213` **メッセージ** ```markdown -Missing required field or column mapping for clustering key %s +The storage does not support mutations across multiple tables. Storage: %s; Mutations: %s ``` -### `DB-CORE-10175` +### `DB-CORE-10214` **メッセージ** ```markdown -Missing required field or column mapping for partition key %s +The storage does not support mutations across multiple namespaces. Storage: %s; Mutations: %s ``` -### `DB-CORE-10176` +### `DB-CORE-10215` **メッセージ** ```markdown -Missing field or column mapping for %s +Mutations across multiple storages are not allowed. Mutations: %s ``` ## `DB-CORE-2xxxx` ステータスコード @@ -1583,14 +1295,6 @@ The record exists, so the %s condition is not satisfied The condition on the column '%s' is not satisfied ``` -### `DB-CORE-20021` - -**メッセージ** - -```markdown -Reading empty records might cause a write skew anomaly, so the transaction has been aborted for safety purposes -``` - ### `DB-CORE-20022` **メッセージ** @@ -1623,6 +1327,14 @@ The %s condition of the %s operation is not satisfied. Targeting column(s): %s A transaction conflict occurred in the Insert operation ``` +### `DB-CORE-20026` + +**メッセージ** + +```markdown +A conflict occurred when committing records +``` + ## `DB-CORE-3xxxx` ステータスコード 以下は、内部エラーカテゴリのステータスコードとメッセージです。 @@ -1856,7 +1568,7 @@ An error occurred in the selection. Details: %s **メッセージ** ```markdown -Fetching the next result failed +Fetching the next result failed. Details: %s ``` ### `DB-CORE-30029` @@ -2003,20 +1715,44 @@ The Update operation failed. Details: %s Handling the before-preparation snapshot hook failed. Details: %s ``` -### `DB-CORE-30047` +### `DB-CORE-30054` + +**メッセージ** + +```markdown +Getting the scanner failed. Details: %s +``` + +### `DB-CORE-30055` + +**メッセージ** + +```markdown +Closing the scanner failed. Details: %s +``` + +### `DB-CORE-30056` + +**メッセージ** + +```markdown +Getting the storage information failed. Namespace: %s +``` + +### `DB-CORE-30057` **メッセージ** ```markdown -Something went wrong while trying to save the data. Details: %s +Recovering records failed. Details: %s ``` -### `DB-CORE-30048` +### `DB-CORE-30058` **メッセージ** ```markdown -Something went wrong while scanning. Are you sure you are running in the correct transaction mode? Details: %s +Committing records failed ``` ## `DB-CORE-4xxxx` ステータスコード diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-data-loader-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-data-loader-status-codes.mdx new file mode 100644 index 00000000..5a47ea53 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-data-loader-status-codes.mdx @@ -0,0 +1,542 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Data Loader エラーコード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB Data Loader のエラーコードの一覧を示します。 + +## エラーコードのクラスと説明 + +| クラス | 説明 | +|:-----------------------|:--------------------------| +| `DB-DATA-LOADER-1xxxx` | ユーザーエラーカテゴリのエラー | +| `DB-DATA-LOADER-3xxxx` | 内部エラーカテゴリのエラー | + +## `DB-DATA-LOADER-1xxxx` ステータスコード + +以下は、ユーザーエラーカテゴリのステータスコードとメッセージです。 + +### `DB-DATA-LOADER-10000` + +**メッセージ** + +```markdown +Data chunk queue size must be greater than 0 +``` + +### `DB-DATA-LOADER-10001` + +**メッセージ** + +```markdown +The directory '%s' does not have write permissions. Please ensure that the current user has write access to the directory +``` + +### `DB-DATA-LOADER-10002` + +**メッセージ** + +```markdown +Failed to create the directory '%s'. Please check if you have sufficient permissions and if there are any file system restrictions. Details: %s +``` + +### `DB-DATA-LOADER-10003` + +**メッセージ** + +```markdown +Directory path cannot be null or empty +``` + +### `DB-DATA-LOADER-10004` + +**メッセージ** + +```markdown +No file extension was found in the provided file name %s +``` + +### `DB-DATA-LOADER-10005` + +**メッセージ** + +```markdown +Invalid file extension: %s. Allowed extensions are: %s +``` + +### `DB-DATA-LOADER-10006` + +**メッセージ** + +```markdown +Invalid key: Column %s does not exist in the table %s in namespace %s +``` + +### `DB-DATA-LOADER-10007` + +**メッセージ** + +```markdown +Invalid base64 encoding for blob value '%s' for column %s in table %s in namespace %s +``` + +### `DB-DATA-LOADER-10008` + +**メッセージ** + +```markdown +Invalid number '%s' specified for column %s in table %s in namespace %s +``` + +### `DB-DATA-LOADER-10009` + +**メッセージ** + +```markdown +Method null argument not allowed +``` + +### `DB-DATA-LOADER-10010` + +**メッセージ** + +```markdown +The provided clustering key %s was not found +``` + +### `DB-DATA-LOADER-10011` + +**メッセージ** + +```markdown +The column '%s' was not found +``` + +### `DB-DATA-LOADER-10012` + +**メッセージ** + +```markdown +The provided partition key is incomplete. Required key: %s +``` + +### `DB-DATA-LOADER-10013` + +**メッセージ** + +```markdown +The provided clustering-key order does not match the table schema. Required order: %s +``` + +### `DB-DATA-LOADER-10014` + +**メッセージ** + +```markdown +The provided partition-key order does not match the table schema. Required order: %s +``` + +### `DB-DATA-LOADER-10015` + +**メッセージ** + +```markdown +Missing namespace or table: %s, %s +``` + +### `DB-DATA-LOADER-10016` + +**メッセージ** + +```markdown +Failed to retrieve table metadata. Details: %s +``` + +### `DB-DATA-LOADER-10017` + +**メッセージ** + +```markdown +Duplicate data mappings found for table '%s' in the control file +``` + +### `DB-DATA-LOADER-10018` + +**メッセージ** + +```markdown +No mapping found for column '%s' in table '%s' in the control file. Control file validation set at 'FULL'. All columns need to be mapped +``` + +### `DB-DATA-LOADER-10019` + +**メッセージ** + +```markdown +The control file is missing data mappings +``` + +### `DB-DATA-LOADER-10020` + +**メッセージ** + +```markdown +The target column '%s' for source field '%s' could not be found in table '%s' +``` + +### `DB-DATA-LOADER-10021` + +**メッセージ** + +```markdown +The required partition key '%s' is missing in the control file mapping for table '%s' +``` + +### `DB-DATA-LOADER-10022` + +**メッセージ** + +```markdown +The required clustering key '%s' is missing in the control file mapping for table '%s' +``` + +### `DB-DATA-LOADER-10023` + +**メッセージ** + +```markdown +Duplicated data mappings found for column '%s' in table '%s' +``` + +### `DB-DATA-LOADER-10024` + +**メッセージ** + +```markdown +Missing required field or column mapping for clustering key %s +``` + +### `DB-DATA-LOADER-10025` + +**メッセージ** + +```markdown +Missing required field or column mapping for partition key %s +``` + +### `DB-DATA-LOADER-10026` + +**メッセージ** + +```markdown +Missing field or column mapping for %s +``` + +### `DB-DATA-LOADER-10027` + +**メッセージ** + +```markdown +Something went wrong while converting the ScalarDB values to strings. The table metadata and Value datatype probably do not match. Details: %s +``` + +### `DB-DATA-LOADER-10028` + +**メッセージ** + +```markdown +The provided file format is not supported : %s +``` + +### `DB-DATA-LOADER-10029` + +**メッセージ** + +```markdown +Could not find the partition key +``` + +### `DB-DATA-LOADER-10030` + +**メッセージ** + +```markdown +The source record needs to contain all fields if the UPSERT turns into an INSERT +``` + +### `DB-DATA-LOADER-10031` + +**メッセージ** + +```markdown +Record already exists +``` + +### `DB-DATA-LOADER-10032` + +**メッセージ** + +```markdown +Record was not found +``` + +### `DB-DATA-LOADER-10033` + +**メッセージ** + +```markdown +Could not find the clustering key +``` + +### `DB-DATA-LOADER-10034` + +**メッセージ** + +```markdown +No table metadata found +``` + +### `DB-DATA-LOADER-10035` + +**メッセージ** + +```markdown +The data mapping source field '%s' for table '%s' is missing in the JSON data record +``` + +### `DB-DATA-LOADER-10036` + +**メッセージ** + +```markdown +The CSV row: %s does not match header: %s +``` + +### `DB-DATA-LOADER-10037` + +**メッセージ** + +```markdown +Expected JSON file content to be an array +``` + +### `DB-DATA-LOADER-10038` + +**メッセージ** + +```markdown +Missing option: either the '--namespace' and '--table' options or the '--control-file' option must be specified +``` + +### `DB-DATA-LOADER-10039` + +**メッセージ** + +```markdown +The file '%s' specified by the argument '%s' does not exist +``` + +### `DB-DATA-LOADER-10040` + +**メッセージ** + +```markdown +Cannot write to the log directory: %s +``` + +### `DB-DATA-LOADER-10041` + +**メッセージ** + +```markdown +Failed to create the log directory: %s +``` + +### `DB-DATA-LOADER-10042` + +**メッセージ** + +```markdown +Failed to parse the control file: %s +``` + +### `DB-DATA-LOADER-10043` + +**メッセージ** + +```markdown +No permission to create or write files in the directory: %s +``` + +### `DB-DATA-LOADER-10044` + +**メッセージ** + +```markdown +Failed to create the directory: %s +``` + +### `DB-DATA-LOADER-10045` + +**メッセージ** + +```markdown +Path exists but is not a directory: %s +``` + +### `DB-DATA-LOADER-10046` + +**メッセージ** + +```markdown +File path must not be blank +``` + +### `DB-DATA-LOADER-10047` + +**メッセージ** + +```markdown +File not found: %s +``` + +### `DB-DATA-LOADER-10048` + +**メッセージ** + +```markdown +Invalid date time value '%s' specified for column %s in table %s in namespace %s +``` + +### `DB-DATA-LOADER-10049` + +**メッセージ** + +```markdown +Key value cannot be null or empty +``` + +### `DB-DATA-LOADER-10050` + +**メッセージ** + +```markdown +Invalid key-value format: %s +``` + +### `DB-DATA-LOADER-10051` + +**メッセージ** + +```markdown +Value must not be null +``` + +### `DB-DATA-LOADER-10052` + +**メッセージ** + +```markdown +Delimiter must not be null +``` + +### `DB-DATA-LOADER-10053` + +**メッセージ** + +```markdown +Config file path must not be blank +``` + +### `DB-DATA-LOADER-10054` + +**メッセージ** + +```markdown +Data chunk size must be greater than 0 +``` + +### `DB-DATA-LOADER-10055` + +**メッセージ** + +```markdown +Transaction size must be greater than 0 +``` + +### `DB-DATA-LOADER-10056` + +**メッセージ** + +```markdown +Number of max threads must be greater than 0 +``` + +## `DB-DATA-LOADER-3xxxx` ステータスコード + +以下は、内部エラーカテゴリのステータスコードとメッセージです。 + +### `DB-DATA-LOADER-30000` + +**メッセージ** + +```markdown +A problem occurred while trying to save the data. Details: %s +``` + +### `DB-DATA-LOADER-30001` + +**メッセージ** + +```markdown +A problem occurred while scanning. Are you sure you are running in the correct transaction mode? Details: %s +``` + +### `DB-DATA-LOADER-30002` + +**メッセージ** + +```markdown +Failed to read CSV file. Details: %s +``` + +### `DB-DATA-LOADER-30003` + +**メッセージ** + +```markdown +Failed to CSV read header line. Details: %s +``` + +### `DB-DATA-LOADER-30004` + +**メッセージ** + +```markdown +Data chunk processing was interrupted. Details: %s +``` + +### `DB-DATA-LOADER-30005` + +**メッセージ** + +```markdown +Failed to read JSON file. Details: %s +``` + +### `DB-DATA-LOADER-30006` + +**メッセージ** + +```markdown +Failed to read JSON Lines file. Details: %s +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-schema-loader-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-schema-loader-status-codes.mdx new file mode 100644 index 00000000..c199dd92 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-schema-loader-status-codes.mdx @@ -0,0 +1,169 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Schema Loader エラーコード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB Schema Loader のエラーコードの一覧を示します。 + +## エラーコードのクラスと説明 + +| クラス | 説明 | +|:-------------------------|:------------------------| +| `DB-SCHEMA-LOADER-1xxxx` | ユーザーエラーカテゴリのエラ | + +## `DB-SCHEMA-LOADER-1xxxx` ステータスコード + +以下は、ユーザーエラーカテゴリのステータスコードとメッセージです。 + +### `DB-SCHEMA-LOADER-10000` + +**メッセージ** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-SCHEMA-LOADER-10001` + +**メッセージ** + +```markdown +The partition keys for the table %s.%s were modified, but altering partition keys is not supported +``` + +### `DB-SCHEMA-LOADER-10002` + +**メッセージ** + +```markdown +The clustering keys for the table %s.%s were modified, but altering clustering keys is not supported +``` + +### `DB-SCHEMA-LOADER-10003` + +**メッセージ** + +```markdown +The clustering order of the table %s.%s were modified, but altering the clustering order is not supported +``` + +### `DB-SCHEMA-LOADER-10004` + +**メッセージ** + +```markdown +The column %s in the table %s.%s has been deleted. Column deletion is not supported when altering a table +``` + +### `DB-SCHEMA-LOADER-10005` + +**メッセージ** + +```markdown +The data type for the column %s in the table %s.%s was modified, but altering data types is not supported +``` + +### `DB-SCHEMA-LOADER-10006` + +**メッセージ** + +```markdown +Specifying the '--schema-file' option is required when using the '--repair-all' option +``` + +### `DB-SCHEMA-LOADER-10007` + +**メッセージ** + +```markdown +Specifying the '--schema-file' option is required when using the '--alter' option +``` + +### `DB-SCHEMA-LOADER-10008` + +**メッセージ** + +```markdown +Specifying the '--schema-file' option is required when using the '--import' option +``` + +### `DB-SCHEMA-LOADER-10009` + +**メッセージ** + +```markdown +Specifying the '--coordinator' option with the '--import' option is not allowed. Create Coordinator tables separately +``` + +### `DB-SCHEMA-LOADER-10010` + +**メッセージ** + +```markdown +Reading the configuration file failed. File: %s +``` + +### `DB-SCHEMA-LOADER-10011` + +**メッセージ** + +```markdown +Reading the schema file failed. File: %s +``` + +### `DB-SCHEMA-LOADER-10012` + +**メッセージ** + +```markdown +Parsing the schema JSON failed. Details: %s +``` + +### `DB-SCHEMA-LOADER-10013` + +**メッセージ** + +```markdown +The table name must contain the namespace and the table. Table: %s +``` + +### `DB-SCHEMA-LOADER-10014` + +**メッセージ** + +```markdown +The partition key must be specified. Table: %s +``` + +### `DB-SCHEMA-LOADER-10015` + +**メッセージ** + +```markdown +Invalid clustering-key format. The clustering key must be in the format of 'column_name' or 'column_name ASC/DESC'. Table: %s; Clustering key: %s +``` + +### `DB-SCHEMA-LOADER-10016` + +**メッセージ** + +```markdown +Columns must be specified. Table: %s +``` + +### `DB-SCHEMA-LOADER-10017` + +**メッセージ** + +```markdown +Invalid column type. Table: %s; Column: %s; Type: %s +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/grammar.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/grammar.mdx index f08aec85..f8abd410 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/grammar.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/grammar.mdx @@ -605,11 +605,11 @@ ALTER TABLE ns.tbl ADD COLUMN new_col TEXT ENCRYPTED; ```java // Add a new column "new_col" to "ns.tbl" -AlterTableAddColumnStatement statement = +AlterTableAddColumnStatement statement1 = StatementBuilder.alterTable("ns", "tbl").addColumn("new_col", DataType.INT).build(); // Add a new encrypted column "new_col" to "ns.tbl" -AlterTableAddColumnStatement statement = +AlterTableAddColumnStatement statement2 = StatementBuilder.alterTable("ns", "tbl").addColumn("new_col", DataType.TEXT, true).build(); ``` @@ -2920,16 +2920,26 @@ UseStatement statement = StatementBuilder.use("ns").build(); #### 文法 ```sql -BEGIN +BEGIN [READ ONLY | READ WRITE] ``` +- `READ ONLY` を指定すると、トランザクションは読み取り専用モードで開始されます。 +- `READ WRITE` を指定すると、トランザクションは読み取り書き込みモードで開始されます。 +- `READ ONLY` または `READ WRITE` オプションを省略すると、デフォルトで読み取り書き込みトランザクションとして開始されます。 + #### 例 `BEGIN` のステートメントオブジェクトを構築する例は次のとおりです。 ```java -// Begin a transaction -BeginStatement statement = StatementBuilder.begin().build(); +// Begin a transaction. +BeginStatement statement1 = StatementBuilder.begin().build(); + +// Begin a transaction in read-only mode. +BeginStatement statement2 = StatementBuilder.begin().readOnly().build(); + +// Begin a transaction in read-write mode. +BeginStatement statement3 = StatementBuilder.begin().readWrite().build(); ``` ### START TRANSACTION @@ -2943,16 +2953,26 @@ BeginStatement statement = StatementBuilder.begin().build(); #### 文法 ```sql -START TRANSACTION +START TRANSACTION [READ ONLY | READ WRITE] ``` +- `READ ONLY` を指定すると、トランザクションは読み取り専用モードで開始されます。 +- `READ WRITE` を指定すると、トランザクションは読み取り書き込みモードで開始されます。 +- `READ ONLY` または `READ WRITE` オプションを省略すると、デフォルトで読み取り書き込みトランザクションとして開始されます。 + #### 例 `START TRANSACTION` のステートメントオブジェクトを構築する例は次のとおりです。 ```java // Start a transaction. -StartTransactionStatement statement = StatementBuilder.startTransaction().build(); +StartTransactionStatement statement1 = StatementBuilder.startTransaction().build(); + +// Start a transaction in read-only mode. +StartTransactionStatement statement2 = StatementBuilder.startTransaction().readOnly().build(); + +// Start a transaction in read-write mode. +StartTransactionStatement statement3 = StatementBuilder.startTransaction().readWrite().build(); ``` ### JOIN diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/jdbc-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/jdbc-guide.mdx index b3a03773..33b67230 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/jdbc-guide.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/jdbc-guide.mdx @@ -71,10 +71,11 @@ jdbc:scalardb:/path/to/database.properties?scalar.db.metadata.cache_expiration_t さらに、ScalarDB JDBC 固有の設定は次のとおりです。 -| 名前 | 説明 | デフォルト | -|---------------------------------------------------------------------|----------------------------------------------------|-----------| -| scalar.db.sql.jdbc.default_auto_commit | デフォルトの接続の自動コミットモード。 | true | -| scalar.db.sql.jdbc.sql_session_factory_cache.expiration_time_millis | SQL セッションファクトリのキャッシュの有効期限 (ミリ秒)。 | 10000 | +| 名前 | 説明 | デフォルト | +|---------------------------------------------------------------------|---------------------------------------------------|----------| +| scalar.db.sql.jdbc.default_auto_commit | デフォルトの接続の自動コミットモード。 | true | +| scalar.db.sql.jdbc.default_read_only | 接続のデフォルトの読み取り専用状態。 | false | +| scalar.db.sql.jdbc.sql_session_factory_cache.expiration_time_millis | SQL セッションファクトリのキャッシュの有効期限 (ミリ秒)。 | 10000 | ## ScalarDB と JDBC 間のデータ型マッピング @@ -219,4 +220,4 @@ try { - [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) - [ScalarDB SQL API ガイド](sql-api-guide.mdx) -- [Javadoc for ScalarDB JDBC](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-jdbc/3.15.4/index.html) +- [Javadoc for ScalarDB JDBC](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-jdbc/3.16.0/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/scalardb-sql-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/scalardb-sql-status-codes.mdx index 66dd4696..72457bc9 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/scalardb-sql-status-codes.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/scalardb-sql-status-codes.mdx @@ -645,3 +645,27 @@ Unmatched column type. The type of the column %s should be %s, but a TIMESTAMPTZ ```markdown The policy %s does not exist ``` + +### `DB-SQL-10078` + +**メッセージ** + +```markdown +Beginning a transaction in read-only mode is not supported in two-phase commit transaction mode +``` + +### `DB-SQL-10079` + +**メッセージ** + +```markdown +Starting a transaction in read-only mode is not supported in two-phase commit transaction mode +``` + +### `DB-SQL-10080` + +**メッセージ** + +```markdown +Cannot change read-only mode while a transaction is in progress +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/spring-data-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/spring-data-guide.mdx index d212ee81..2766ad7e 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/spring-data-guide.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/spring-data-guide.mdx @@ -824,4 +824,4 @@ Spring Data JDBC for ScalarDB を使用するために、統合では次の機 - [Spring Data JDBC - Reference Documentation](https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/) - [ScalarDB JDBC ガイド](jdbc-guide.mdx) -- [Javadoc for Spring Data JDBC for ScalarDB](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-spring-data/3.15.4/index.html) +- [Javadoc for Spring Data JDBC for ScalarDB](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-spring-data/3.16.0/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/sql-api-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/sql-api-guide.mdx index b8493ecf..711572b1 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/sql-api-guide.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-sql/sql-api-guide.mdx @@ -380,4 +380,4 @@ Metadata metadata = sqlSession.getMetadata(); - [ScalarDB SQL 文法](grammar.mdx) - [2フェーズコミットトランザクション](../two-phase-commit-transactions.mdx) -- [Javadoc for ScalarDB SQL](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.15.4/index.html) +- [Javadoc for ScalarDB SQL](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.16.0/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/schema-loader.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/schema-loader.mdx index 181bcba2..c701c3f9 100644 --- a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/schema-loader.mdx +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/schema-loader.mdx @@ -38,10 +38,10 @@ Schema Loader で一般的な CLI オプションを指定するには、次の2 Schema Loader のリリースバージョンは、[ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) ページからダウンロードできます。 - 次のコマンドを実行し、山括弧内の内容を説明に従って置き換えることで、[Scalar コンテナーレジストリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-schema-loader) から Docker イメージをプルできます。 + 次のコマンドを実行し、山括弧内の内容を説明に従って置き換えることで、[Scalar コンテナーレジストリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-schema-loader) から Docker イメージを取得できます。 ```console - docker run --rm -v : [-v :] ghcr.io/scalar-labs/scalardb-schema-loader: + docker run --rm -v :/scalardb.properties -v :/schema.json ghcr.io/scalar-labs/scalardb-schema-loader: --config /scalardb.properties --schema-file /schema.json ``` :::note diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15.json b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15.json new file mode 100644 index 00000000..c38fe261 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15.json @@ -0,0 +1,6 @@ +{ + "version.label": { + "message": "3.15", + "description": "The label for version current" + } +} diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/_develop-run-analytical-queries-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/_develop-run-analytical-queries-overview.mdx new file mode 100644 index 00000000..2a5ed4e9 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/_develop-run-analytical-queries-overview.mdx @@ -0,0 +1,18 @@ +--- +tags: + - Community + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# 分析クエリの実行の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このサブカテゴリでは、ScalarDB の分析コンポーネントである ScalarDB Analytics の設定と構成方法を学習できます。その後、ScalarDB トランザクションを通じて更新される ScalarDB 管理データベースと、ScalarDB 管理外のデータベースに対して分析クエリを実行できます。 + +分析クエリの実行方法については、次のガイドを参照してください。 + +- [ScalarDB Analytics with PostgreSQL を使用してサンプルデータに対して分析クエリを実行する](scalardb-samples/scalardb-analytics-postgresql-sample/README.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/add-scalardb-to-your-build.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/add-scalardb-to-your-build.mdx new file mode 100644 index 00000000..7e21ac74 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/add-scalardb-to-your-build.mdx @@ -0,0 +1,44 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ビルドに ScalarDB を追加する + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB ライブラリは、[Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb) で入手できます。Gradle または Maven を使用して、ライブラリをビルド依存関係としてアプリケーションに追加できます。 + +## ビルドツールに基づいてアプリケーションを設定する + +ビルドツールを選択し、手順に従って ScalarDB のビルド依存関係をアプリケーションに追加します。 + + + + Gradle を使用して ScalarDB のビルド依存関係を追加するには、アプリケーションの `build.gradle` に次のコードを追加し、`` を使用する ScalarDB のバージョンに置き換えます。 + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb:' + } + ``` + + + Maven を使用して ScalarDB のビルド依存関係を追加するには、アプリケーションの `pom.xml` に次のコードを追加し、`` を使用する ScalarDB のバージョンに置き換えます。 + + ```xml + + com.scalar-labs + scalardb + + + ``` + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/api-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/api-guide.mdx new file mode 100644 index 00000000..bf8463ea --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/api-guide.mdx @@ -0,0 +1,1713 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Java API ガイド + +import JavadocLink from '/src/theme/JavadocLink.js'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Java API は、主に管理 API とトランザクション API で設定されています。このガイドでは、どのような種類の API が存在するのか、それらの使用方法、例外の処理方法などの関連トピックについて簡単に説明します。 + +## Administrative API + +このセクションでは、ScalarDB の管理 API を使用してプログラムで管理操作を実行する方法について説明します。 + +:::note + +管理操作を実行する別の方法は、[Schema Loader](schema-loader.mdx) を使用することです。 + +::: + +### `DistributedTransactionAdmin` インスタンスを取得する + +管理操作を実行するには、まず `DistributedTransactionAdmin` インスタンスを取得する必要があります。 + +`DistributedTransactionAdmin` インスタンスを取得するには、次のように `TransactionFactory` を使用します。 + +```java +TransactionFactory transactionFactory = TransactionFactory.create(""); +DistributedTransactionAdmin admin = transactionFactory.getTransactionAdmin(); +``` + +設定の詳細については、[ScalarDB 設定](configurations.mdx)を参照してください。 + +すべての管理操作を実行したら、次のように `DistributedTransactionAdmin` インスタンスを閉じる必要があります。 + +```java +admin.close(); +``` + +### 名前空間を作成する + +テーブルは1つの名前空間に属するため、テーブルを作成する前に名前空間を作成する必要があります。 + +名前空間は次のように作成できます。 + +```java +// Create the namespace "ns". If the namespace already exists, an exception will be thrown. +admin.createNamespace("ns"); + +// Create the namespace only if it does not already exist. +boolean ifNotExists = true; +admin.createNamespace("ns", ifNotExists); + +// Create the namespace with options. +Map options = ...; +admin.createNamespace("ns", options); +``` + +#### 作成オプション + +名前空間の作成やテーブルの作成などの作成操作では、オプション名と値のマップであるオプション (`Map`) を指定できます。オプションを使用すると、ストレージアダプタ固有の設定ができます。 + +データベースを選択して、使用可能なオプションを確認します。 + + + + JDBC データベースには使用できるオプションはありません。 + + + | 名前 | 説明 | デフォルト | + |------------|-------------------------------------------------|------------| + | no-scaling | DynamoDB の自動スケーリングを無効にします。 | false | + | no-backup | DynamoDB の継続的なバックアップを無効にします。 | false | + | ru | 基本リソース単位。 | 10 | + + + | 名前 | 説明 | デフォルト | + |------------|--------------------------------------------------------|------------| + | ru | 基本リソース単位。 | 400 | + | no-scaling | Cosmos DB for NoSQL の自動スケーリングを無効にします。 | false | + + + | 名前 | 説明 | デフォルト | + |----------------------|----------------------------------------------------------------------------------------------------------|-------------------| + | replication-strategy | Cassandra レプリケーション戦略。`SimpleStrategy` または `NetworkTopologyStrategy` である必要があります。 | `SimpleStrategy` | + | compaction-strategy | Cassandra 圧縮戦略。`LCS`、`STCS`、または `TWCS` である必要があります。 | `STCS` | + | replication-factor | Cassandra の複製係数。 | 3 | + + + +### テーブルを作成する + +テーブルを作成するときは、テーブルメタデータを定義してからテーブルを作成する必要があります。 + +テーブルメタデータを定義するには、`TableMetadata` を使用できます。次の図は、テーブルの列、パーティションキー、クラスタリングキー (クラスタリング順序を含む)、およびセカンダリインデックスを定義する方法を示しています。 + +```java +// Define the table metadata. +TableMetadata tableMetadata = + TableMetadata.newBuilder() + .addColumn("c1", DataType.INT) + .addColumn("c2", DataType.TEXT) + .addColumn("c3", DataType.BIGINT) + .addColumn("c4", DataType.FLOAT) + .addColumn("c5", DataType.DOUBLE) + .addPartitionKey("c1") + .addClusteringKey("c2", Scan.Ordering.Order.DESC) + .addClusteringKey("c3", Scan.Ordering.Order.ASC) + .addSecondaryIndex("c4") + .build(); +``` + +ScalarDB のデータモデルの詳細については、[データモデル](design.mdx#データモデル)を参照してください。 + +次に、次のようにテーブルを作成します。 + +```java +// Create the table "ns.tbl". If the table already exists, an exception will be thrown. +admin.createTable("ns", "tbl", tableMetadata); + +// Create the table only if it does not already exist. +boolean ifNotExists = true; +admin.createTable("ns", "tbl", tableMetadata, ifNotExists); + +// Create the table with options. +Map options = ...; +admin.createTable("ns", "tbl", tableMetadata, options); +``` + +### セカンダリインデックスを作成する + +セカンダリインデックスは次のように作成できます。 + +```java +// Create a secondary index on column "c5" for table "ns.tbl". If a secondary index already exists, an exception will be thrown. +admin.createIndex("ns", "tbl", "c5"); + +// Create the secondary index only if it does not already exist. +boolean ifNotExists = true; +admin.createIndex("ns", "tbl", "c5", ifNotExists); + +// Create the secondary index with options. +Map options = ...; +admin.createIndex("ns", "tbl", "c5", options); +``` + +### テーブルに新しい列を追加する + +次のように、テーブルに新しい非パーティションキー列を追加できます。 + +```java +// Add a new column "c6" with the INT data type to the table "ns.tbl". +admin.addNewColumnToTable("ns", "tbl", "c6", DataType.INT) +``` + +:::warning + +テーブルに新しい列を追加する場合は、基盤となるストレージによって実行時間が大きく異なる可能性があるため、慎重に検討する必要があります。それに応じて計画を立て、特にデータベースが本番環境で実行されている場合は、次の点を考慮してください。 + +- **Cosmos DB for NoSQL および DynamoDB の場合:** テーブルスキーマは変更されないため、列の追加はほぼ瞬時に行われます。別のテーブルに格納されているテーブルメタデータのみが更新されます。 +- **Cassandra の場合:** 列を追加すると、スキーマメタデータのみが更新され、既存のスキーマレコードは変更されません。クラスタートポロジが実行時間の主な要因です。スキーマメタデータの変更は、ゴシッププロトコルを介して各クラスターノードに共有されます。このため、クラスターが大きいほど、すべてのノードが更新されるまでの時間が長くなります。 +- **リレーショナルデータベース (MySQL、Oracle など) の場合:** 列の追加は実行にそれほど時間がかかりません。 + +::: + +### テーブルを切り捨てる + +テーブルを切り捨てるには、次のようにします。 + +```java +// Truncate the table "ns.tbl". +admin.truncateTable("ns", "tbl"); +``` + +### セカンダリインデックスを削除する + +セカンダリインデックスは次のように削除できます。 + +```java +// Drop the secondary index on column "c5" from table "ns.tbl". If the secondary index does not exist, an exception will be thrown. +admin.dropIndex("ns", "tbl", "c5"); + +// Drop the secondary index only if it exists. +boolean ifExists = true; +admin.dropIndex("ns", "tbl", "c5", ifExists); +``` + +### テーブルを削除する + +テーブルを削除するには、次のようにします。 + +```java +// Drop the table "ns.tbl". If the table does not exist, an exception will be thrown. +admin.dropTable("ns", "tbl"); + +// Drop the table only if it exists. +boolean ifExists = true; +admin.dropTable("ns", "tbl", ifExists); +``` + +### 名前空間を削除する + +名前空間を削除するには、次のようにします。 + +```java +// Drop the namespace "ns". If the namespace does not exist, an exception will be thrown. +admin.dropNamespace("ns"); + +// Drop the namespace only if it exists. +boolean ifExists = true; +admin.dropNamespace("ns", ifExists); +``` + +### 既存の名前空間を取得する + +既存の名前空間は次のように取得できます。 + +```java +Set namespaces = admin.getNamespaceNames(); +``` + +### 名前空間のテーブルを取得する + +名前空間のテーブルは次のように取得できます。 + +```java +// Get the tables of the namespace "ns". +Set tables = admin.getNamespaceTableNames("ns"); +``` + +### テーブルメタデータを取得する + +テーブルメタデータは次のように取得できます。 + +```java +// Get the table metadata for "ns.tbl". +TableMetadata tableMetadata = admin.getTableMetadata("ns", "tbl"); +``` + +### 名前空間を修復する + +名前空間が不明な状態の場合 (たとえば、名前空間が基盤となるストレージに存在するが ScalarDB メタデータが存在しない、またはその逆)、このメソッドは必要に応じて名前空間とそのメタデータを再作成します。 + +名前空間は次のように修復できます。 + +```java +// Repair the namespace "ns" with options. +Map options = ...; +admin.repairNamespace("ns", options); +``` + +### テーブルを修復する + +テーブルが不明な状態の場合 (テーブルは基盤となるストレージに存在するが ScalarDB メタデータは存在しない、またはその逆)、このメソッドは必要に応じてテーブル、そのセカンダリインデックス、およびそのメタデータを再作成します。 + +テーブルは次のように修復できます。 + +```java +// Repair the table "ns.tbl" with options. +TableMetadata tableMetadata = + TableMetadata.newBuilder() + ... + .build(); +Map options = ...; +admin.repairTable("ns", "tbl", tableMetadata, options); +``` + +### 最新の ScalarDB API をサポートするように環境をアップグレードする + +ScalarDB API の最新バージョンをサポートするように ScalarDB 環境をアップグレードできます。通常、リリースノートに記載されているように、アプリケーション環境が使用する ScalarDB バージョンを更新した後、このメソッドを実行する必要があります。 + +```java +// Upgrade the ScalarDB environment. +Map options = ...; +admin.upgrade(options); +``` + +### Coordinator テーブルの操作を指定する + +Coordinator テーブルは、[Transactional API](#transactional-api) によってトランザクションのステータスを追跡するために使用されます。 + +トランザクションマネージャーを使用する場合は、トランザクションを実行するために Coordinator テーブルを作成する必要があります。テーブルの作成に加えて、Coordinator テーブルを切り捨てたり削除したりすることもできます。 + +#### Coordinator テーブルを作成する + +Coordinator テーブルは次のように作成できます。 + +```java +// Create the Coordinator table. +admin.createCoordinatorTables(); + +// Create the Coordinator table only if one does not already exist. +boolean ifNotExist = true; +admin.createCoordinatorTables(ifNotExist); + +// Create the Coordinator table with options. +Map options = ...; +admin.createCoordinatorTables(options); +``` + +#### Coordinator テーブルを切り捨てる + +Coordinator テーブルは次のように切り捨てることができます。 + +```java +// Truncate the Coordinator table. +admin.truncateCoordinatorTables(); +``` + +#### Coordinator テーブルを削除する + +Coordinator テーブルは次のように削除できます。 + +```java +// Drop the Coordinator table. +admin.dropCoordinatorTables(); + +// Drop the Coordinator table if one exist. +boolean ifExist = true; +admin.dropCoordinatorTables(ifExist); +``` + +### テーブルをインポートする + +既存のテーブルを ScalarDB にインポートするには、次のようにします。 + +```java +// Import the table "ns.tbl". If the table is already managed by ScalarDB, the target table does not +// exist, or the table does not meet the requirements of the ScalarDB table, an exception will be thrown. +admin.importTable("ns", "tbl", options, overrideColumnsType); +``` + +:::warning + +運用環境で ScalarDB にテーブルをインポートする場合は、データベーステーブルと ScalarDB メタデータテーブルにトランザクションメタデータ列が追加されるため、慎重に計画する必要があります。この場合、データベースと ScalarDB の間にはいくつかの違いがあり、いくつかの制限もあります。詳細については、[ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](./schema-loader-import.mdx)を参照してください。 + +::: + +## Transactional API + +このセクションでは、ScalarDB の Transactional API を使用してトランザクション操作を実行する方法について説明します。 + +### `DistributedTransactionManager` インスタンスを取得する + +トランザクション操作を実行するには、まず `DistributedTransactionManager` インスタンスを取得する必要があります。 + +`DistributedTransactionManager` インスタンスを取得するには、次のように `TransactionFactory` を使用します。 + +```java +TransactionFactory transactionFactory = TransactionFactory.create(""); +DistributedTransactionManager transactionManager = transactionFactory.getTransactionManager(); +``` + +すべてのトランザクション操作を実行した後、次のように `DistributedTransactionManager` インスタンスを閉じる必要があります。 + +```java +transactionManager.close(); +``` + +### トランザクションを実行する + +このサブセクションでは、複数の CRUD 操作でトランザクションを実行する方法について説明します。 + +#### トランザクションを開始する + +トランザクション CRUD 操作を実行する前に、トランザクションを開始する必要があります。 + +トランザクションは次のように開始できます。 + +```java +// Begin a transaction. +DistributedTransaction transaction = transactionManager.begin(); +``` + +または、次のようにトランザクションを開始することもできます。 + +```java +// Start a transaction. +DistributedTransaction transaction = transactionManager.start(); +``` + +あるいは、次のようにトランザクション ID を指定して、トランザクションに `begin` メソッドを使用することもできます。 + +```java +// Begin a transaction with specifying a transaction ID. +DistributedTransaction transaction = transactionManager.begin(""); +``` + +または、次のようにトランザクション ID を指定して、トランザクションに `start` メソッドを使用することもできます。 + +```java +// Start a transaction with specifying a transaction ID. +DistributedTransaction transaction = transactionManager.start(""); +``` + +:::note + +トランザクション ID を指定すると、外部システムを ScalarDB にリンクする場合に便利です。それ以外の場合は、`begin()` メソッドまたは `start()` メソッドを使用する必要があります。 + +トランザクション ID を指定する場合は、ScalarDB の正確性はトランザクション ID の一意性に依存するため、システム全体で一意の ID (UUID v4など) を指定してください。 + +::: + +#### トランザクションに参加する + +トランザクションに参加することは、トランザクションが複数のクライアントリクエストにまたがるステートフルアプリケーションで特に便利です。このようなシナリオでは、アプリケーションは最初のクライアントリクエスト中にトランザクションを開始できます。その後、後続のクライアントリクエストで、アプリケーションは `join()` メソッドを使用して進行中のトランザクションに参加できます。 + +次のようにトランザクション ID を指定すると、すでに開始されている進行中のトランザクションに参加できます。 + +```java +// Join a transaction. +DistributedTransaction transaction = transactionManager.join(""); +``` + +:::note + +`getId()` を使用してトランザクション ID を取得するには、次のように指定します。 + +```java +tx.getId(); +``` + +::: + +#### トランザクションを再開する + +トランザクションの再開は、トランザクションが複数のクライアントリクエストにまたがるステートフルアプリケーションで特に役立ちます。このようなシナリオでは、アプリケーションは最初のクライアントリクエスト中にトランザクションを開始できます。その後、後続のクライアントリクエストで、アプリケーションは `resume()` メソッドを使用して進行中のトランザクションを再開できます。 + +次のようにトランザクション ID を指定すると、すでに開始した進行中のトランザクションを再開できます。 + +```java +// Resume a transaction. +DistributedTransaction transaction = transactionManager.resume(""); +``` + +:::note + +`getId()` を使用してトランザクション ID を取得するには、次のように指定します。 + +```java +tx.getId(); +``` + +::: + +#### CRUD 操作を実装する + +次のセクションでは、キーの構築と CRUD 操作について説明します。 + +:::note + +CRUD 操作のすべてのビルダーは `consistency()` メソッドを使用して一貫性を指定できますが、これらのメソッドは無視されます。代わりに、トランザクションでは常に `LINEARIZABLE` 一貫性レベルが使用されます。 + +::: + +##### キーの構築 + +ほとんどの CRUD 操作では、`Key` オブジェクト (パーティションキー、クラスタリングキーなど) を指定する必要があります。そのため、CRUD 操作に進む前に、`Key` オブジェクトの構築方法を次に説明します。 + +単一の列キーの場合、次のように `Key.of()` メソッドを使用してキーを構築できます。 + +```java +// For a key that consists of a single column of INT. +Key key1 = Key.ofInt("col1", 1); + +// For a key that consists of a single column of BIGINT. +Key key2 = Key.ofBigInt("col1", 100L); + +// For a key that consists of a single column of DOUBLE. +Key key3 = Key.ofDouble("col1", 1.3d); + +// For a key that consists of a single column of TEXT. +Key key4 = Key.ofText("col1", "value"); +``` + +2~5列で設定されるキーの場合は、`Key.of()` メソッドを使用して次のようにキーを構築できます。Guava の `ImmutableMap.of()` と同様に、列名と値を順番に指定する必要があります。 + +```java +// For a key that consists of two to five columns. +Key key1 = Key.of("col1", 1, "col2", 100L); +Key key2 = Key.of("col1", 1, "col2", 100L, "col3", 1.3d); +Key key3 = Key.of("col1", 1, "col2", 100L, "col3", 1.3d, "col4", "value"); +Key key4 = Key.of("col1", 1, "col2", 100L, "col3", 1.3d, "col4", "value", "col5", false); +``` + +5列を超えるキーの場合は、ビルダーを使用して次のようにキーを構築できます。 + +```java +// For a key that consists of more than five columns. +Key key = Key.newBuilder() + .addInt("col1", 1) + .addBigInt("col2", 100L) + .addDouble("col3", 1.3d) + .addText("col4", "value") + .addBoolean("col5", false) + .addInt("col6", 100) + .build(); +``` + +##### `Get` 操作 + +`Get` は、主キーで指定された単一のレコードを取得する操作です。 + +まず `Get` オブジェクトを作成し、次に次のように `transaction.get()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Get` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .projections("c1", "c2", "c3", "c4") + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .build(); + +// Execute the `Get` operation. +Optional result = transaction.get(get); +``` + +射影を指定して、返される列を選択できます。 + +###### `WHERE` 句を使用する + +`where()` メソッドを使用して任意の条件を指定することもできます。取得したレコードが `where()` メソッドで指定された条件と一致しない場合は、`Option.empty()` が返されます。`where()` メソッドの引数として、条件、AND 条件セット、または OR 条件セットを指定できます。`where()` メソッドを呼び出した後、次のように `and()` メソッドまたは `or()` メソッドを使用して、さらに条件または条件セットを追加できます。 + +```java +// Create a `Get` operation with condition sets. +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .where( + ConditionSetBuilder.condition(ConditionBuilder.column("c1").isLessThanInt(10)) + .or(ConditionBuilder.column("c1").isGreaterThanInt(20)) + .build()) + .and( + ConditionSetBuilder.condition(ConditionBuilder.column("c2").isLikeText("a%")) + .or(ConditionBuilder.column("c2").isLikeText("b%")) + .build()) + .build(); +``` + +:::note + +`where()` 条件メソッドチェーンでは、条件は上記の例のように `ConditionalExpression` または `OrConditionSet` の AND 結合 (結合正規形と呼ばれる)、または `ConditionalExpression` または `AndConditionSet` の OR 結合 (分離正規形と呼ばれる) である必要があります。 + +::: + +使用可能な条件と条件セットの詳細については、Javadoc の および ページを参照してください。 + +###### `Result` オブジェクトの処理 + +`Get` 操作と `Scan` 操作は `Result` オブジェクトを返します。次に、`Result` オブジェクトの処理方法を示します。 + +次のように `get("")` メソッドを使用して、結果の列値を取得できます。 + +```java +// Get the BOOLEAN value of a column. +boolean booleanValue = result.getBoolean(""); + +// Get the INT value of a column. +int intValue = result.getInt(""); + +// Get the BIGINT value of a column. +long bigIntValue = result.getBigInt(""); + +// Get the FLOAT value of a column. +float floatValue = result.getFloat(""); + +// Get the DOUBLE value of a column. +double doubleValue = result.getDouble(""); + +// Get the TEXT value of a column. +String textValue = result.getText(""); + +// Get the BLOB value of a column as a `ByteBuffer`. +ByteBuffer blobValue = result.getBlob(""); + +// Get the BLOB value of a column as a `byte` array. +byte[] blobValueAsBytes = result.getBlobAsBytes(""); + +// Get the DATE value of a column as a `LocalDate`. +LocalDate dateValue = result.getDate(""); + +// Get the TIME value of a column as a `LocalTime`. +LocalTime timeValue = result.getTime(""); + +// Get the TIMESTAMP value of a column as a `LocalDateTime`. +LocalDateTime timestampValue = result.getTimestamp(""); + +// Get the TIMESTAMPTZ value of a column as a `Instant`. +Instant timestampTZValue = result.getTimestampTZ(""); +``` + +列の値が null かどうかを確認する必要がある場合は、`isNull("")` メソッドを使用できます。 + +``` java +// Check if a value of a column is null. +boolean isNull = result.isNull(""); +``` + +詳細については、Javadoc の ページを参照してください。 + +###### セカンダリインデックスを使用して `Get` を実行する + +セカンダリインデックスを使用して `Get` 操作を実行できます。 + +パーティションキーを指定する代わりに、次のようにインデックスキー (インデックス付き列) を指定してセカンダリインデックスを使用できます。 + +```java +// Create a `Get` operation by using a secondary index. +Key indexKey = Key.ofFloat("c4", 1.23F); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .indexKey(indexKey) + .projections("c1", "c2", "c3", "c4") + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .build(); + +// Execute the `Get` operation. +Optional result = transaction.get(get); +``` + +`where()` メソッドを使用して任意の条件を指定することもできます。詳細については、[`WHERE` 句を使用する](#where-句を使用する)を参照してください。 + +:::note + +結果に複数のレコードがある場合、`transaction.get()` は例外をスローします。複数の結果を処理する場合は、[セカンダリインデックスを使用して `Scan` を実行する](#セカンダリインデックスを使用して-scan-を実行する)を参照してください。 + +::: + +##### `Scan` 操作 + +`Scan` は、パーティション内の複数のレコードを取得する操作です。`Scan` 操作では、クラスタリングキーの境界とクラスタリングキー列の順序を指定できます。 + +まず `Scan` オブジェクトを作成し、次に次のように `transaction.scan()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Scan` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key startClusteringKey = Key.of("c2", "aaa", "c3", 100L); +Key endClusteringKey = Key.of("c2", "aaa", "c3", 300L); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .start(startClusteringKey, true) // Include startClusteringKey + .end(endClusteringKey, false) // Exclude endClusteringKey + .projections("c1", "c2", "c3", "c4") + .orderings(Scan.Ordering.desc("c2"), Scan.Ordering.asc("c3")) + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transaction.scan(scan); +``` + +クラスタリングキー境界を省略するか、`start` 境界または `end` 境界のいずれかを指定できます。`orderings` を指定しない場合は、テーブルの作成時に定義したクラスタリング順序で結果が並べられます。 + +さらに、`projections` を指定して返される列を選択し、`limit` を使用して `Scan` 操作で返されるレコードの数を指定できます。 + +###### `WHERE` 句を使用する + +`where()` メソッドを使用してスキャンされたレコードをフィルタリングすることで、任意の条件を指定することもできます。`where()` メソッドの引数として、条件、AND 条件セット、または OR 条件セットを指定できます。`where()` メソッドを呼び出した後、次のように `and()` メソッドまたは `or()` メソッドを使用して、さらに条件または条件セットを追加できます。 + +```java +// Create a `Scan` operation with condition sets. +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .where( + ConditionSetBuilder.condition(ConditionBuilder.column("c1").isLessThanInt(10)) + .or(ConditionBuilder.column("c1").isGreaterThanInt(20)) + .build()) + .and( + ConditionSetBuilder.condition(ConditionBuilder.column("c2").isLikeText("a%")) + .or(ConditionBuilder.column("c2").isLikeText("b%")) + .build()) + .limit(10) + .build(); +``` + +:::note + +`where()` 条件メソッドチェーンでは、条件は上記の例のように `ConditionalExpression` または `OrConditionSet` の AND 結合 (結合正規形と呼ばれる)、または `ConditionalExpression` または `AndConditionSet` の OR 結合 (分離正規形と呼ばれる) である必要があります。 + +::: + +使用可能な条件と条件セットの詳細については、Javadoc の および ページを参照してください。 + +###### セカンダリインデックスを使用して `Scan` を実行する + +セカンダリインデックスを使用して、`Scan` 操作を実行できます。 + +パーティションキーを指定する代わりに、次のようにインデックスキー (インデックス付き列) を指定してセカンダリインデックスを使用できます。 + +```java +// Create a `Scan` operation by using a secondary index. +Key indexKey = Key.ofFloat("c4", 1.23F); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .indexKey(indexKey) + .projections("c1", "c2", "c3", "c4") + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transaction.scan(scan); +``` + +`where()` メソッドを使用して任意の条件を指定することもできます。詳細については、[`WHERE` 句を使用する](#where-句を使用する)を参照してください。 + +:::note + +セカンダリインデックスを使用して、`Scan` でクラスタリングキーの境界と順序を指定することはできません。 + +::: + +###### パーティションキーを指定せずにクロスパーティション `Scan` を実行し、テーブルのすべてのレコードを取得します + +ScalarDB プロパティファイルで次の設定を有効にすると、パーティションキーを指定せずに、すべてのパーティションにわたって `Scan` 操作 (クロスパーティションスキャン* と呼びます) を実行できます。 + +```properties +scalar.db.cross_partition_scan.enabled=true +``` + +:::warning + +非 JDBC データベースの場合、`SERIALIZABLE` 分離レベルでクロスパーティションスキャンを有効にした場合でも、トランザクションは読み取りコミットスナップショット分離 (`SNAPSHOT`) で実行される可能性があります。これは、より低い分離レベルです。非 JDBC データベースを使用する場合は、トランザクションの一貫性が重要でない場合にのみ、クロスパーティションスキャンを使用してください。 + +::: + +ビルダーで `partitionKey()` メソッドを呼び出す代わりに、次のように `all()` メソッドを呼び出して、パーティションキーを指定せずにテーブルをスキャンできます。 + +```java +// Create a `Scan` operation without specifying a partition key. +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .projections("c1", "c2", "c3", "c4") + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transaction.scan(scan); +``` + +:::note + +非 JDBC データベースを使用する場合、クロスパーティション `Scan` で順序を指定することはできません。フィルタリングまたは順序付けを指定したクロスパーティション `Scan` の使用方法の詳細については、[フィルタリングと順序付けを使用してパーティション間の `Scan` を実行する](#フィルタリングと順序付けを使用してパーティション間の-scan-を実行する)を参照してください。 + +::: + +###### フィルタリングと順序付けを使用してパーティション間の `Scan` を実行する + +次のようにフィルタリングと順序付けによるクロスパーティションスキャンオプションを有効にすると、柔軟な条件と順序付けでクロスパーティション `Scan` 操作を実行できます。 + +```properties +scalar.db.cross_partition_scan.enabled=true +scalar.db.cross_partition_scan.filtering.enabled=true +scalar.db.cross_partition_scan.ordering.enabled=true +``` + +:::note + +非 JDBC データベースでは `scalar.db.cross_partition_scan.ordering` を有効にすることはできません。 + +::: + +次のように、`all()` メソッドを呼び出した後に `where()` メソッドと `ordering()` メソッドを呼び出して、任意の条件と順序を指定できます。 + +```java +// Create a `Scan` operation with arbitrary conditions and orderings. +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .projections("c1", "c2", "c3", "c4") + .orderings(Scan.Ordering.desc("c3"), Scan.Ordering.asc("c4")) + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transaction.scan(scan); +``` + +`WHERE` 句の詳細については、[`WHERE` 句を使用する](#where-句を使用する)を参照してください。 + +##### `Put` 操作 + +:::note + +`Put` 操作は ScalarDB 3.13以降では非推奨となり、将来のリリースでは削除される予定です。`Put` 操作の代わりに、`Insert` 操作、`Upsert` 操作、または `Update` 操作を使用してください。 + +::: + +`Put` は、主キーで指定されたレコードを配置する操作です。この操作はレコードの upsert 操作として動作し、レコードが存在する場合はレコードを更新し、レコードが存在しない場合はレコードを挿入します。 + +:::note + +既存のレコードを更新する場合、`Put` 操作を使用する前に `Get` または `Scan` を使用してレコードを読み取る必要があります。そうしないと、競合により操作が失敗します。これは、トランザクションを適切に管理するための ScalarDB の仕様により発生します。レコードを明示的に読み取る代わりに、暗黙的な事前読み取りを有効にできます。詳細については、[`Put` 操作の暗黙的な事前読み取りを有効にする](#put-操作の暗黙的な事前読み取りを有効にする)を参照してください。 + +::: + +まず `Put` オブジェクトを作成し、次に次のように `transaction.put()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Put` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Put` operation. +transaction.put(put); +``` + +次のように `null` 値を持つレコードを配置することもできます。 + +```java +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", null) + .doubleValue("c5", null) + .build(); +``` + +###### `Put` 操作の暗黙的な事前読み取りを有効にする + +Consensus Commit では、レコードが存在する場合、レコードの最新の状態を取得するために、アプリケーションは `Put` および `Delete` 操作でレコードを変更する前にレコードを読み取る必要があります。レコードを明示的に読み取る代わりに、*暗黙的な事前読み取り* を有効にすることができます。暗黙的な事前読み取りを有効にすると、アプリケーションがトランザクションでレコードを明示的に読み取らない場合は、ScalarDB がトランザクションをコミットする前にアプリケーションに代わってレコードを読み取ります。 + +`Put` 操作の暗黙的な事前読み取りを有効にするには、次のように `Put` 操作ビルダーで `enableImplicitPreRead()` を指定します。 + +```java +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .enableImplicitPreRead() + .build(); +``` + +:::note + +変更しようとしているレコードが存在しないことが確実な場合は、パフォーマンスを向上させるために、`Put` 操作の暗黙的な事前読み取りを有効にしないでください。たとえば、初期データをロードする場合は、暗黙的な事前読み取りを有効にしないでください。暗黙的な事前読み取りのない `Put` 操作は、暗黙的な事前読み取りのある `Put` 操作よりも高速です。これは、操作によって不要な読み取りがスキップされるためです。 + +::: + +##### `Insert` 操作 + +`Insert` は、トランザクションを通じて基礎となるストレージにエントリを挿入する操作です。エントリがすでに存在する場合は、競合エラーが発生します。 + +まず `Insert` オブジェクトを作成し、次に次のように `transaction.insert()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create an `Insert` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Insert insert = + Insert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Insert` operation. +transaction.insert(insert); +``` + +##### `Upsert` 操作 + +`Upsert` は、トランザクションを通じて基礎となるストレージにエントリを挿入したり、エントリを更新したりする操作です。エントリがすでに存在する場合は更新され、そうでない場合はエントリが挿入されます。 + +まず `Upsert` オブジェクトを作成し、次に次のように `transaction.upsert()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create an `Upsert` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Upsert upsert = + Upsert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Upsert` operation. +transaction.upsert(upsert); +``` + +##### `Update` 操作 + +`Update` は、トランザクションを通じて基礎となるストレージ内のエントリを更新する操作です。エントリが存在しない場合、操作によって変更は行われません。 + +まず `Update` オブジェクトを作成し、次に次のように `transaction.update()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create an `Update` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Update update = + Update.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Update` operation. +transaction.update(update); +``` + +##### `Delete` 操作 + +`Delete` は、主キーで指定されたレコードを削除する操作です。 + +:::note + +レコードを削除する場合、`Delete` 操作では暗黙的な事前読み取りが常に有効になっているため、事前にレコードを読み取る必要はありません。 + +::: + +まず `Delete` オブジェクトを作成し、次に次のように `transaction.delete()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Delete` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .build(); + +// Execute the `Delete` operation. +transaction.delete(delete); +``` + +##### 条件付きの `Put`、`Delete`、`Update` + +トランザクション内で条件をチェックするロジックを実装することで、コミット前にトランザクションが満たす必要のある任意の条件 (たとえば、銀行口座の残高が0以上である必要がある) を記述できます。または、`Put`、`Delete`、`Update` などのミューテーション操作で単純な条件を記述することもできます。 + +`Put`、`Delete`、`Update` 操作に条件が含まれている場合、指定された条件が満たされた場合にのみ操作が実行されます。操作の実行時に条件が満たされていない場合は、`UnsatisfiedConditionException` という例外がスローされます。 + +:::note + +`Put` 操作で条件を指定する場合は、事前にレコードを読み取るか、暗黙的な事前読み取りを有効にする必要があります。 + +::: + +###### `Put` の条件 + +`Put` 操作では、次のように条件を指定できます。 + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.putIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .condition(condition) // condition + .build(); + +// Execute the `Put` operation. +transaction.put(put); +``` + +`putIf` 条件を使用するだけでなく、次のように `putIfExists` 条件と `putIfNotExists` 条件を指定することもできます。 + +```java +// Build a `putIfExists` condition. +MutationCondition putIfExistsCondition = ConditionBuilder.putIfExists(); + +// Build a `putIfNotExists` condition. +MutationCondition putIfNotExistsCondition = ConditionBuilder.putIfNotExists(); +``` + +###### `Delete` の条件 + +`Delete` 操作では、次のように条件を指定できます。 + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.deleteIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .condition(condition) // condition + .build(); + +// Execute the `Delete` operation. +transaction.delete(delete); +``` + +`deleteIf` 条件を使用するだけでなく、次のように `deleteIfExists` 条件を指定することもできます。 + +```java +// Build a `deleteIfExists` condition. +MutationCondition deleteIfExistsCondition = ConditionBuilder.deleteIfExists(); +``` + +###### `Update` の条件 + +`Update` 操作では、次のように条件を指定できます。 + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.updateIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Update update = + Update.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .condition(condition) // condition + .build(); + +// Execute the `Update` operation. +transaction.update(update); +``` + +`updateIf` 条件を使用するだけでなく、次のように `updateIfExists` 条件を指定することもできます。 + +```java +// Build a `updateIfExists` condition. +MutationCondition updateIfExistsCondition = ConditionBuilder.updateIfExists(); +``` + +##### Mutate 操作 + +Mutate は、`Put`、`Insert`、`Upsert`、`Update`、`Delete` の複数の操作を実行する操作です。 + +まず Mutate オブジェクトを作成し、次に次のように `transaction.mutate()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create `Put` and `Delete` operations. +Key partitionKey = Key.ofInt("c1", 10); + +Key clusteringKeyForPut = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForPut) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +Key clusteringKeyForDelete = Key.of("c2", "bbb", "c3", 200L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForDelete) + .build(); + +// Execute the operations. +transaction.mutate(Arrays.asList(put, delete)); +``` + +##### CRUD 操作のデフォルト名前空間 + +すべての CRUD 操作のデフォルト名前空間は、ScalarDB 設定のプロパティを使用して設定できます。 + +```properties +scalar.db.default_namespace_name= +``` + +名前空間を指定しない操作では、設定されたデフォルトの名前空間が使用されます。 + +```java +// This operation will target the default namespace. +Scan scanUsingDefaultNamespace = + Scan.newBuilder() + .table("tbl") + .all() + .build(); +// This operation will target the "ns" namespace. +Scan scanUsingSpecifiedNamespace = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .build(); +``` + +##### オペレーション属性 + +オペレーション属性は、オペレーションに関する追加情報を保持するためのキーと値のペアです。以下のように、オペレーションビルダーの`attribute()`メソッドや`attributes()`メソッドを使って設定できます。 + +```java +// Set operation attributes in the `Get` operation. +Get get = Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Scan` operation. +Scan scan = Scan.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .projections("c1", "c2", "c3", "c4") + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Insert` operation. +Insert insert = Insert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Upsert` operation. +Upsert upsert = Upsert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Update` operation. +Update update = Update.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Delete` operation. +Delete delete = Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); +``` + +:::note + +ScalarDB では現在、利用可能なオペレーション属性はありません。 + +::: + +#### トランザクションをコミットする + +CRUD 操作を実行した後、トランザクションをコミットして終了する必要があります。 + +トランザクションは次のようにコミットできます。 + +```java +// Commit a transaction. +transaction.commit(); +``` + +#### トランザクションをロールバックまたはアボートする + +トランザクションの実行中にエラーが発生した場合は、トランザクションをロールバックまたはアボートできます。 + +トランザクションは次のようにロールバックできます。 + +```java +// Roll back a transaction. +transaction.rollback(); +``` + +または、次のようにトランザクションをアボートすることもできます。 + +```java +// Abort a transaction. +transaction.abort(); +``` + +ScalarDB で例外を処理する方法の詳細については、[例外の処理方法](#例外の処理方法)を参照してください。 + +### トランザクションを開始せずにトランザクションを実行する + +トランザクションを開始せずにトランザクション操作を実行できます。この場合、ScalarDB は操作を実行する前に自動的にトランザクションを開始し、操作の実行後にトランザクションをコミットします。このセクションでは、トランザクションを開始せずにトランザクションを実行する方法について説明します。 + +#### `Get` 操作を実行する + +`Get` は、主キーで指定された単一のレコードを取得する操作です。 + +最初に `Get` オブジェクトを作成し、次に次のように `transactionManager.get()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Get` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .projections("c1", "c2", "c3", "c4") + .build(); + +// Execute the `Get` operation. +Optional result = transactionManager.get(get); +``` + +`Get` 操作の詳細については、[`Get` 操作](#get-操作)を参照してください。 + +#### `Scan` 操作の実行 + +`Scan` は、パーティション内の複数のレコードを取得する操作です。`Scan` 操作では、クラスタリングキーの境界とクラスタリングキー列の順序を指定できます。 + +まず `Scan` オブジェクトを作成し、次に次のように `transactionManager.scan()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Scan` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key startClusteringKey = Key.of("c2", "aaa", "c3", 100L); +Key endClusteringKey = Key.of("c2", "aaa", "c3", 300L); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .start(startClusteringKey, true) // Include startClusteringKey + .end(endClusteringKey, false) // Exclude endClusteringKey + .projections("c1", "c2", "c3", "c4") + .orderings(Scan.Ordering.desc("c2"), Scan.Ordering.asc("c3")) + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transactionManager.scan(scan); +``` + +`Scan` 操作の詳細については、[`Scan` 操作](#scan-操作)を参照してください。 + +#### `Put` 操作を実行します + +:::note + +`Put` 操作は ScalarDB 3.13以降では非推奨となり、将来のリリースでは削除される予定です。`Put` 操作の代わりに、`Insert` 操作、`Upsert` 操作、または `Update` 操作を使用してください。 + +::: + +まず `Put` オブジェクトを作成し、次に次のように `transactionManager.put()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Put` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Put` operation. +transactionManager.put(put); +``` + +`Put` 操作の詳細については、[`Put` 操作](#put-操作)を参照してください。 + +#### `Insert` 操作の実行 + +`Insert` は、トランザクションを通じて基礎となるストレージにエントリを挿入する操作です。エントリがすでに存在する場合は、競合エラーが発生します。 + +まず `Insert` オブジェクトを作成し、次に次のように `transactionManager.insert()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create an `Insert` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Insert insert = + Insert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Insert` operation. +transactionManager.insert(insert); +``` + +`Insert` 操作の詳細については、[`Insert` 操作](#insert-操作)を参照してください。 + +#### `Upsert` 操作を実行する + +`Upsert` は、トランザクションを通じて基礎となるストレージにエントリを挿入するか、エントリを更新する操作です。エントリがすでに存在する場合は更新され、そうでない場合はエントリが挿入されます。 + +まず `Upsert` オブジェクトを作成し、次に次のように `transactionManager.upsert()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create an `Upsert` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Upsert upsert = + Upsert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Upsert` operation. +transactionManager.upsert(upsert); +``` + +`Insert` 操作の詳細については、[`Upsert` 操作](#upsert-操作)を参照してください。 + +#### `Update` 操作の実行 + +`Update` は、トランザクションを通じて基礎となるストレージ内のエントリを更新する操作です。エントリが存在しない場合、操作によって変更は行われません。 + +まず `Update` オブジェクトを作成し、次に次のように `transactionManager.update()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create an `Update` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Update update = + Update.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Update` operation. +transactionManager.update(update); +``` + +`Update` 操作の詳細については、[`Update` 操作](#update-操作)を参照してください。 + +#### `Delete` 操作を実行する + +`Delete` は、主キーで指定されたレコードを削除する操作です。 + +まず `Delete` オブジェクトを作成し、次に次のように `transaction.delete()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Delete` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .build(); + +// Execute the `Delete` operation. +transactionManager.delete(delete); +``` + +`Delete` 操作の詳細については、[`Delete` 操作](#delete-操作)を参照してください。 + +#### Mutate 操作の実行 + +Mutate は、複数のミューテーション (`Put`、`Insert`、`Upsert`、`Update`、および `Delete` 操作) を実行する操作です。 + +まずミューテーションオブジェクトを作成し、次に次のように `transactionManager.mutate()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create `Put` and `Delete` operations. +Key partitionKey = Key.ofInt("c1", 10); + +Key clusteringKeyForPut = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForPut) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +Key clusteringKeyForDelete = Key.of("c2", "bbb", "c3", 200L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForDelete) + .build(); + +// Execute the operations. +transactionManager.mutate(Arrays.asList(put, delete)); +``` + +Mutate 操作の詳細については、[Mutate 操作](#mutate-操作)を参照してください。 + +また、ScalarDB での例外の処理方法の詳細については、[例外の処理方法](#例外の処理方法)を参照してください。 + +## 例外の処理方法 + +トランザクションを実行するときは、例外も適切に処理する必要があります。 + +:::warning + +例外を適切に処理しないと、異常やデータの不整合が発生する可能性があります。 + +::: + +次のサンプルコードは、例外を処理する方法を示しています。 + +```java +public class Sample { + public static void main(String[] args) throws Exception { + TransactionFactory factory = TransactionFactory.create(""); + DistributedTransactionManager transactionManager = factory.getTransactionManager(); + + int retryCount = 0; + TransactionException lastException = null; + + while (true) { + if (retryCount++ > 0) { + // Retry the transaction three times maximum. + if (retryCount >= 3) { + // Throw the last exception if the number of retries exceeds the maximum. + throw lastException; + } + + // Sleep 100 milliseconds before retrying the transaction. + TimeUnit.MILLISECONDS.sleep(100); + } + + DistributedTransaction transaction = null; + try { + // Begin a transaction. + transaction = transactionManager.begin(); + + // Execute CRUD operations in the transaction. + Optional result = transaction.get(...); + List results = transaction.scan(...); + transaction.put(...); + transaction.delete(...); + + // Commit the transaction. + transaction.commit(); + } catch (UnsatisfiedConditionException e) { + // You need to handle `UnsatisfiedConditionException` only if a mutation operation specifies a condition. + // This exception indicates the condition for the mutation operation is not met. + + try { + transaction.rollback(); + } catch (RollbackException ex) { + // Rolling back the transaction failed. Since the transaction should eventually recover, + // you don't need to do anything further. You can simply log the occurrence here. + } + + // You can handle the exception here, according to your application requirements. + + return; + } catch (UnknownTransactionStatusException e) { + // If you catch `UnknownTransactionStatusException` when committing the transaction, + // it indicates that the status of the transaction, whether it was successful or not, is unknown. + // In such a case, you need to check if the transaction is committed successfully or not and + // retry the transaction if it failed. How to identify a transaction status is delegated to users. + return; + } catch (TransactionException e) { + // For other exceptions, you can try retrying the transaction. + + // For `CrudConflictException`, `CommitConflictException`, and `TransactionNotFoundException`, + // you can basically retry the transaction. However, for the other exceptions, the transaction + // will still fail if the cause of the exception is non-transient. In such a case, you will + // exhaust the number of retries and throw the last exception. + + if (transaction != null) { + try { + transaction.rollback(); + } catch (RollbackException ex) { + // Rolling back the transaction failed. The transaction should eventually recover, + // so you don't need to do anything further. You can simply log the occurrence here. + } + } + + lastException = e; + } + } + } +} +``` + +### `TransactionException` および `TransactionNotFoundException` + +`begin()` API は `TransactionException` または `TransactionNotFoundException` をスローする可能性があります: + +- `TransactionException` をキャッチした場合、この例外は、一時的または非一時的障害が原因でトランザクションを開始できなかったことを示します。トランザクションを再試行することはできますが、非一時的障害が原因でトランザクションを開始できない可能性があります。 +- `TransactionNotFoundException` をキャッチした場合、この例外は、一時的障害が原因でトランザクションを開始できなかったことを示します。この場合、トランザクションを再試行できます。 + +`join()` API も `TransactionNotFoundException` をスローする可能性があります。この例外は、`begin()` API の例外を処理するのと同じ方法で処理できます。 + +### `CrudException` および `CrudConflictException` + +CRUD 操作の API (`get()`、`scan()`、`put()`、`delete()`、および `mutate()`) は、`CrudException` または `CrudConflictException` をスローする可能性があります: + +- `CrudException` をキャッチした場合、この例外は、一時的または非一時的障害が原因でトランザクション CRUD 操作が失敗したことを示します。トランザクションを最初から再試行できますが、原因が非一時的である場合は、トランザクションが失敗する可能性があります。 +- `CrudConflictException` をキャッチした場合、この例外は、一時的な障害 (競合エラーなど) が原因でトランザクション CRUD 操作が失敗したことを示します。この場合、トランザクションを最初から再試行できます。 + +### `UnsatisfiedConditionException` + +ミューテーション操作の API (`put()`、`delete()`、および `mutate()`) も `UnsatisfiedConditionException` をスローする可能性があります。 + +`UnsatisfiedConditionException` をキャッチした場合、この例外はミューテーション操作の条件が満たされていないことを示します。この例外は、アプリケーションの要件に従って処理できます。 + +### `CommitException`、`CommitConflictException`、および `UnknownTransactionStatusException` + +`commit()` API は `CommitException`、`CommitConflictException`、または `UnknownTransactionStatusException` をスローする可能性があります。 + +- `CommitException` をキャッチした場合、この例外は、一時的または非一時的障害が原因でトランザクションのコミットが失敗したことを示します。トランザクションを最初から再試行できますが、原因が非一時的である場合はトランザクションが失敗する可能性があります。 +- `CommitConflictException` をキャッチした場合、この例外は、一時的な障害 (競合エラーなど) が原因でトランザクションのコミットが失敗したことを示します。この場合、トランザクションを最初から再試行できます。 +- `UnknownTransactionStatusException` をキャッチした場合、この例外は、トランザクションのステータス (成功したかどうか) が不明であることを示します。この場合、トランザクションが正常にコミットされたかどうかを確認し、失敗した場合はトランザクションを再試行する必要があります。 + +トランザクションステータスを識別する方法は、ユーザーに委任されています。トランザクションステータステーブルを作成し、他のアプリケーションデータを使用してトランザクション的に更新して、ステータステーブルからトランザクションのステータスを取得できるようにすることができます。 + +### 一部の例外に関する注意 + +サンプルコードには示されていませんが、`resume()` API は `TransactionNotFoundException` をスローする可能性もあります。この例外は、指定された ID に関連付けられたトランザクションが見つからなかったか、トランザクションの有効期限が切れた可能性があることを示します。いずれの場合も、この例外の原因は基本的に一時的なものであるため、トランザクションを最初から再試行できます。 + +サンプルコードでは、`UnknownTransactionStatusException` の場合、重複操作の可能性を回避するためにアプリケーションがトランザクションが成功したかどうかを確認する必要があるため、トランザクションは再試行されません。その他の例外の場合、例外の原因が一時的または非一時的であるため、トランザクションは再試行されます。例外の原因が一時的な場合、再試行するとトランザクションが成功する可能性があります。ただし、例外の原因が非一時的である場合、再試行してもトランザクションは失敗します。このような場合、再試行回数を使い果たします。 + +:::note + +サンプルコードでは、トランザクションは最大3回再試行され、再試行される前に100ミリ秒間スリープします。ただし、アプリケーションの要件に応じて、指数バックオフなどの再試行ポリシーを選択できます。 + +::: + +## Coordinator テーブルのグループコミット + +Consensus Commit トランザクションに使用される Coordinator テーブルは重要なデータストアであり、堅牢なストレージを使用することをお勧めします。ただし、内部でマルチ AZ またはマルチリージョンレプリケーションを活用するなど、より堅牢なストレージオプションを使用すると、ストレージにレコードを書き込むときにレイテンシが増加し、スループットパフォーマンスが低下する可能性があります。 + +ScalarDB は、Coordinator テーブルにグループコミット機能を提供します。この機能は、複数のレコードの書き込みを1つの書き込み操作にグループ化し、書き込みスループットを向上させます。この場合、基盤となるデータベースとワークロードに応じて、レイテンシが増加または減少する可能性があります。 + +グループコミット機能を有効にするには、次の設定を追加します。 + +```properties +# By default, this configuration is set to `false`. +scalar.db.consensus_commit.coordinator.group_commit.enabled=true + +# These properties are for tuning the performance of the group commit feature. +# scalar.db.consensus_commit.coordinator.group_commit.group_size_fix_timeout_millis=40 +# scalar.db.consensus_commit.coordinator.group_commit.delayed_slot_move_timeout_millis=800 +# scalar.db.consensus_commit.coordinator.group_commit.old_group_abort_timeout_millis=30000 +# scalar.db.consensus_commit.coordinator.group_commit.timeout_check_interval_millis=10 +# scalar.db.consensus_commit.coordinator.group_commit.metrics_monitor_log_enabled=true +``` + +### 制限事項 + +このセクションでは、グループコミット機能の制限事項について説明します。 + +#### ユーザーが渡したカスタムトランザクション ID + +グループコミット機能は、内部値を暗黙的に生成し、それをトランザクション ID の一部として使用します。したがって、ユーザーが `com.scalar.db.transaction.consensuscommit.ConsensusCommitManager.begin(String txId)` または `com.scalar.db.transaction.consensuscommit.TwoPhaseConsensusCommitManager.begin(String txId)` を介して手動で渡したカスタムトランザクション ID は、その後の API 呼び出しでそのまま使用することはできません。代わりに、`com.scalar.db.transaction.consensuscommit.ConsensusCommit.getId()` または `com.scalar.db.transaction.consensuscommit.TwoPhaseConsensusCommit.getId()` から返されたトランザクション ID を使用する必要があります。 + +```java + // This custom transaction ID needs to be used for ScalarDB transactions. + String myTxId = UUID.randomUUID().toString(); + + ... + + DistributedTransaction transaction = manager.begin(myTxId); + + ... + + // When the group commit feature is enabled, a custom transaction ID passed by users can't be used as is. + // logger.info("The transaction state: {}", manager.getState(myTxId)); + logger.info("The transaction state: {}", manager.getState(transaction.getId())); +``` + +#### 2フェーズコミットインターフェースでの使用の禁止 + +グループコミット機能は、進行中のすべてのトランザクションをメモリ内で管理します。この機能が2フェーズコミットインターフェースで有効になっている場合、Coordinator テーブルへの参加者サービスの一貫性のない書き込みによって生じる競合 (グループ間で異なるトランザクション分散が含まれる場合があります) を防ぐために、情報は Coordinator サービスによってのみ維持される必要があります。 + +この制限により、アプリケーション開発に関連する複雑さと柔軟性が損なわれます。したがって、グループコミット機能と2フェーズコミットインターフェースを組み合わせて使用​​することは現在禁止されています。 + +## Consensus Commit トランザクションマネージャーエラーの調査 + +Consensus Commit トランザクションマネージャーの使用時にエラーを調査するには、トランザクションメタデータ列が追加されたテーブルメタデータを返す設定を有効にできます。これは、トランザクション関連の問題を調査するときに役立ちます。この設定は、Consensus Commit トランザクションマネージャーのトラブルシューティング時にのみ使用可能で、`DistributedTransactionAdmin.getTableMetadata()` メソッドを使用して、特定のテーブルのトランザクションメタデータ列の詳細を表示できます。 + +次の設定を追加すると、`Get` および `Scan` 操作の結果に [トランザクションメタデータ](schema-loader.mdx#consensus-commit-の内部メタデータ)が含まれます。 + +```properties +# By default, this configuration is set to `false`. +scalar.db.consensus_commit.include_metadata.enabled=true +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/backup-restore.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/backup-restore.mdx new file mode 100644 index 00000000..fdf2b878 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/backup-restore.mdx @@ -0,0 +1,181 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB で使用されるデータベースのバックアップと復元方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB は非トランザクションデータベースまたはトランザクションデータベース上で非侵入的にトランザクション機能を提供するため、トランザクション的に一貫性のある方法でデータベースをバックアップおよび復元するには特別な注意が必要です。 + +このガイドでは、ScalarDB がサポートするデータベースをバックアップおよび復元する方法について説明します。 + +## バックアップを作成する + +バックアップの作成方法は、使用しているデータベースと、複数のデータベースを使用しているかどうかによって異なります。次の決定ツリーは、どのアプローチを取るべきかを示しています。 + +```mermaid +flowchart TD + A[ScalarDB で単一のデータベースを使用していますか?] + A -->|はい| B[データベースはトランザクションをサポートしていますか?] + B -->|はい| C[明示的に一時停止せずにバックアップを実行します] + B ---->|いいえ| D[明示的な一時停止を伴うバックアップを実行します] + A ---->|いいえ| D +``` + +### 明示的に一時停止せずにバックアップする + +トランザクションをサポートする単一のデータベースで ScalarDB を使用している場合は、ScalarDB がトランザクションを受け入れ続けている間でも、データベースのバックアップを作成できます。 + +:::warning + +バックアップを作成する前に、データベースのトランザクション的に一貫性のあるバックアップを作成する最も安全な方法を検討し、バックアッププロセスに関連するリスクを理解する必要があります。 + +::: + +ScalarDB でバックアップを作成するための要件の1つは、ScalarDB が管理するすべてのテーブル (Coordinator テーブルを含む) のバックアップがトランザクション的に一貫しているか、トランザクション的に一貫した状態に自動的に回復可能である必要があることです。つまり、すべてのテーブルを1回のトランザクションでダンプして、一貫性のあるバックアップを作成する必要があります。 + +トランザクション的に一貫性のあるバックアップを作成する方法は、使用しているデータベースの種類によって異なります。データベースを選択して、ScalarDB のトランザクション的に一貫性のあるバックアップを作成する方法を確認してください。 + +:::note + +以下にリストされているデータベース別のバックアップ方法は、ScalarDB がサポートするデータベースの一部の例にすぎません。 + +::: + + + + 自動バックアップ機能を使用すると、バックアップ保持期間内の任意の時点に復元できます。 + + + `--single-transaction` オプションを指定した `mysqldump` コマンドを使用します。 + + + `pg_dump` コマンドを使用します。 + + + [Special commands to sqlite3 (dot-commands)](https://www.sqlite.org/cli.html#special_commands_to_sqlite3_dot_commands_) で指定されているように、`.backup` コマンドを `.timeout` コマンドとともに使用します。 + + 例については、[BASH: SQLite3 .backup command](https://stackoverflow.com/questions/23164445/bash-sqlite3-backup-command) を参照してください。 + + + クラスターはバックアップポリシーに基づいて自動的にバックアップされ、これらのバックアップは特定の期間保持されます。オンデマンドバックアップを実行することもできます。バックアップの実行の詳細については、[YugabyteDB Managed: Back up and restore clusters](https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-clusters/backup-clusters/)を参照してください。 + + + +### 明示的に一時停止してバックアップする + +トランザクション的に一貫性のあるバックアップを作成する別の方法は、ScalarDB インスタンスのクラスターに未処理のトランザクションがないときにバックアップを作成することです。バックアップの作成は、次の条件によって異なります。 + +- 基盤となるデータベースにポイントインタイムスナップショットまたはバックアップ機能がある場合は、未処理のトランザクションが存在しない期間にバックアップを作成できます。 +- 基盤となるデータベースにポイントインタイムリストアまたはリカバリ (PITR) 機能がある場合は、一時停止期間内の未処理のトランザクションが存在しない時間 (できれば中間時間) にリストアポイントを設定できます。 + +:::note + +PITR 機能を使用する場合は、NTP などのクロック同期を使用して、クライアントとサーバー間のクロックのずれを最小限に抑える必要があります。そうしないと、一時停止期間として取得される時間が、一時停止が実際に行われた時間と大きく異なる可能性があり、バックアップが進行中のトランザクションが存在する時点に復元される可能性があります。 + +また、クロック同期ではノード間のクロックを完全に同期できないため、十分な時間 (たとえば、5秒) 一時停止し、一時停止期間の中間時間を復元ポイントとして使用する必要があります。 + +::: + +ScalarDB が未処理のリクエストを排出し、新しいリクエストの受け入れを停止して一時停止期間を作成できるようにするには、ScalarDB を使用するアプリケーションで [Scalar Admin](https://github.com/scalar-labs/scalar-admin) インターフェースを適切に実装するか、Scalar Admin インターフェースを実装する [ScalarDB Cluster](scalardb-cluster/index.mdx) を使用する必要があります。 + +[Scalar Admin クライアントツール](https://github.com/scalar-labs/scalar-admin/blob/main/README.md#scalar-admin-client-tool)を使用すると、進行中のトランザクションを失うことなく、Scalar Admin インターフェースを実装するノード、サーバー、またはアプリケーションを一時停止できます。 + +トランザクション的に一貫性のあるバックアップを作成する方法は、使用しているデータベースの種類によって異なります。データベースを選択して、ScalarDB のトランザクション的に一貫性のあるバックアップを作成する方法を確認します。 + +:::note + +以下にリストされているデータベース別のバックアップ方法は、ScalarDB がサポートするデータベースの一部の例にすぎません。 + +::: + + + + DynamoDB テーブルに対して PITR 機能を有効にする必要があります。[ScalarDB Schema Loader](schema-loader.mdx) を使用してスキーマを作成する場合、ツールはデフォルトでテーブルの PITR 機能を有効にします。 + + トランザクション的に一貫性のある復元ポイントを指定するには、[明示的な一時停止によるバックアップ](#明示的に一時停止してバックアップする)の説明に従って、ScalarDB を DynamoDB とともに使用しているアプリケーションを一時停止します。 + + + PITR 機能が有効になっている継続的バックアップポリシーを使用して、Cosmos DB for NoSQL アカウントを作成する必要があります。この機能を有効にすると、バックアップが継続的に作成されます。 + + トランザクション的に一貫性のある復元ポイントを指定するには、[明示的に一時停止してバックアップする](#明示的に一時停止してバックアップする)の説明に従って、ScalarDB を Cosmos DB for NoSQL とともに使用しているアプリケーションを一時停止します。 + + + Cassandra にはレプリケーション機能が組み込まれているため、必ずしもトランザクション的に一貫性のあるバックアップを作成する必要はありません。たとえば、レプリケーション係数が `3` に設定されていて、Cassandra クラスター内のノードの1つのデータのみが失われた場合、通常のトランザクション的に一貫性のないバックアップ (スナップショット) と修復機能を使用してノードを回復できるため、トランザクション的に一貫性のあるバックアップ (スナップショット) は必要ありません。 + + ただし、クラスターノードのクォーラムでデータが失われた場合は、クラスターを特定のトランザクション的に一貫性のあるポイントに復元するために、トランザクション的に一貫性のあるバックアップ (スナップショット) が必要になります。 + + トランザクション的に一貫性のあるクラスター全体のバックアップ (スナップショット) を作成するには、ScalarDB または [ScalarDB Cluster](scalardb-cluster/index.mdx) を使用しているアプリケーションを一時停止し、[明示的な一時停止によるバックアップ](#明示的に一時停止してバックアップする)の説明に従ってノードのバックアップ (スナップショット) を作成するか、Cassandra クラスターを停止してノード内のすべてのデータのコピーを作成し、クラスターを起動します。 + + + 一時停止期間中にオンデマンドバックアップまたはスケジュールされたバックアップを実行できます。バックアップの実行の詳細については、[YugabyteDB Managed: Back up and restore clusters](https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-clusters/backup-clusters/) を参照してください。 + + + +## バックアップを復元する + +トランザクション的に一貫性のあるバックアップを復元する方法は、使用しているデータベースの種類によって異なります。データベースを選択して、ScalarDB のトランザクション的に一貫性のあるバックアップを作成する方法を確認してください。 + +:::note + +以下にリストされているデータベース別の復元方法は、ScalarDB がサポートするデータベースの一部の例にすぎません。 + +::: + + + + 自動バックアップ機能を使用すると、バックアップ保持期間内の任意の時点に復元できます。 + + + まず、Cassandra クラスターのすべてのノードを停止します。次に、`data`、`commitlog`、`hints` ディレクトリをクリーンアップし、各ノードにバックアップ (スナップショット) を配置します。 + + 各ノードにバックアップ (スナップショット) を配置したら、Cassandra クラスターのすべてのノードを起動します。 + + + [Azure portal を使用してアカウントを復元する](https://docs.microsoft.com/ja-jp/azure/cosmos-db/restore-account-continuous-backup#restore-account-portal)については、Azure の公式ドキュメントに従ってください。バックアップを復元した後、復元されたデータベースの [既定の整合性レベルを構成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)を `STRONG` に設定します。さらに、前述のように、一時停止期間の中間時点を復元ポイントとして使用する必要があります。 + + ScalarDB は、ScalarDB Schema Loader を使用してスキーマを作成するときにインストールされるストアドプロシージャを使用して、Cosmos DB アダプターを実装します。ただし、Cosmos DB の PITR 機能では、ストアドプロシージャは復元されません。このため、復元後にすべてのテーブルに必要なストアドプロシージャを再インストールする必要があります。これは、ScalarDB Schema Loader を `--repair-all` オプションとともに使用することで実行できます。詳細については、[名前空間とテーブルを修復する](schema-loader.mdx#名前空間とテーブルを修復する)を参照してください。 + + + [DynamoDB テーブルを特定の時点に復元](https://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/PointInTimeRecovery.Tutorial.html)については、公式の AWS ドキュメントに従ってください。ただし、テーブルはエイリアスを使用してのみ復元できることに注意してください。このため、エイリアスを使用してテーブルを復元し、元のテーブルを削除して、エイリアスを元の名前に変更し、同じ名前のテーブルを復元する必要があります。 + + この手順を実行するには、次の手順を実行します。 + + 1. バックアップを作成します。 + 1. 一時停止期間の中間時点を復元ポイントとして選択します。 + 2. テーブル A の PITR を使用してテーブル B に復元します。 + 3. 復元されたテーブル B のバックアップを作成します (バックアップの名前がバックアップ B であると仮定します)。 + 4. テーブル B を削除します。 + 2. バックアップを復元します。 + 1. テーブル A を削除します。 + 2. バックアップ B を使用して A という名前のテーブルを作成します。 + +:::note + +* テーブルは一度に1つしか復元できないため、上記の手順はテーブルごとに実行する必要があります。 +* 復元されたテーブルでは、PITR や自動スケーリングポリシーなどの設定がデフォルト値にリセットされるため、必要な設定を手動で行う必要があります。詳細については、公式 AWS ドキュメントの [DynamoDB を使用した DynamoDB テーブルのバックアップと復元の仕組み](https://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/CreateBackup.html#CreateBackup_HowItWorks-restore)を参照してください。 + +::: + + + `mysqldump` を使用してバックアップファイルを作成した場合は、[Reloading SQL-Format Backups](https://dev.mysql.com/doc/mysql-backup-excerpt/8.0/en/reloading-sql-format-dumps.html) で指定されているように、`mysql` コマンドを使用してバックアップを復元します。 + + + `pg_dump` を使用してバックアップファイルを作成した場合は、[Restoring the Dump](https://www.postgresql.org/docs/current/backup-dump.html#BACKUP-DUMP-RESTORE) で指定されているように、`psql` コマンドを使用してバックアップを復元します。 + + + [Special commands to sqlite3 (dot-commands)](https://www.sqlite.org/cli.html#special_commands_to_sqlite3_dot_commands_) で指定されているように、`.restore` コマンドを使用します。 + + + バックアップ保持期間内であれば、スケジュールされたバックアップまたはオンデマンドバックアップから復元できます。バックアップの実行の詳細については、[YugabyteDB Managed: Back up and restore clusters](https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-clusters/backup-clusters/) を参照してください。 + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/configurations.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/configurations.mdx new file mode 100644 index 00000000..732ecf34 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/configurations.mdx @@ -0,0 +1,297 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB の設定 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB で使用可能な設定について説明します。 + +## ScalarDB クライアントの設定 + +このセクションでは、ScalarDB クライアントの設定について説明します。ScalarDB は、Consensus Commit を使用してトランザクションを実行する方法、非トランザクションストレージ操作を実行する方法、および ScalarDB Cluster を介してトランザクションを実行する方法を提供します。 + +### Consensus Commit を使用してトランザクションを実行する + +ScalarDB は、Consensus Commit と呼ばれる独自のトランザクションプロトコルを提供します。これは、ScalarDB のデフォルトのトランザクションマネージャータイプです。Consensus Commit トランザクションマネージャーを使用するには、ScalarDB プロパティファイルに次の内容を追加します。 + +```properties +scalar.db.transaction_manager=consensus-commit +``` + +:::note + +`scalar.db.transaction_manager` プロパティを指定しない場合は、`consensus-commit` がデフォルト値になります。 + +::: + +#### 基本設定 + +Consensus Commit トランザクションマネージャーでは、次の基本設定が利用可能です。 + +| 名前 | 説明 | デフォルト | +|-------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------| +| `scalar.db.transaction_manager` | `consensus-commit` を指定する必要があります。 | - | +| `scalar.db.consensus_commit.isolation_level` | Consensus Commit に使用される分離レベル。`SNAPSHOT` または `SERIALIZABLE` のいずれかを指定できます。 | `SNAPSHOT` | +| `scalar.db.consensus_commit.serializable_strategy` | Consensus Commit に使用されるシリアル化可能な戦略。`EXTRA_READ` または `EXTRA_WRITE` のいずれかを指定できます。`scalar.db.consensus_commit.isolation_level` プロパティで `SNAPSHOT` が指定されている場合、この設定は無視されます。 | `EXTRA_READ` | +| `scalar.db.consensus_commit.coordinator.namespace` | Coordinator テーブルの名前空間名。 | `coordinator` | +| `scalar.db.consensus_commit.include_metadata.enabled` | `true` に設定すると、`Get` および `Scan` 操作の結果にトランザクションメタデータが含まれます。特定のテーブルのトランザクションメタデータ列の詳細を表示するには、`DistributedTransactionAdmin.getTableMetadata()` メソッドを使用します。このメソッドは、トランザクションメタデータ列が追加されたテーブルメタデータを返します。この設定を使用すると、トランザクション関連の問題を調査するのに役立ちます。 | `false` | + +#### パフォーマンス関連の設定 + +Consensus Commit トランザクションマネージャーでは、次のパフォーマンス関連の設定が利用できます。 + +| 名前 | 説明 | デフォルト | +|----------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------| +| `scalar.db.consensus_commit.parallel_executor_count` | 並列実行のためのエグゼキュータ (スレッド) の数。この数値は、ScalarDB Cluster ノード内または ScalarDB プロセス内のトランザクション全体のスレッド数の合計を示します。 | `128` | +| `scalar.db.consensus_commit.parallel_preparation.enabled` | 準備フェーズが並行して実行されるかどうか。 | `true` | +| `scalar.db.consensus_commit.parallel_validation.enabled` | 検証フェーズ (`EXTRA_READ` 内) が並列で実行されるかどうか。 | `scalar.db.consensus_commit.parallel_commit.enabled` の値 | +| `scalar.db.consensus_commit.parallel_commit.enabled` | コミットフェーズが並列で実行されるかどうか。 | `true` | +| `scalar.db.consensus_commit.parallel_rollback.enabled` | ロールバックフェーズが並列で実行されるかどうか。 | `scalar.db.consensus_commit.parallel_commit.enabled` の値 | +| `scalar.db.consensus_commit.async_commit.enabled` | コミットフェーズが非同期で実行されるかどうか。 | `false` | +| `scalar.db.consensus_commit.async_rollback.enabled` | ロールバックフェーズが非同期に実行されるかどうか。 | `scalar.db.consensus_commit.async_commit.enabled` の値 | +| `scalar.db.consensus_commit.parallel_implicit_pre_read.enabled` | 暗黙的な事前読み取りが並列で実行されるかどうか。 | `true` | +| `scalar.db.consensus_commit.coordinator.group_commit.enabled` | トランザクション状態のコミットがバッチモードで実行されるかどうか。この機能は、2フェーズコミットインターフェイスでは使用できません。 | `false` | +| `scalar.db.consensus_commit.coordinator.group_commit.slot_capacity` | グループコミット機能のグループ内のスロットの最大数。値が大きいとグループコミットの効率は向上しますが、待ち時間が増加し、トランザクションの競合が発生する可能性も高くなります。[^1] | `20` | +| `scalar.db.consensus_commit.coordinator.group_commit.group_size_fix_timeout_millis` | グループ内のスロットのサイズを固定するためのタイムアウト。値が大きいとグループコミットの効率が向上しますが、待ち時間が増加し、トランザクションの競合が発生する可能性も高くなります。[^1] | `40` | +| `scalar.db.consensus_commit.coordinator.group_commit.delayed_slot_move_timeout_millis` | 遅延スロットをグループから別の分離グループに移動して、元のグループが遅延トランザクションの影響を受けないようにするためのタイムアウト。値が大きいとグループコミットの効率が向上しますが、待ち時間が増加し、トランザクションの競合が発生する可能性も高くなります。[^1] | `1200` | +| `scalar.db.consensus_commit.coordinator.group_commit.old_group_abort_timeout_millis` | 進行中の古いグループをアボートするためのタイムアウト。値が小さいと、積極的なアボートによってリソースの消費量が減りますが、長時間実行されるトランザクションで不要なアボートが発生する可能性も高くなります。 | `60000` | +| `scalar.db.consensus_commit.coordinator.group_commit.timeout_check_interval_millis` | グループコミット関連のタイムアウトをチェックする間隔。 | `20` | +| `scalar.db.consensus_commit.coordinator.group_commit.metrics_monitor_log_enabled` | グループコミットのメトリックが定期的にログに記録されるかどうか。 | `false` | + +#### 基盤となるストレージまたはデータベースの設定 + +Consensus Commit にはストレージ抽象化レイヤーがあり、複数の基盤となるストレージをサポートしています。`scalar.db.storage` プロパティを使用してストレージ実装を指定できます。 + +データベースを選択して、各ストレージで使用可能な設定を確認します。 + + + + JDBC データベースでは次の設定を使用できます。 + + | 名前 | 説明 | デフォルト | + |-----------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------| + | `scalar.db.storage` | `jdbc` を指定する必要があります。 | - | + | `scalar.db.contact_points` | JDBC 接続 URL。 | | + | `scalar.db.username` | データベースにアクセスするためのユーザー名。 | | + | `scalar.db.password` | データベースにアクセスするためのパスワード。 | | + | `scalar.db.jdbc.connection_pool.min_idle` | 接続プール内のアイドル接続の最小数。 | `20` | + | `scalar.db.jdbc.connection_pool.max_idle` | 接続プール内でアイドル状態のままにできる接続の最大数。 | `50` | + | `scalar.db.jdbc.connection_pool.max_total` | 接続プールで同時にアクティブにできるアイドル接続と借用接続の最大合計数。制限がない場合は負の値を使用します。 | `100` | + | `scalar.db.jdbc.prepared_statements_pool.enabled` | このプロパティを `true` に設定すると、準備済みステートメントプーリングが有効になります。 | `false` | + | `scalar.db.jdbc.prepared_statements_pool.max_open` | ステートメントプールから同時に割り当てることができるオープンステートメントの最大数。制限がない場合は負の値を使用します。 | `-1` | + | `scalar.db.jdbc.isolation_level` | JDBC の分離レベル。`READ_UNCOMMITTED`、`READ_COMMITTED`、`REPEATABLE_READ`、または `SERIALIZABLE` を指定できます。 | 基盤データベース固有 | + | `scalar.db.jdbc.table_metadata.connection_pool.min_idle` | テーブルメタデータの接続プール内のアイドル接続の最小数。 | `5` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_idle` | テーブルメタデータの接続プール内でアイドル状態のままにできる接続の最大数。 | `10` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_total` | テーブルメタデータの接続プールで同時にアクティブにできるアイドル接続と借用接続の最大合計数。制限がない場合は負の値を使用します。 | `25` | + | `scalar.db.jdbc.admin.connection_pool.min_idle` | 管理者の接続プール内のアイドル接続の最小数。 | `5` | + | `scalar.db.jdbc.admin.connection_pool.max_idle` | 管理者の接続プール内でアイドル状態のままにできる接続の最大数。 | `10` | + | `scalar.db.jdbc.admin.connection_pool.max_total` | 管理者の接続プールで同時にアクティブにできるアイドル接続と借用接続の最大合計数。制限がない場合は負の値を使用します。 | `25` | + | `scalar.db.jdbc.mysql.variable_key_column_size` | MySQL で主キーまたはセカンダリキーとして使用される場合の TEXT 列と BLOB 列の列サイズ。最小 64 バイト。 | `128` | + | `scalar.db.jdbc.oracle.variable_key_column_size` | Oracle で主キーまたはセカンダリキーとして使用される場合の TEXT 列と BLOB 列の列サイズ。最小 64 バイト。 | `128` | + | `scalar.db.jdbc.oracle.time_column.default_date_component` | Oracle で `TIME` データを格納するために使用される日付コンポーネントの値。Oracle には日付コンポーネントなしで時間のみを格納するデータ型がないため、ScalarDB は比較と並べ替えを容易にするために、同じ日付コンポーネント値を持つ `TIME` データを保存します。 | `1970-01-01` | + +:::note + +#### SQLite3 + +SQLite3 を JDBC データベースとして使用している場合は、`scalar.db.contact_points` を次のように設定する必要があります。 + +```properties +scalar.db.contact_points=jdbc:sqlite:?busy_timeout=10000 +``` + +他の JDBC データベースとは異なり、[SQLite3 doesn't fully support concurrent access](https://www.sqlite.org/lang_transaction.html)。[`SQLITE_BUSY`](https://www.sqlite.org/rescode.html#busy) によって内部的に頻繁に発生するエラーを回避するには、[`busy_timeout`](https://www.sqlite.org/c3ref/busy_timeout.html) パラメータを設定することをお勧めします。 + +#### YugabyteDB + +YugabyteDB を JDBC データベースとして使用している場合は、次のように `scalar.db.contact_points` で複数のエンドポイントを指定できます。 + +```properties +scalar.db.contact_points=jdbc:yugabytedb://127.0.0.1:5433\\,127.0.0.2:5433\\,127.0.0.3:5433/?load-balance=true +``` + +複数のエンドポイントはエスケープされたコンマで区切る必要があります。 + +YugabyteDB のスマートドライバーと負荷分散の詳細については、[YugabyteDB smart drivers for YSQL](https://docs.yugabyte.com/preview/drivers-orms/smart-drivers/) を参照してください。 + +::: + + + + DynamoDB では次の設定が利用可能です。 + + | 名前 | 説明 | デフォルト | + |--------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------| + | `scalar.db.storage` | `dynamo` を指定する必要があります。 | - | + | `scalar.db.contact_points` | ScalarDB が通信する AWS リージョン (例: `us-east-1`)。 | | + | `scalar.db.username` | AWS とやり取りするユーザーを識別するために使用される AWS アクセスキー。 | | + | `scalar.db.password` | AWS と対話するユーザーを認証するために使用される AWS シークレットアクセスキー。 | | + | `scalar.db.dynamo.endpoint_override` | ScalarDB が通信する Amazon DynamoDB エンドポイント。これは主に、AWS サービスではなくローカルインスタンスでのテストに使用されます。 | | + | `scalar.db.dynamo.namespace.prefix` | ユーザー名前空間とメタデータ名前空間名のプレフィックス。AWS では単一の AWS リージョン内で一意のテーブル名を持つ必要があるため、単一の AWS リージョン内で複数の ScalarDB 環境 (開発、本番など) を使用する場合に便利です。 | | + + + Cosmos DB for NoSQL では次の設定が利用可能です。 + + | 名前 | 説明 | デフォルト | + |--------------------------------------|------------------------------------------------------------------------------------------------------------|-----------| + | `scalar.db.storage` | `cosmos` を指定する必要があります。 | - | + | `scalar.db.contact_points` | ScalarDB が通信する NoSQL エンドポイント用の Azure Cosmos DB。 | | + | `scalar.db.password` | Azure Cosmos DB for NoSQL にアクセスするための認証を実行するために使用されるマスターキーまたは読み取り専用キーのいずれか。 | | + | `scalar.db.cosmos.consistency_level` | Cosmos DB 操作に使用される一貫性レベル。`STRONG` または `BOUNDED_STALENESS` を指定できます。 | `STRONG` | + + + Cassandra では次の設定が利用可能です。 + + | 名前 | 説明 | デフォルト | + |----------------------------|--------------------------------------|----------| + | `scalar.db.storage` | `cassandra` を指定する必要があります。 | - | + | `scalar.db.contact_points` | カンマで区切られた連絡先。 | | + | `scalar.db.contact_port` | すべての連絡先ポイントのポート番号。 | | + | `scalar.db.username` | データベースにアクセスするためのユーザー名。 | | + | `scalar.db.password` | データベースにアクセスするためのパスワード。 | | + + + +##### マルチストレージのサポート + +ScalarDB は、複数のストレージ実装の同時使用をサポートしています。`scalar.db.storage` プロパティの値として `multi-storage` を指定することで、複数のストレージを使用できます。 + +複数のストレージの使用の詳細については、[マルチストレージトランザクション](multi-storage-transactions.mdx)を参照してください。 + +##### クロスパーティションスキャン設定 + +以下で説明するようにクロスパーティションスキャンオプションを有効にすると、`Scan` 操作でパーティション全体のすべてのレコードを取得できます。さらに、`cross_partition_scan.filtering` と `cross_partition_scan.ordering` をそれぞれ有効にすることで、クロスパーティション `Scan` 操作で任意の条件と順序を指定できます。現在、順序付けオプション付きのクロスパーティションスキャンは、JDBC データベースでのみ使用できます。フィルタリングと順序付けを有効にするには、`scalar.db.cross_partition_scan.enabled` を `true` に設定する必要があります。 + +クロスパーティションスキャンの使用方法の詳細については、[`Scan` 操作](./api-guide.mdx#scan-操作)を参照してください。 + +:::warning + +非 JDBC データベースの場合、`SERIALIZABLE` 分離レベルでクロスパーティションスキャンを有効にした場合でも、トランザクションは読み取りコミットスナップショット分離 (`SNAPSHOT`) で実行される可能性があります。これは、より低い分離レベルです。非 JDBC データベースを使用する場合は、トランザクションの一貫性が重要でない場合にのみ、クロスパーティションスキャンを使用してください。 + +::: + +| 名前 | 説明 | デフォルト | +|----------------------------------------------------|---------------------------------------------------|----------| +| `scalar.db.cross_partition_scan.enabled` | パーティション間スキャンを有効にします。 | `false` | +| `scalar.db.cross_partition_scan.filtering.enabled` | クロスパーティションスキャンでフィルタリングを有効にします。 | `false` | +| `scalar.db.cross_partition_scan.ordering.enabled` | パーティション間スキャンでの順序付けを有効にします。 | `false` | + +### 非トランザクションストレージ操作を実行する + +非トランザクションストレージ操作を実行するには、`scalar.db.transaction_manager` プロパティを `single-crud-operation` に設定する必要があります。 + +```properties +scalar.db.transaction_manager=single-crud-operation +``` + +また、[基盤となるストレージまたはデータベースの設定](#基盤となるストレージまたはデータベースの設定)の説明に従って、基盤となるストレージまたはデータベースを設定する必要があります。 + +### ScalarDB Cluster を介してトランザクションを実行する + +[ScalarDB Cluster](scalardb-cluster/index.mdx) は、ScalarDB に gRPC インターフェースを提供するコンポーネントです。 + +クライアント設定の詳細については、[ScalarDB Cluster クライアント設定](scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#クライアント設定)を参照してください。 + +## その他の ScalarDB 設定 + +ScalarDB で使用できる追加の設定は次のとおりです。 + +| 名前 | 説明 | デフォルト | +|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------| +| `scalar.db.metadata.cache_expiration_time_secs` | ScalarDB には、データベースへのリクエスト数を減らすためのメタデータキャッシュがあります。この設定では、キャッシュの有効期限を秒単位で指定します。`-1`を指定した場合は、キャッシュは期限切れになりません。 | `60` | +| `scalar.db.active_transaction_management.expiration_time_millis` | ScalarDB は進行中のトランザクションを維持し、トランザクション ID を使用して再開できます。この設定は、このトランザクション管理機能の有効期限をミリ秒単位で指定します。 | `-1` (有効期限なし) | +| `scalar.db.default_namespace_name` | 指定された名前空間名は、名前空間を指定していない操作によって使用されます。 | | +| `scalar.db.system_namespace_name` | 指定された名前空間名は ScalarDB によって内部的に使用されます。 | `scalardb` | + +## プレースホルダーの使用 + +値にプレースホルダーを使用できます。プレースホルダーは環境変数 (`${env:}`) またはシステムプロパティ (`${sys:}`) に置き換えられます。また、`${sys::-}` のようにプレースホルダーにデフォルト値を指定することもできます。 + +以下は、プレースホルダーを使用する設定の例です。 + +```properties +scalar.db.username=${env:SCALAR_DB_USERNAME:-admin} +scalar.db.password=${env:SCALAR_DB_PASSWORD} +``` + +この設定例では、ScalarDB は環境変数からユーザー名とパスワードを読み取ります。環境変数 `SCALAR_DB_USERNAME` が存在しない場合、ScalarDB はデフォルト値 `admin` を使用します。 + +## 設定例 + +このセクションでは、いくつかの設定例を示します。 + +### 設定例 #1 - アプリとデータベース + +```mermaid +flowchart LR + app["アプリ
(ScalarDB ライブラリと
Consensus Commit)"] + db[(基盤となるストレージまたはデータベース)] + app --> db +``` + +この例の設定では、アプリ (Consensus Commit を備えた ScalarDB ライブラリ) が、基盤となるストレージまたはデータベース (この場合は Cassandra) に直接接続します。 + +:::warning + +この設定は開発目的のみに存在し、実稼働環境には適していません。これは、ScalarDB のトランザクション的に一貫性のあるバックアップを取得するために、アプリが [Scalar Admin](https://github.com/scalar-labs/scalar-admin) インターフェースを実装する必要があり、追加の設定が必要になるためです。 + +::: + +以下は、ScalarDB を介してアプリを基盤となるデータベースに接続するための設定の例です。 + +```properties +# Transaction manager implementation. +scalar.db.transaction_manager=consensus-commit + +# Storage implementation. +scalar.db.storage=cassandra + +# Comma-separated contact points. +scalar.db.contact_points= + +# Credential information to access the database. +scalar.db.username= +scalar.db.password= +``` + +### 設定例 #2 - アプリ、ScalarDB Cluster、データベース + +```mermaid +flowchart LR + app["アプリ -
ScalarDB ライブラリと gRPC"] + cluster["ScalarDB Cluster -
(ScalarDB ライブラリと
Consensus Commit)"] + db[(基盤となるストレージまたはデータベース)] + app --> cluster --> db +``` + +この例の設定では、アプリ (gRPC を使用した ScalarDB ライブラリ) は、ScalarDB Enterprise エディションでのみ使用可能なコンポーネントである ScalarDB Cluster を介して、基盤となるストレージまたはデータベース (この場合は Cassandra) に接続します。 + +:::note + +ScalarDB Cluster は [Scalar Admin](https://github.com/scalar-labs/scalar-admin) インターフェイスを実装しており、これにより ScalarDB Cluster を一時停止することで ScalarDB のトランザクション的に一貫性のあるバックアップを取得できるため、この設定は実稼働環境での使用に適しています。 + +::: + +以下は、ScalarDB Cluster を介してアプリを基盤となるデータベースに接続するための設定の例です。 + +```properties +# Transaction manager implementation. +scalar.db.transaction_manager=cluster + +# Contact point of the cluster. +scalar.db.contact_points=indirect: +``` + +クライアント設定の詳細については、[ScalarDB Cluster クライアント設定](scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#クライアント設定) を参照してください。 + +[^1]: アプリケーションのアクセスパターンを考慮し、アプリケーションが使用する同じ基盤ストレージで、いくつかのバリエーション (たとえば、デフォルト値の 75% と 125%) でパフォーマンスをベンチマークして、最適な設定を決定することは価値があります。最適な設定は実際にはこれらの要因によって決まるためです。また、これらのパラメーターの組み合わせ (たとえば、1番目に `slot_capacity:20` と `group_size_fix_timeout_millis:40`、2番目に `slot_capacity:30` と `group_size_fix_timeout_millis:40`、3番目に `slot_capacity:20` と `group_size_fix_timeout_millis:80`) をベンチマークして、最適な組み合わせを決定することも重要です。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/consensus-commit.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/consensus-commit.mdx new file mode 100644 index 00000000..f2efa7c4 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/consensus-commit.mdx @@ -0,0 +1,234 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Consensus Commit プロトコル + +import JavadocLink from '/src/theme/JavadocLink.js'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + +Consensus Commit は ScalarDB で使用されるトランザクションプロトコルであり、複数の異なるデータベースにまたがるトランザクションを実行するために設計されています。このプロトコルの特徴は、X/Open XA ベースのソリューションとは異なり、下位のデータベースのトランザクション機能に依存せずに ACID トランザクションを実現することです。このドキュメントでは、プロトコルの詳細、その動作方法、保証される分離レベル、インターフェース、採用されているパフォーマンス最適化、および制限事項について説明します。 + +## プロトコル + +このセクションでは、Consensus Commit プロトコルの仕組みについて説明します。Consensus Commit プロトコルは、分離を保証するための並行性制御プロトコルと、原子性と永続性を保証するためのアトミックコミットメントプロトコルを使用します。 + +### 並行性制御プロトコル + +Consensus Commit プロトコルは、並行性制御プロトコルとして楽観的並行性制御 (OCC) を採用しています。OCC は競合が少ないという前提で動作し、ロックを必要とせずにトランザクションを進め、競合が実際に発生した場合にのみ解決します。そのため、OCC は競合の少ない環境で優れたパフォーマンスを発揮します。また、ロック管理が難しい分散環境において特に有益です。 + +:::note + +一方、悲観的並行性制御 (PCC) は、競合が多いという前提で動作し、干渉を避けるために使用されるリソースにロックをかけます。そのため、PCC は競合の多い環境で優れたパフォーマンスを発揮します。 + +::: + +ScalarDB の OCC プロトコルは、一般的に使用される OCC プロトコルと同様に、次の3つのフェーズで構成されています: + +- 読み取りフェーズ: + - ScalarDB はトランザクションの読み取りセットと書き込みセットを追跡します。ScalarDB はトランザクションがアクセスするすべてのレコードをデータベースからローカルワークスペースにコピーし、書き込みをローカルワークスペースに保存します。 +- 検証フェーズ: + - ScalarDB はコミット中のトランザクションが他のトランザクションと競合していないか確認します。ScalarDB は後方検証を使用し、他のトランザクションがトランザクションが読み書きする内容を書き込んでいない場合にのみ、書き込みフェーズに進みます。これらはそれぞれ、読み取り検証と書き込み検証と呼ばれます。 +- 書き込みフェーズ: + - ScalarDB はトランザクションの書き込みセットの変更をデータベースに伝播し、それらを他のトランザクションから見えるようにします。 + +次に説明するように、ScalarDB は検証フェーズでの読み取り検証をスキップする分離モード (分離レベル) を提供し、正確性のために読み取り検証を必要としない一部のワークロードでより良いパフォーマンスを可能にします。 + +:::note + +読み取り検証なしの ScalarDB の OCC は、スナップショット分離と同様に動作します。ただし、単一バージョンで動作し、グローバルスナップショットを作成しないため、読み取りスキュー異常を引き起こします。 + +::: + +### アトミックコミットメントプロトコル + +Consensus Commit プロトコルは、アトミックコミットメントプロトコル (ACP) として2フェーズコミットプロトコルの変種を採用しています。ScalarDB の ACP は2つのフェーズで構成され、各フェーズには2つのサブフェーズがあり、簡単に説明すると以下のように動作します: + +- 準備フェーズ(レコード準備フェーズ + レコード検証フェーズ): + - レコード準備フェーズでは、ScalarDB はトランザクションによって書き込まれたすべてのレコードについて、OCC プロトコルの書き込み検証を実行し、レコードの状態を PREPARED に更新し、すべてのレコードが正常に検証された場合は次のフェーズに進みます。 + - レコード検証フェーズでは、ScalarDB はトランザクションによって読み取られたすべてのレコードについて、OCC プロトコルの読み取り検証を実行し、すべてのレコードが正常に検証された場合は次のフェーズに進みます。 +- コミットフェーズ(状態コミットフェーズ + レコードコミットフェーズ): + - 状態コミットフェーズでは、ScalarDB は Coordinator テーブルと呼ばれる特別なテーブルに COMMITTED の状態を書き込むことでトランザクションをコミットします。 + - レコードコミットフェーズでは、ScalarDB はトランザクションによって書き込まれたすべてのレコードについて、OCC プロトコルの書き込みフェーズを実行し、レコードの状態を COMMITTED に更新します。 + +:::note + +レコードを削除する場合、レコードの状態は最初に準備フェーズで DELETED に変更され、その後コミットフェーズで物理的に削除されます。 + +::: + +#### より詳細な動作方法 + +プロトコルが各フェーズでどのように機能するかをより詳しく見ていきましょう。 + +##### 準備フェーズの前 + +まず、クライアントが ScalarDB (または ScalarDB Cluster ノード) にアクセスして `begin` コマンドを発行すると、トランザクションが開始します。トランザクションが開始すると、ScalarDB は下位のデータベースにアクセスするトランザクションコーディネーターとして動作し、最初に UUID version 4 でトランザクション ID (TxID) を生成します。その後、クライアントがレコードの読み取りや書き込みなどの操作を実行した後にトランザクションをコミットする準備ができると、`commit` コマンドを呼び出して ScalarDB にトランザクションのコミットを要求し、準備フェーズに入ります。前述のように、ScalarDB はコミット時にトランザクションの読み取りセット (readSet) と書き込みセット (writeSet) をローカルワークスペースに保持します。 + +##### 準備フェーズ + +ScalarDB はまず、レコード準備フェーズとして、後述する TxID などのトランザクションログを含むレコードを PREPARED 状態で下位のデータベースに伝播することにより、書き込みセットのレコードを準備します。ここでは、書き込みセットが元のレコードと更新された列で構成される更新されたレコードを維持すると仮定します。準備処理が失敗した場合、すべてのトランザクションの最終状態が決定され管理される Coordinator テーブルに ABORTED 状態のレコードを書き込むことでトランザクションをアボートします。Coordinator テーブルの詳細は、このセクションの後半で説明します。 + +:::note + +ScalarDB は線形化可能な条件付き書き込みを使用して、競合する準備処理をチェックします。トランザクションは、レコードの TxID が変更されていないかをチェックすることで、そのレコードがトランザクションの読み取り後に別のトランザクションによって更新されていない場合にのみ、レコードを更新します。 + +::: + +必要に応じて、ScalarDB はレコード検証フェーズに進みます。レコード検証フェーズは、分離レベルが SERIALIZABLE に設定されている場合にのみ必要です。このフェーズでは、ScalarDB は読み取りセット内のすべてのレコードを再読み取りして、他のトランザクションがトランザクションが以前に読み取ったレコードを書き込んでいるかどうかを確認します。読み取りセットが変更されていなければ、反依存関係がないためトランザクションは状態コミットフェーズに進むことができます。そうでない場合は、トランザクションをアボートします。 + +##### コミットフェーズ + +準備フェーズでのすべての検証が正常に完了した場合、ScalarDB は状態コミットフェーズとして Coordinator テーブルに COMMITTED 状態のレコードを書き込むことでトランザクションをコミットします。 + +:::note + +ScalarDB は Coordinator テーブルへの同時書き込みを調整するために線形化可能な条件付き書き込みを使用し、その TxID のレコードがない場合に TxID を持つ状態レコードを作成します。COMMITTED 状態が Coordinator テーブルに正しく書き込まれると、トランザクションはコミットされたとみなされます。 + +::: + +その後、ScalarDB はレコードコミットフェーズとして、検証された (準備された) すべてのレコードの状態を COMMITTED に変更することでコミットします。 + +#### 分散 WAL + +ScalarDB はトランザクションログ (ログ先行書き込み/WAL) を、管理する下位のデータベースのレコードに保存します。具体的には、次の図に示すように、ScalarDB はアプリケーションが管理する列に加えて、レコード内にログ情報用の特別な列を管理します。ログ情報は、例えば、対応するレコードを最近更新したトランザクションID (TxID)、レコードのバージョン番号 (Version)、レコードの状態 (TxState) (例えば、COMMITTED または PREPARED)、タイムスタンプ(図には表示されていません)、および前のバージョンのアプリケーションデータとそのメタデータで構成される前イメージなどで構成されます。 + +ScalarDB はまた、アプリケーションレコードとは別に Coordinator テーブルでトランザクション状態を管理します。Coordinator テーブルは、信頼できる唯一の情報源としてトランザクション状態を決定し管理します。Coordinator テーブルは、アプリケーション管理テーブルと同じ場所に配置するか、別の専用データベースに配置することができます。 + +![分散 WAL](images/scalardb-metadata.png) + +:::note + +Coordinator テーブルは、下位のデータベースのレプリケーションおよびコンセンサス機能を使用して、高可用性のためにレプリケートすることができます。例えば、レプリケーション係数3の Cassandra を使用して Coordinator テーブルを管理する場合、ScalarDB のトランザクション調整を1つのレプリカのクラッシュに耐えるようにすることができます。したがって、ScalarDB のアトミックコミットメントプロトコルを Paxos Commit プロトコルのように機能させることができます。つまり、安全性を犠牲にすることなく、活性の問題(例えば、ブロッキング問題)を軽減することができます。 + +::: + +#### 遅延リカバリ + +トランザクションはいつでもクラッシュし、レコードをコミットされていない状態で残す可能性があります。ScalarDBは、Coordinator テーブルのトランザクション状態に応じて、レコードを読み取るときにコミットされていないレコードを遅延回復します。具体的には、レコードが PREPARED 状態にあるが、レコードを更新したトランザクションが期限切れまたはアボートされた場合、レコードはロールバックされます。レコードが PREPARED 状態にあり、レコードを更新したトランザクションがコミットされている場合、レコードはロールフォワードされます。 + +トランザクションは一定時間 (現在は15秒) 後に期限切れになります。ScalarDB が期限切れのトランザクションによって準備されたレコードを観察すると、ScalarDB は Coordinator テーブルにそのトランザクションの ABORTED 状態を書き込みます (再試行あり)。ScalarDB が Coordinator テーブルに ABORTED 状態を正常に書き込むと、トランザクションはアボートされます。それ以外の場合、トランザクションは何らかの理由で遅いが依然としてアクティブな元のプロセスによってコミットされるか、アボートまたはコミットされるまで UNKNOWN 状態のままになります。 + +## 分離レベル + +Consensus Commit プロトコルは、2つの分離レベルをサポートしています。スナップショット分離の弱い変種であるリードコミットスナップショット分離とシリアライザブルの2つです。それぞれ以下の特性を持ちます: + +- リードコミットスナップショット分離 (SNAPSHOT - デフォルト) + - 発生しうる異常:読み取りスキュー、書き込みスキュー、読み取り専用 + - シリアライザブルより高速ですが、弱い正確性を保証します。 +- シリアライザブル (SERIALIZABLE) + - 発生しうる異常:なし + - リードコミットスナップショット分離より遅いですが、より強い(最強の)正確性を保証します。 + +上述のように、シリアライザブルは正確性の観点からは望ましいですが、リードコミットスナップショット分離よりも遅くなります。アプリケーションの要件とワークロードに基づいて、適切なものを選択してください。リードコミットスナップショット分離とシリアライザブルの設定方法の詳細については、[ScalarDB の設定](configurations.mdx#基本設定)を参照してください。 + +:::note + +ScalarDB の Consensus Commit プロトコルは、[ScalarDB の下位のデータベースの設定](database-configurations.mdx#トランザクション)で説明されているように、下位のデータベースが線形化可能な操作を提供する必要があります。それにより、厳密なシリアライザビリティを保証します。 + +::: + +:::warning + +非 JDBC データベースに対して、パーティションキーを指定せずにレコードをスキャンする (例えば、 または `SELECT * FROM table`) 場合、`SERIALIZABLE`が指定されていても、常にシリアライザビリティを保証するわけではありません。したがって、自己判断で行い、可能であればスキーマの更新を検討してください。詳細については、[クロスパーティションスキャン設定](configurations.mdx#クロスパーティションスキャン設定)を参照してください。 + +::: + +## インターフェース + +Consensus Commit プロトコルは、[1フェーズコミットインターフェースと2フェーズコミットインターフェース](scalardb-cluster/run-transactions-through-scalardb-cluster.mdx#トランザクションを実行する)の2つのインターフェースを提供します。 + +1フェーズコミットインターフェースは、単一の `commit` メソッドのみを提供するシンプルなインターフェースで、アトミックコミットメントプロトコルのすべてのフェーズがこのメソッドで実行されます。一方、2フェーズコミットインターフェースは、`prepare`、`validate`、`commit` メソッドでプロトコルの各フェーズを公開します。 + +:::note + +`prepare` メソッドはレコード準備フェーズ用で、`validate` メソッドはレコード検証フェーズ用です。 + +::: + +ほとんどの場合、使いやすくエラー処理も容易であるため、1フェーズコミットインターフェースの使用をお勧めします。しかし、2フェーズコミットインターフェースは、ScalarDB からデータベースに直接アクセスせずに、複数のアプリケーションやサービス間でトランザクションを実行する場合に役立ちます。例えば、マイクロサービスのデータベースの一貫性を維持する場合などです。 + +## パフォーマンスの最適化 + +Consensus Commit プロトコルは、いくつかのパフォーマンス最適化を採用しています。 + +### 並列実行 + +Consensus Commit は、正確性を犠牲にすることなく、トランザクション内並列処理を使用してアトミックコミットメントプロトコルの各フェーズを並列に実行します。具体的には、PREPARED 状態でレコードを書き込むことにより、レコード準備フェーズを並列に実行しようとします。同様に、レコード検証フェーズ、レコードコミットフェーズ、およびロールバックプロセスにも同様の並列実行を使用します。 + +以下のパラメータを使用して、それぞれの並列実行を有効にできます: + +- レコード準備フェーズ + - `scalar.db.consensus_commit.parallel_preparation.enabled` +- レコード検証フェーズ + - `scalar.db.consensus_commit.parallel_validation.enabled` +- レコードコミットフェーズ + - `scalar.db.consensus_commit.parallel_commit.enabled` +- ロールバック処理 + - `scalar.db.consensus_commit.parallel_rollback.enabled` + +また、以下のパラメータを使用して実行の並列性を設定できます: + +- `scalar.db.consensus_commit.parallel_executor_count` + +設定の詳細については、[パフォーマンス関連の設定](configurations.mdx#パフォーマンス関連の設定)を参照してください。 + +### 非同期実行 + +トランザクションは状態コミットフェーズが正常に完了すると「コミット済み」とみなされるため、レコードコミットフェーズの完了を待たずにクライアントに戻り、フェーズを非同期に実行することもできます。同様に、トランザクションが何らかの理由で失敗してロールバックを行う場合、ロールバックプロセスもその完了を待たずに非同期に実行できます。 + +以下のパラメータを使用して、それぞれの非同期実行を有効にできます: + +- レコードコミットフェーズ + - `scalar.db.consensus_commit.async_commit.enabled` +- ロールバック処理 + - `scalar.db.consensus_commit.async_rollback.enabled` + +### グループコミット + +Consensus Commit は、複数のトランザクションの状態コミットフェーズをバッチで実行し、状態コミットフェーズの書き込み回数を減らすグループコミット機能を提供します。これは特に、Coordinator テーブルへの書き込みが遅い場合、たとえば高可用性のためにマルチリージョン環境に Coordinator テーブルがデプロイされている場合に役立ちます。 + +以下のパラメータを使用してグループコミットを有効にできます: + +- `scalar.db.consensus_commit.coordinator.group_commit.enabled` + +グループコミットにはいくつかの他のパラメータがあります。詳細については、[パフォーマンス関連の設定](configurations.mdx#パフォーマンス関連の設定)を参照してください。 + +## 制限事項 + +ScalarDB には、データベースに依存しないトランザクションを実現するうえでいくつかの制限があります。 + +### アプリケーションは下位のデータベースにアクセスするために ScalarDB にアクセスする必要がある + +Consensus Commit プロトコルを使用する ScalarDB は、下位のデータベースのトランザクション機能に依存することなく、そのレイヤーでトランザクションを処理するため、アプリケーションは ScalarDB をバイパスすることはできません。バイパスすると、予期しない動作が発生し、ほとんどの場合、いくつかのデータベース異常に直面することになります。読み取り操作であっても、ScalarDB の下位のデータベースに直接アクセスすると、トランザクションメタデータを含む一貫性のないデータが得られるため、許可されていません。 + +ただし、ScalarDB のトランザクションによって管理または触れられていないテーブルについては、テーブルから読み取りや書き込みを行うことができます。たとえば、ScalarDB を経由せずに直接テーブルにアクセスして、情報スキーマなどのテーブルのメタデータ情報を確認することは問題ありません。また、ScalarDB を経由せずに直接データベースにアクセスできる他のケースもいくつかあります。基本的な基準は、下位のデータベースにデータを書き込むかどうかです。データベースに書き込まないことが確実であれば、データベースに直接アクセスできます。たとえば、データベースネイティブツールを使用してデータベースのバックアップを取ることは問題ありません。 + +:::note + +複数のデータベースやトランザクションをサポートしないデータベースからバックアップを取る場合は、アプリケーションや ScalarDB Cluster を一時停止する必要があります。詳細については、[ScalarDB で使用されるデータベースのバックアップと復元方法](backup-restore.mdx)を参照してください。 + +::: + +### 正確性のために特定の操作を特定の順序で実行することは禁止されている + +現在の実装では、ScalarDB は以下の場合に例外をスローします: + +- トランザクション内で同じレコードに対して書き込み (Put、Insert、Update、Upsert、Delete) 操作の後にスキャン操作を実行する場合。 +- トランザクション内で同じレコードに対して削除操作の後に書き込み (Put、Insert、Update、Upsert) 操作を実行する場合。 + +## 関連情報 + +以下のプレゼンテーションと YouTube ビデオを見ることで、Consensus Commit プロトコルについてさらに学ぶことができます。これらはプロトコルの動作を視覚的に要約しています: + +- **Speaker Deck プレゼンテーション (英語):** [ScalarDB: Universal Transaction Manager](https://speakerdeck.com/scalar/scalar-db-universal-transaction-manager) +- **YouTube:** [ScalarDB におけるトランザクションの挙動 (DBSJ 講義の一部)](https://www.youtube.com/watch?v=s6Q7QQccDTc) + +さらに、プロトコルの詳細については、背景、課題、新規性を含めて、以下の研究論文とそのプレゼンテーションで議論されています: + +- **研究論文 (英語):** [ScalarDB: Universal Transaction Manager for Polystores](https://www.vldb.org/pvldb/vol16/p3768-yamada.pdf) +- **Speaker Deck プレゼンテーション (英語):** [ScalarDB: Universal Transaction Manager for Polystores](https://speakerdeck.com/scalar/scalardb-universal-transaction-manager-for-polystores-vldb23) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/data-modeling.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/data-modeling.mdx new file mode 100644 index 00000000..302e8f1c --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/data-modeling.mdx @@ -0,0 +1,135 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# データをモデル化する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +データモデリング (つまり、データベーススキーマの設計) とは、データへのアクセスに使用されるパターンと、ビジネスオペレーション内で実行されるクエリの種類を特定することで、データの保存方法と使用方法を概念化して視覚化するプロセスです。 + +このページでは、まず ScalarDB データモデルについて説明し、次にデータモデルに基づいてデータベーススキーマを設計する方法について説明します。 + +## ScalarDB データモデル + +ScalarDB のデータモデルは、Bigtable データモデルにヒントを得た拡張キー値モデルです。リレーショナルモデルに似ていますが、以下に示すようにいくつかの点で異なります。データモデルは、リレーショナルデータベース、NoSQL データベース、NewSQL データベースなど、さまざまなデータベースを抽象化するために選択されます。 + +次の図は、それぞれがレコードのコレクションである ScalarDB テーブルの例を示しています。このセクションでは、まず、テーブルやレコードなどの ScalarDB が定義するオブジェクトについて説明し、次にレコードの検索方法について説明します。 + +![ScalarDB データモデル](images/scalardb_data_model.png) + +### ScalarDB のオブジェクト + +ScalarDB データモデルには、いくつかのオブジェクトがあります。 + +#### 名前空間 + +名前空間は、SQL 名前空間またはデータベースに類似したテーブルのコレクションです。 + +#### テーブル + +テーブルはパーティションのコレクションです。名前空間には、通常、それぞれが名前で識別される1つ以上のテーブルが含まれます。 + +#### パーティション + +パーティションはレコードのコレクションであり、論理ノードまたは物理ノードへの分散単位です。したがって、同じパーティション内のレコードは同じノードに配置されます。ScalarDB では、複数のパーティションがハッシュによって分散されていると想定しています。 + +#### レコード / 行 + +レコードまたは行は、他のすべてのレコード間で一意に識別できる列のセットです。 + +#### 列 + +列は基本的なデータ要素であり、これ以上細分化する必要はありません。各レコードは、1つ以上の列で設定されます。各列にはデータ型があります。データ型の詳細については、[ScalarDB と他のデータベース間のデータ型マッピング](schema-loader.mdx#scalardb-と他のデータベース間のデータ型マッピング)を参照してください。 + +#### セカンダリインデックス + +セカンダリインデックスは、単一の基本テーブル内の列のソートされたコピーです。各インデックスエントリは、対応するテーブルパーティションにリンクされています。ScalarDB は現在、複数列のインデックスをサポートしていないため、1つの列のみでインデックスを作成できます。 + +### レコードの検索方法 + +このセクションでは、テーブルからレコードを検索する方法について説明します。 + +#### 主キー + +主キーは各レコードを一意に識別します。2つのレコードが同じ主キーを持つことはできません。したがって、主キーを指定してレコードを検索できます。主キーは、パーティションキーと、オプションでクラスタリングキーで設定されます。 + +#### パーティションキー + +パーティションキーは、パーティションを一意に識別します。パーティションキーは、パーティションキー列と呼ばれる列のセットで設定されます。パーティションキーのみを指定すると、パーティションに属するレコードのセットを取得できます。 + +#### クラスタリングキー + +クラスタリングキーは、パーティション内のレコードを一意に識別します。クラスタリングキー列と呼ばれる列のセットで設定されます。クラスタリングキーを指定する場合は、効率的な検索のためにパーティションキーを指定する必要があります。パーティションキーなしでクラスタリングキーを指定すると、すべてのパーティションをスキャンすることになります。すべてのパーティションをスキャンすると、特にデータ量が多い場合は時間がかかるため、自己判断でのみ実行してください。 + +パーティション内のレコードは、クラスタリング順序として指定されたクラスタリングキー列でソートされていると想定されます。したがって、定義された順序でクラスタリングキー列の一部を指定して、返される結果を絞り込むことができます。 + +#### インデックスキー + +インデックスキーは、インデックス内のキーを検索してレコードを識別します。インデックスキーの検索はすべてのパーティションにまたがるため、特に検索の選択性が低くない場合は、必ずしも効率的であるとは限りません。 + +## データベーススキーマの設計方法 + +データベーススキーマはリレーショナルモデルと同様に設計できますが、基本的な原則があり、従うべきベストプラクティスがいくつかあります。 + +### クエリ駆動型データモデリング + +リレーショナルデータベースでは、データは正規化されたテーブルに整理され、外部キーを使用して他のテーブル内の関連データを参照します。アプリケーションが実行するクエリはテーブルによって構造化され、関連データはテーブル結合としてクエリされます。 + +ScalarDB は ScalarDB SQL での結合操作をサポートしていますが、データモデリングは NoSQL データベースのように、よりクエリ駆動型である必要があります。データアクセスパターンとアプリケーションクエリによって、テーブルの構造と設定が決定されます。 + +### ベストプラクティス + +このセクションでは、データベーススキーマを設計するためのベストプラクティスについて説明します。 + +#### データ分散を考慮する + +パーティションキーとクラスタリングキーを適切に選択して、パーティションへの負荷を分散させることをお勧めします。 + +たとえば、銀行アプリケーションでアカウント ID をパーティションキーとして選択すると、アカウントが属するパーティション内で特定のアカウントに対するすべてのアカウント操作を実行できます。したがって、異なるアカウント ID を操作すると、異なるパーティションにアクセスすることになります。 + +一方、ブランチ ID をパーティションキーとして選択し、アカウント ID をクラスタリングキーとして選択すると、ブランチのアカウント ID へのアクセスはすべて同じパーティションに送られるため、負荷とデータサイズの不均衡が生じます。さらに、少数の大きなパーティションを作成すると負荷とデータサイズの不均衡が生じるため、パーティションキーにはカーディナリティの高い列を選択する必要があります。 + +#### 単一のパーティションの読み取りを試みる + +データモデルの特性により、単一パーティション検索が最も効率的です。スキャンを発行したり、複数パーティションの検索やスキャンを必要とするリクエストを選択したりする必要がある場合は、[クロスパーティションスキャンで有効にする](configurations.mdx#クロスパーティションスキャン設定)ことができますが、独自の判断で実行し、可能であればスキーマの更新を検討してください。 + +たとえば、銀行アプリケーションで、パーティションキーとして電子メールを選択し、クラスタリングキーとしてアカウント ID を選択し、アカウント ID を指定するクエリを発行すると、対応するパーティションを効率的に識別できないため、クエリはすべてのパーティションにまたがって実行されます。このような場合は、常にアカウント ID を使用してテーブルを検索する必要があります。 + +:::note + +適切なインデックスを持つリレーショナルデータベース上の複数のパーティションを読み取る場合、クエリがデータベースにプッシュダウンされるため、クエリが効率的になる可能性があります。 + +::: + +#### セカンダリインデックスの使用を避ける + +上記と同様に、セカンダリインデックスを使用するスキャンまたは選択リクエストを発行する必要がある場合、そのリクエストはテーブルのすべてのパーティションにまたがります。したがって、セカンダリインデックスの使用を避けるようにしてください。セカンダリインデックスを使用する必要がある場合は、小さな部分を検索する低選択性クエリを介して使用します。 + +セカンダリインデックスの代わりに、ベーステーブルのクラスター化インデックスとして機能する別のテーブルを作成できます。 + +たとえば、主キーが `A` である `table1(A, B, C)` という 3つの列を持つテーブルがあるとします。次に、`C` を主キーとして `index-table1(C, A, B)` のようなテーブルを作成し、`C` の値を指定して単一のパーティションを検索できるようにします。このアプローチにより、読み取りクエリは高速化されますが、ScalarDB トランザクションを使用して2つのテーブルに書き込む必要があるため、書き込みクエリの負荷が増加する可能性があります。 + +:::note + +将来的には、ScalarDB にテーブルベースのセカンダリインデックス機能が追加される予定です。 + +::: + +#### データはハッシュによって分散されていると想定されていることを考慮する + +現在の ScalarDB データモデルでは、データはハッシュによって分散されていると想定されています。したがって、パーティションキーがないと範囲クエリを効率的に実行できません。 + +範囲クエリを効率的に発行するには、パーティション内で実行する必要があります。ただし、このアプローチに従う場合は、パーティションキーを指定する必要があります。範囲クエリは常に同じパーティションに送信されるので、パーティションが過負荷になる可能性があり、スケーラビリティの問題が発生する可能性があります。この制限は ScalarDB に固有のものではなく、スケーラビリティのためにハッシュによってデータが分散されているデータベースに固有のものです。 + +:::note + +適切なインデックスを持つリレーショナルデータベースで ScalarDB を実行すると、クエリがデータベースにプッシュダウンされるため、範囲クエリが効率的になる可能性があります。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/database-configurations.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/database-configurations.mdx new file mode 100644 index 00000000..2f221487 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/database-configurations.mdx @@ -0,0 +1,123 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB の基盤となるデータベースの設定 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDB を使用するアプリケーションが正しく効率的に動作するように、ScalarDB の基盤となるデータベースを設定する方法について説明します。 + +## 基盤となるデータベースの一般的な要件 + +ScalarDB では、基盤となる各データベースが、データベースでトランザクションと分析を実行するための特定の機能を提供する必要があります。このドキュメントでは、一般的な要件と、要件を満たすために各データベースを設定する方法について説明します。 + +### トランザクション + +ScalarDB では、基盤となる各データベースが、データベースでトランザクションを実行するために少なくとも次の機能を提供する必要があります。 + +- 単一のデータベースレコードに対する線形化可能な読み取りと条件付きミューテーション (書き込みと削除)。 +- 書き込まれたデータベースレコードの耐久性。 +- 各データベースレコードにアプリケーションデータのほかに任意のデータを保存できる機能。 + +### 分析 + +ScalarDB では、基盤となる各データベースが、データベースで分析を実行するために次の機能を提供する必要があります。 + +- コミットされたレコードのみを返す機能。 + +:::note + +ScalarDB は、CRUD 操作だけでなく、スキーマ、テーブル、インデックスの作成や変更などの操作を実行するために、基盤となるデータベース上で実行されるため、ScalarDB を介してデータベースにアクセスするのに十分な権限を持つデータベースアカウントが必要です。基本的に、ScalarDB では、基盤となるデータベースにアクセスするために完全な権限を持つアカウントが必要です。 + +::: + +## 一般的な要件を満たすようにデータベースを設定する方法 + +一般的な要件を満たすようにデータベースを設定する方法の詳細については、データベースを選択してください。 + + + +

トランザクション

+ + - すべての操作に単一のプライマリサーバーまたは同期された複数のプライマリサーバーを使用します (プライマリデータベースから非同期にレプリケートされた読み取りレプリカに対する読み取り操作はありません)。 + - 読み取りコミットまたはより厳格な分離レベルを使用します。 + +

分析

+ + - 読み取りコミットまたはより厳格な分離レベルを使用します。 +
+ +

トランザクション

+ + - すべての操作に単一のプライマリリージョンを使用します。(プライマリリージョン以外のグローバルテーブルに対する読み取りおよび書き込み操作は実行できません。) + - DynamoDB にはプライマリリージョンの概念がないため、プライマリリージョンは自分で指定する必要があります。 + +

分析

+ + - 該当なし。DynamoDB は常にコミットされたレコードを返すため、DynamoDB 固有の要件はありません。 +
+ +

トランザクション

+ + - 「Strong」または「Bounded Staleness」の一貫性を持つすべての操作に単一のプライマリリージョンを使用します。 + +

分析

+ + - 該当なし。Cosmos DB は常にコミットされたレコードを返すため、Cosmos DB 固有の要件はありません。 +
+ +

トランザクション

+ + - すべての操作に単一のプライマリクラスターを使用します (プライマリ以外のクラスターでは読み取りまたは書き込み操作は行いません)。 + - `commitlog_sync` には `batch` または `group` を使用します。 + - Cassandra 互換データベースを使用している場合、それらのデータベースは軽量トランザクション (LWT) を適切にサポートしている必要があります。 + +

分析

+ + - 該当なし。Cassandra は常にコミットされたレコードを返すため、Cassandra 固有の要件はありません。 +
+
+ +## 推奨事項 + +ScalarDB の基盤となる各データベースを適切に設定して、高パフォーマンスと高可用性を実現することが推奨されます。次の推奨事項には、更新すべきいくつかのオプションが含まれています。 + +:::note + +ScalarDB は基盤となるデータベースのアプリケーションと見なすことができるため、効率を向上させるためによく使用されるその他のオプションを更新してみることをお勧めします。 + +::: + + + + - パフォーマンスを向上させるには、読み取りコミット分離を使用します。 + - 各データベースのパフォーマンス最適化のベストプラクティスに従います。たとえば、パフォーマンスを向上させるには、通常、バッファサイズ (PostgreSQL の `shared_buffers` など) を増やし、接続数 (PostgreSQL の `max_connections` など) を増やすことが推奨されます。 + + + - 読み取り容量ユニット (RCU) と書き込み容量ユニット (WCU) の数を増やして、スループットを高めます。 + - ポイントインタイムリカバリ (PITR) を有効にします。 + +:::note + +DynamoDB はデフォルトで複数のアベイラビリティーゾーンにデータを保存するため、可用性を向上させるために設定を調整する必要はありません。 + +::: + + + - 高いスループットを実現するために、リクエストユニット (RU) の数を増やします。 + - ポイントインタイムリストア (PITR) を有効にします。 + - 可用性ゾーンを有効にします。 + + + - スループットを高めるために、`concurrent_reads` と `concurrent_writes` を増やします。詳細については、[`concurrent_writes`](https://cassandra.apache.org/doc/stable/cassandra/configuration/cass_yaml_file.html#concurrent_writes) に関する Cassandra の公式ドキュメントを参照してください。 + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/deploy-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/deploy-overview.mdx new file mode 100644 index 00000000..edfad999 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/deploy-overview.mdx @@ -0,0 +1,27 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# デプロイの概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このカテゴリでは、ローカルおよびクラウドベースの Kubernetes 環境での ScalarDB、特に ScalarDB Cluster と ScalarDB Analytics のデプロイに慣れるためのガイドに従うことができます。 + +## ローカル Kubernetes 環境に ScalarDB Cluster をデプロイする + +Helm Chart と PostgreSQL データベースを使用してローカル Kubernetes 環境に ScalarDB Cluster をデプロイする方法については、[ScalarDB Cluster をローカルにデプロイする](scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx)を参照してください。 + +## クラウドベースの Kubernetes 環境に ScalarDB Cluster をデプロイする + +Helm Chart を使用してクラウドベースの Kubernetes 環境に ScalarDB Cluster をデプロイする方法については、[Amazon Elastic Kubernetes Service (EKS) に ScalarDB Cluster をデプロイする](scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS.mdx)を参照してください。 + +## パブリッククラウドベースの環境に ScalarDB Analytics をデプロイする + +パブリッククラウドベースの環境に ScalarDB Analytics をデプロイする方法については、[パブリッククラウド環境での ScalarDB Analytics のデプロイ](scalardb-analytics/deployment.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/design.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/design.mdx new file mode 100644 index 00000000..73ac2b67 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/design.mdx @@ -0,0 +1,85 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB デザイン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDB の設計と実装について簡単に説明します。ScalarDB の概要とその使用例については、[ScalarDB の概要](./overview.mdx)を参照してください。 + +## 全体的なアーキテクチャ + +ScalarDB は、アプリケーションとデータベースの間に配置されるハイブリッドトランザクション/分析処理 (HTAP) ミドルウェアです。次の図に示すように、ScalarDB は、Core、Cluster、Analytics の3つのコンポーネントで構成されています。ScalarDB は基本的に階層型アーキテクチャを採用しているため、Cluster コンポーネントと Analytics コンポーネントは、Core コンポーネントを使用して基盤となるデータベースとやり取りしますが、正確さを犠牲にすることなくパフォーマンスを最適化するために Core コンポーネントをバイパスすることもあります。同様に、各コンポーネントも複数のレイヤーで構成されています。 + +![ScalarDB architecture](images/scalardb-architecture.png) + +## コンポーネント + +次のサブセクションでは、各コンポーネントについて1つずつ説明します。 + +### Core + +Apache 2 ライセンスの下でオープンソースソフトウェアとして提供される ScalarDB Core は、ScalarDB の不可欠な部分です。Core は、基礎となるデータベースを抽象化する抽象化レイヤーと、各データベースの抽象化を実装するアダプター (またはシム) を備えたデータベースマネージャーを提供します。さらに、データベース抽象化の上にトランザクションマネージャーを提供し、Scalar の新しい分散トランザクションプロトコルである [Consensus Commit](./consensus-commit.mdx) に基づいて、データベースに依存しないトランザクション管理を実現します。Core は、シンプルな CRUD インターフェースを提供するライブラリとして提供されます。 + +### Cluster + +商用ライセンスでライセンスされている ScalarDB Cluster は、Core コンポーネントがクラスター化されたサーバーとして機能するためのクラスタリングソリューションを提供するコンポーネントです。Cluster は主に、多数の小規模なトランザクションおよび非トランザクションの読み取りと書き込みがある OLTP ワークロード向けに設計されています。さらに、認証、承認、保存時の暗号化、きめ細かなアクセス制御 (属性ベースのアクセス制御) などのエンタープライズ機能もいくつか提供しています。Cluster は Core コンポーネントと同じ CRUD インターフェースを提供するだけでなく、SQL および GraphQL インターフェースも提供しています。さらに、複数のベクターストアと対話するためのベクターストアインターフェースも提供します。Cluster は Kubernetes Pod 内のコンテナーとして提供されるため、コンテナーを増やすことでパフォーマンスと可用性を高めることができます。 + +### Analytics + +商用ライセンスでライセンスされている ScalarDB Analytics は、Core コンポーネントによって管理されるデータ、または ScalarDB を使用しないアプリケーションによって管理されるデータに対してスケーラブルな分析処理を提供するコンポーネントです。Analytics は主に、少数の大規模な分析読み取りクエリがある OLAP ワークロード向けに設計されています。さらに、Spark を通じて SQL および DataSet API も提供されます。Analytics コンポーネントは Apache Spark エンジンにインストールできる Java パッケージとして提供されるため、Spark ワーカーノードを増やすことでパフォーマンスを向上させることができます。 + +## メタデータテーブル + +ScalarDB は機能を提供するために基盤となるデータベース内でさまざまな種類のメタデータを管理しています。次の表は、各コンポーネントによって管理されるメタデータをまとめたものです。 + +| コンポーネント | メタデータテーブル | 用途 | 格納場所 | +| ----------- | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- | --------------------------------------------------------- | +| Core | `scalardb.metadata` | データベーススキーマ情報用 | ScalarDB の下にあるすべてのデータベース内 | +| Core | `coordinator.state` | トランザクションステータス用 | コーディネーターテーブルを格納するために指定された1つのデータベース内 | +| Core | アプリケーション管理テーブル | ログ先行書き込み (WAL) 情報用 | Consensus Commit によってアクセスされるすべてのテーブル内 | +| Cluster | `scalardb.users`, `scalardb.namespace_privileges`, `scalardb.table_privileges`, `scalardb.auth_tokens` | [認証と承認](./scalardb-cluster/scalardb-auth-with-sql.mdx)用 | scalardb のシステム名前空間を格納するために指定された1つのデータベース内 | +| Cluster | `scalardb.encrypted_columns` | [保存時の暗号化](./scalardb-cluster/encrypt-data-at-rest.mdx)用 | scalardb のシステム名前空間を格納するために指定された1つのデータベース内 | +| Cluster | `scalardb.abac_*` | [属性ベースのアクセス制御](./scalardb-cluster/authorize-with-abac.mdx)用 | scalardb のシステム名前空間を格納するために指定された1つのデータベース内 | +| Analytics | カタログサーバーによって管理されるすべてのテーブル | [データカタログ](./scalardb-analytics/design.mdx#universal-data-catalog)用 | カタログサーバーデータベース内 | + +:::note + +ScalarDB を通じてアクセスされるデータベースのバックアップを取得する必要がある場合は、ScalarDB によって管理されるメタデータのバックアップも取得する必要があります。詳細については、[ScalarDB で使用されるデータベースのバックアップと復元方法](./backup-restore.mdx)を参照してください。 + +::: + +## 制限事項 + +ScalarDB はアプリケーションとデータベースの間で動作するため、いくつかの制限があります。このセクションでは、ScalarDB の制限事項をまとめています。 + +### アプリケーションは ScalarDB をバイパスしてトランザクションや分析クエリを実行することはできません + +ScalarDB Core は、データベースの外部で動作し、データベースに依存しないトランザクション機能を提供します。したがって、アプリケーションはトランザクションを実行するために ScalarDB とやり取りする必要があります。そうでなければ、ScalarDB はスナップショットやシリアライザブル分離などのトランザクションの正確性を保証できません。詳細については、[Consensus Commit](./consensus-commit.mdx) を参照してください。 + +同様に、ScalarDB Analytics は、データベースの外部で動作し、スケーラブルな分析クエリ処理機能を提供します。したがって、アプリケーションは分析クエリを実行するために ScalarDB Analytics とやり取りする必要があります。そうでなければ、ScalarDB は読み取りコミットされた分離などの正確性を保証できません。詳細については、[ScalarDB Analytics の設計](./scalardb-analytics/design.mdx)を参照してください。 + +### アプリケーションは基盤となるデータベースのすべての機能を使用できません + +ScalarDB は基盤となるデータベースの抽象化レイヤーとして機能するため、アプリケーションはこれらのデータベースのすべての機能やデータ型を使用することはできません。例えば、ScalarDB は Oracle PL/SQL のようなデータベース固有の機能をサポートしていません。 + +ScalarDB は、ほとんどのサポートされているデータベースで一般的に見られる機能を提供するように強化されています。機能の一覧については、[ScalarDB の機能](./features.mdx)を参照してください。今後のリリースで予定されている機能については、[ロードマップ](./roadmap.mdx)を参照してください。 + +## 詳細 + +ScalarDB の設計と実装の詳細については、次のドキュメントを参照してください。 + +- **Speaker Deck プレゼンテーション:** [ScalarDB: Universal Transaction Manager](https://speakerdeck.com/scalar/scalar-db-universal-transaction-manager) +- **Speaker Deck プレゼンテーション:** [ScalarDB を用いたマイクロサービスにおけるデータ管理](https://speakerdeck.com/scalar/scalardbwoyong-itamaikurosabisuniokerudetaguan-li-database-engineering-meetup-number-2) + +さらに、VLDB 2023 カンファレンスでは以下の資料が発表されました。 + +- **Speaker Deck プレゼンテーション:** [ScalarDB: Universal Transaction Manager for Polystores](https://speakerdeck.com/scalar/scalardb-universal-transaction-manager-for-polystores-vldb23) +- **詳細な論文:** [ScalarDB: Universal Transaction Manager for Polystores](https://www.vldb.org/pvldb/vol16/p3768-yamada.pdf) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-overview.mdx new file mode 100644 index 00000000..5bc196c9 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-overview.mdx @@ -0,0 +1,39 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 開発の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このカテゴリでは、ScalarDB について、特にトランザクション、分析クエリ、非トランザクションストレージ操作の実行方法について詳しく理解するためのガイドに従うことができます。 + +ScalarDB 用アプリケーションの開発を開始するには、次のサブカテゴリを参照してください。 + +## トランザクションの実行 + +このサブカテゴリでは、ScalarDB データモデルに基づいてデータをモデル化し、スキーマを作成する方法を学習できます。次に、ScalarDB Core ライブラリと、Core ライブラリをラップする gRPC サーバーである ScalarDB Cluster を介してトランザクションを実行する方法を学習できます。 + +このサブカテゴリの概要については、[トランザクションの実行の概要](develop-run-transactions-overview.mdx)を参照してください。 + +## 非トランザクション操作の実行 + +このサブカテゴリでは、このような非トランザクションストレージ操作の実行方法を学習できます。 + +このサブカテゴリの概要については、[非トランザクションストレージ操作を実行](develop-run-non-transactional-operations-overview.mdx)を参照してください。 + +## 分析クエリの実行 + +ScalarDB Analytics を使用して分析クエリを実行する方法については、[ScalarDB Analytics を介して分析クエリを実行する](scalardb-analytics/run-analytical-queries.mdx)を参照してください。 + +## サンプルアプリケーションの実行 + +このサブカテゴリでは、ScalarDB を活用するさまざまなサンプルアプリケーションの実行方法を学習できます。 + +このサブカテゴリの概要については、[サンプルアプリケーションの実行の概要](scalardb-samples/README.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-run-non-transactional-operations-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-run-non-transactional-operations-overview.mdx new file mode 100644 index 00000000..052e16fa --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-run-non-transactional-operations-overview.mdx @@ -0,0 +1,25 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 非トランザクションストレージ操作を実行 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB は当初、多様なデータベース間の統一された抽象化と、そのようなデータベース間のトランザクションを提供するために設計されました。ただし、複数の、場合によっては多様なデータベースを使用するアプリケーションを簡素化するために、統一された抽象化のみが必要な場合があります。 + +ScalarDB は、トランザクション機能なしで統一された抽象化のみを提供するように設定することで、基盤となるデータベースとストレージで非トランザクション操作のみを実行できます。この設定の ScalarDB は複数の操作間で ACID を保証しませんが、より優れたパフォーマンスで操作を実行できます。 + +このサブカテゴリでは、このような非トランザクションストレージ操作を実行する方法を学習できます。 + +- CRUD インターフェースを使用して実行 + - [ScalarDB Core ライブラリを使用](run-non-transactional-storage-operations-through-library.mdx) + - [ScalarDB Cluster を使用](scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx) +- [SQL インターフェースを使用して実行](scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx) +- [プリミティブ CRUD インターフェースを使用して実行](run-non-transactional-storage-operations-through-primitive-crud-interface.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-run-transactions-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-run-transactions-overview.mdx new file mode 100644 index 00000000..b60fddb7 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/develop-run-transactions-overview.mdx @@ -0,0 +1,21 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# トランザクションの実行の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このサブカテゴリでは、ScalarDB データモデルに基づいてデータをモデル化し、スキーマを作成する方法を学習できます。次に、ScalarDB Core ライブラリと、Core ライブラリをラップする gRPC サーバーである ScalarDB Cluster を介してトランザクションを実行する方法を学習できます。 + +- [データモデリング](data-modeling.mdx) +- CRUD インターフェースを使用して実行 + - [ScalarDB Core ライブラリを使用](run-transactions-through-scalardb-core-library.mdx) + - [ScalarDB Cluster を使用](scalardb-cluster/run-transactions-through-scalardb-cluster.mdx) +- [SQL インターフェースを使用して実行](scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/features.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/features.mdx new file mode 100644 index 00000000..6634726d --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/features.mdx @@ -0,0 +1,33 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB の機能 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDB の各エディションで利用可能な機能について簡単に説明します。 + +| | ScalarDB Core (Community) | ScalarDB Cluster (Enterprise Standard) | ScalarDB Cluster (Enterprise Premium) | ScalarDB Analytics (Enterprise) | +|-----------------------------------------------------------------------------------------------------------------|---------------------------|----------------------------------------|-----------------------------------------------------------|----------------------------------| +| [プリミティブインターフェースを使用した複数データベースをまたがるトランザクション処理](getting-started-with-scalardb.mdx) | ✅ | ✅ | ✅ | – | +| [クラスタリング](scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx) | – | ✅ | ✅ | – | +| [トランザクションを用いないストレージ操作](develop-run-non-transactional-operations-overview.mdx) | – | ✅ (3.14+) | ✅ (3.14+) | – | +| [認証/認可](scalardb-cluster/scalardb-auth-with-sql.mdx) | – | ✅ | ✅ | – | +| [暗号化](scalardb-cluster/encrypt-data-at-rest.mdx) | – | – | ✅ (3.14+) | – | +| [属性ベースのアクセス制御](scalardb-cluster/authorize-with-abac.mdx) | – | – | ✅ (3.15+) (Enterprise Premium Option*, Private Preview**) | – | +| [SQL インターフェース (SQL API、JDBC、Spring Data JDBC、および LINQ)](scalardb-sql/index.mdx) | – | – | ✅ | – | +| [GraphQL インターフェース](scalardb-graphql/index.mdx) | – | – | ✅ | – | +| [ベクトル検索インターフェース](scalardb-cluster/getting-started-with-vector-search.mdx) | – | – | ✅ (3.15+) (Private Preview**) | – | +| [ScalarDB 管理下のデータソースをまたがる分析クエリ処理](scalardb-samples/scalardb-analytics-spark-sample/README.mdx) | – | – | – | ✅ (3.14+) | +| [非 ScalarDB 管理下のデータソースをまたがる分析クエリ処理](scalardb-samples/scalardb-analytics-spark-sample/README.mdx) | – | – | – | ✅ (3.15+) | + +\* この機能は Enterprise Premium エディションでは利用できません。この機能を使用したい場合は、[お問い合わせください](https://www.scalar-labs.com/contact)。 + +\*\* この機能は現在、Private Preview です。詳細については、[お問い合わせ](https://www.scalar-labs.com/contact)いただくか、この機能が将来のバージョンで一般公開されるまでお待ちください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/getting-started-with-scalardb-by-using-kotlin.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/getting-started-with-scalardb-by-using-kotlin.mdx new file mode 100644 index 00000000..7d182d98 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/getting-started-with-scalardb-by-using-kotlin.mdx @@ -0,0 +1,419 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kotlin を使って ScalarDB をはじめよう + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +この入門チュートリアルでは、ScalarDB で好みのデータベースを設定し、Kotlin を使用して基本的な電子マネーアプリケーションをセットアップする方法について説明します。Kotlin は Java との相互運用性を備えているため、Kotlin から直接 ScalarDB を使用できます。 + +:::warning + +電子マネーアプリケーションはこのチュートリアル用に簡略化されており、実稼働環境には適していません。 + +::: + +## このサンプルアプリケーションの前提条件 + +ScalarDB は Java で記述されているため、環境に次のいずれかの Java Development Kit (JDK) がインストールされている必要があります。 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10以降と [Docker Compose](https://docs.docker.com/compose/install/) V2以降 + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](./requirements.mdx)を参照してください。 + +::: + +## ScalarDB サンプルリポジトリのクローンを作成する + +**Terminal** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、サンプルアプリケーションが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-kotlin-sample +``` + +## データベースをセットアップする + +データベースを選択し、指示に従って ScalarDB 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](requirements.mdx#データベース)を参照してください。 + + + +

MySQLをローカルで実行する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://localhost:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://localhost:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//localhost:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB をローカルで実行する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://localhost:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントをお持ちでない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを構成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル**を**強力**に設定します。 + +

ScalarDB を設定する

+ + 以下の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。`scalar.db.contact_points` と `scalar.db.password` の値は、説明に従って必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d cassandra + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-kotlin-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +## データベーススキーマをロードする + +アプリケーションでデータベーススキーマ (データを整理する方法) を定義する必要があります。サポートされているデータ型の詳細については、[ScalarDB と他のデータベース間のデータ型マッピング](schema-loader.mdx#scalardb-と他のデータベース間のデータ型マッピング)を参照してください。 + +このチュートリアルでは、**schema.json** というファイルが `scalardb-samples/scalardb-kotlin-sample` ディレクトリに既に存在します。スキーマを適用するには、[`scalardb` Releases](https://github.com/scalar-labs/scalardb/releases) ページに移動し、使用している ScalarDB のバージョンに一致する ScalarDB Schema Loader を `scalardb-samples/scalardb-kotlin-sample` ディレクトリにダウンロードします。 + +次に、データベースに基づいて、`` をダウンロードした ScalarDB Schema Loader のバージョンに置き換えて、次のコマンドを実行します。 + + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator --no-backup --no-scaling + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +また、Amazon DynamoDB Local は継続的なバックアップと自動スケーリングをサポートしていないため、`--no-backup` および `--no-scaling` オプションが指定されています。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator --replication-factor=1 + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +また、`--replication-factor=1` オプションは Cassandra を使用する場合にのみ有効です。デフォルトのレプリケーション係数は `3` ですが、このチュートリアルではセットアップを容易にするために `1` が使用されているため、3つのノードではなく1つのノードを持つクラスターを準備するだけで済みます。ただし、レプリケーション係数 `1` は本番環境には適していないことに注意してください。 + +::: + + + +## 基本的な電子マネーアプリケーションでトランザクションを実行し、データを取得します + +スキーマをロードした後、クローンしたリポジトリに含まれる基本的な電子マネーアプリケーションでトランザクションを実行し、データを取得できます。 + +アプリケーションは、次の種類のトランザクションをサポートしています: + +- アカウントを作成します。 +- アカウントに資金を追加します。 +- 2つのアカウント間で資金を送信します。 +- アカウント残高を取得します。 + +:::note + +初めて Gradle コマンドを実行すると、Gradle によって必要なライブラリが自動的にインストールされます。 + +::: + +### 残高のあるアカウントを作成する + +アカウント間で資金を送金するには、残高のあるアカウントが必要です。 + +**customer1** の残高が **500** のアカウントを作成するには、次のコマンドを実行します。 + +```console +./gradlew run --args="-action charge -amount 500 -to customer1" +``` + +### 残高のないアカウントを作成する + +残高のあるアカウントを設定したら、資金を送金するための別のアカウントが必要です。 + +残高が **0** の **merchant1** のアカウントを作成するには、次のコマンドを実行します。 + +```console +./gradlew run --args="-action charge -amount 0 -to merchant1" +``` + +### アカウントに資金を追加する + +[残高のあるアカウントを作成する](#残高のあるアカウントを作成する)でアカウントを作成して資金を追加したのと同じ方法で、アカウントに資金を追加できます。 + +**customer1** のアカウントに **500** を追加するには、次のコマンドを実行します。 + +```console +./gradlew run --args="-action charge -amount 500 -to customer1" +``` + +**customer1** のアカウントの残高は **1000** になります。 + +### 2つのアカウント間で電子マネーを送金する + +これで 2つのアカウントが作成され、少なくとも1つのアカウントに残高があるので、一方のアカウントからもう一方のアカウントに資金を送金できます。 + +**customer1** が **merchant1** に **100** を支払うようにするには、次のコマンドを実行します。 + +```console +./gradlew run --args="-action pay -amount 100 -from customer1 -to merchant1" +``` + +### アカウント残高を取得する + +あるアカウントから別のアカウントに資金を送金した後、各アカウントの残高を確認できます。 + +**customer1** の残高を取得するには、次のコマンドを実行します。 + +```console +./gradlew run --args="-action getBalance -id customer1" +``` + +次の出力が表示されます。 + +```console +... +The balance for customer1 is 900 +... +``` + +**merchant1** の残高を取得するには、次のコマンドを実行します。 + +```console +./gradlew run --args="-action getBalance -id merchant1" +``` + +次の出力が表示されます。 + +```console +... +The balance for merchant1 is 100 +... +``` + +## データベースを停止する + +データベースを停止するには、次のコマンドを実行して Docker コンテナを停止します。 + +```console +docker compose down +``` + +## 参照 + +このチュートリアルで使用されている電子マネーアプリケーションのソースコードを確認するには、[`ElectronicMoney.kt`](https://github.com/scalar-labs/scalardb-samples/blob/main/scalardb-kotlin-sample/src/main/kotlin/sample/ElectronicMoney.kt) を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/getting-started-with-scalardb.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/getting-started-with-scalardb.mdx new file mode 100644 index 00000000..5a920d81 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/getting-started-with-scalardb.mdx @@ -0,0 +1,538 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB をはじめよう + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +この入門チュートリアルでは、ScalarDB でデータベースを設定する方法について説明し、ScalarDB を使用してクレジットカードでアイテムを注文して支払うことができるサンプルの電子商取引アプリケーションを作成するプロセスを示します。サンプルの電子商取引アプリケーションでは、ユーザーがクレジットラインを使用してアイテムを注文して支払う方法を示します。 + +:::warning + +サンプルアプリケーションは ScalarDB の使用方法を示すことに重点を置いているため、アプリケーション固有のエラー処理、認証処理、および同様の機能はサンプルアプリケーションに含まれていません。ScalarDB での例外処理の詳細については、[例外の処理方法](api-guide.mdx#how-to-handle-exceptions)を参照してください。 + +::: + +## このサンプルアプリケーションの前提条件 + +ScalarDB は Java で記述されているため、環境に次のいずれかの Java Development Kit (JDK) がインストールされている必要があります。 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10以降と [Docker Compose](https://docs.docker.com/compose/install/) V2以降 + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](./requirements.mdx)を参照してください。 + +::: + +## ScalarDB サンプルリポジトリのクローンを作成する + +**Terminal** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、サンプルアプリケーションが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-sample +``` + +## データベースをセットアップする + +データベースを選択し、指示に従って ScalarDB 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](requirements.mdx#データベース)を参照してください。 + + + +

MySQLをローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://localhost:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://localhost:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//localhost:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://localhost:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントをお持ちでない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを構成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル**を**強力**に設定します。 + +

ScalarDB を設定する

+ + 以下の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。`scalar.db.contact_points` と `scalar.db.password` の値は、説明に従って必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + ```console + docker compose up -d cassandra + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +## データベーススキーマをロードする + +アプリケーションでデータベーススキーマ (データを整理する方法) を定義する必要があります。サポートされているデータ型の詳細については、[ScalarDB と他のデータベース間のデータ型マッピング](schema-loader.mdx#scalardb-と他のデータベース間のデータ型マッピング)を参照してください。 + +このチュートリアルでは、**schema.json** というファイルが `scalardb-samples/scalardb-sample` ディレクトリに既に存在します。スキーマを適用するには、[`scalardb` Releases](https://github.com/scalar-labs/scalardb/releases) ページに移動し、使用している ScalarDB のバージョンに一致する ScalarDB Schema Loader を `scalardb-samples/scalardb-sample` ディレクトリにダウンロードします。 + +次に、データベースに基づいて、`` をダウンロードした ScalarDB Schema Loader のバージョンに置き換えて、次のコマンドを実行します。 + + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator --no-backup --no-scaling + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +また、Amazon DynamoDB Local は継続的なバックアップと自動スケーリングをサポートしていないため、`--no-backup` および `--no-scaling` オプションが指定されています。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator --replication-factor=1 + ``` + +:::note + +`transaction` が `true` に設定されたテーブルがスキーマ内に存在するため、`--coordinator` オプションが指定されています。スキーマの設定とロードの詳細については、[ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 + +また、`--replication-factor=1` オプションは Cassandra を使用する場合にのみ有効です。デフォルトのレプリケーション係数は `3` ですが、このチュートリアルではセットアップを容易にするために `1` が使用されているため、3つのノードではなく1つのノードを持つクラスターを準備するだけで済みます。ただし、レプリケーション係数 `1` は本番環境には適していないことに注意してください。 + +::: + + + +### スキーマの詳細 + +サンプルアプリケーションの [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sample/schema.json) に示されているように、すべてのテーブルは `sample` 名前空間に作成されます。 + +- `sample.customers`: 顧客情報を管理するテーブル + - `credit_limit`: 貸し手が顧客に信用枠から支出を許可する最大金額 + - `credit_total`: 顧客が信用枠から支出した金額 +- `sample.orders`: 注文情報を管理するテーブル +- `sample.statements`: 注文明細情報を管理するテーブル +- `sample.items`: 注文するアイテムの情報を管理するテーブル + +スキーマのエンティティ関係図は次のとおりです。 + +![ERD](images/getting-started-ERD.png) + +### 初期データをロードする + +サンプルアプリケーションを実行する前に、次のコマンドを実行して初期データをロードする必要があります。 + +```console +./gradlew run --args="LoadInitialData" +``` + +初期データがロードされた後、次のレコードがテーブルに保存される必要があります。 + +**`sample.customers` テーブル** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` テーブル** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションでトランザクションを実行し、データを取得する + +次のセクションでは、サンプル電子商取引アプリケーションでトランザクションを実行し、データを取得する方法について説明します。 + +### 顧客情報を取得する + +まず、次のコマンドを実行して、ID が `1` である顧客に関する情報を取得します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 0} +... +``` + +### 注文する + +次に、次のコマンドを実行して、顧客 ID `1` にリンゴ3個とオレンジ2個を注文してもらいます。 + +:::note + +このコマンドの注文形式は `./gradlew run --args="PlaceOrder :,:,..."` です。 + +::: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +... +{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e"} +... +``` + +### 注文の詳細を確認する + +次のコマンドを実行して注文の詳細を確認します。`` は、前のコマンドを実行した後に表示される `order_id` の UUID に置き換えます。 + +```console +./gradlew run --args="GetOrder " +``` + +`order_id` と `timestamp` の UUID が異なる、以下のような出力が表示されます。 + +```console +... +{"order": {"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +### 別の注文をする + +次のコマンドを実行して、顧客 ID `1` の `credit_total` の残額を使用してメロン1個を注文します。 + +```console +./gradlew run --args="PlaceOrder 1 5:1" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +... +{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d"} +... +``` + +### 注文履歴を確認する + +次のコマンドを実行して、顧客 ID `1` のすべての注文履歴を取得します。 + +```console +./gradlew run --args="GetOrders 1" +``` + +`order_id` と `timestamp` の UUID が異なる以下のような出力が表示されます。これは、顧客 ID `1` のすべての注文履歴をタイムスタンプの降順で表示します。 + +```console +... +{"order": [{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000},{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d","timestamp": 1650948412766,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000}]} +... +``` + +### クレジット合計を確認する + +次のコマンドを実行して、顧客 ID `1` のクレジット合計を取得します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。これは、顧客 ID `1` が `credit_total` の `credit_limit` に達しており、これ以上注文できないことを示しています。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +``` + +次のコマンドを実行して、ブドウ1個とマンゴー1個を注文してみます。 + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +次の出力が表示されます。これは、`credit_total` 金額が `credit_limit` 金額を超えたために注文が失敗したことを示しています。 + +```console +... +java.lang.RuntimeException: Credit limit exceeded + at sample.Sample.placeOrder(Sample.java:205) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:33) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:8) + at picocli.CommandLine.executeUserObject(CommandLine.java:1783) + at picocli.CommandLine.access$900(CommandLine.java:145) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2141) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2108) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:1975) + at picocli.CommandLine.execute(CommandLine.java:1904) + at sample.command.SampleCommand.main(SampleCommand.java:35) +... +``` + +### 支払いを行う + +注文を続行するには、顧客 ID `1` が支払いを行って `credit_total` の金額を減らす必要があります。 + +次のコマンドを実行して支払いを行います。 + +```console +./gradlew run --args="Repayment 1 8000" +``` + +次に、次のコマンドを実行して、顧客 ID `1` の `credit_total` 金額を確認します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。これは、顧客 ID `1` に支払いが適用され、`credit_total` の金額が減ったことを示しています。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 2000} +... +``` + +顧客 ID `1` が支払いを済ませたので、次のコマンドを実行してブドウ1個とメロン1個を注文します。 + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +... +{"order_id": "8911cab3-1c2b-4322-9386-adb1c024e078"} +... +``` + +## データベースを停止する + +データベースを停止するには、次のコマンドを実行して Docker コンテナを停止します。 + +```console +docker compose down +``` + +## 参照 + +このチュートリアルで使用される電子商取引アプリケーションのソースコードを確認するには、[`Sample.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/scalardb-sample/src/main/java/sample/Sample.java) を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/glossary.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/glossary.mdx new file mode 100644 index 00000000..b9133a20 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/glossary.mdx @@ -0,0 +1,119 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 用語集 + +この用語集には、ScalarDB を使用するときによく使用されるデータベースおよび分散システムの用語が含まれています。 + +## グローバルトランザクション + +グローバルトランザクションは複数のデータベースまたは分散システムにまたがり、関係するすべてのシステムが単一のユニットとして変更をコミットまたはロールバックすることを保証します。 + +## コンセンサス + +分散システムにおけるコンセンサスとは、単一のデータ値またはシステム状態について複数のコンピューターまたはノード間で合意を得るプロセスを指します。 + +## 直列化可能な分離 + +直列化可能な分離は、トランザクションシステムにおける最高の分離レベルであり、同時に実行されるトランザクションの結果が、順番に実行された場合と同じになることを保証します。 + +## スナップショット分離 + +スナップショット分離は、トランザクションがデータベースの一貫したスナップショットを読み取ることを可能にする分離レベルです。これにより、トランザクションが完了するまで、他のトランザクションによる変更が表示されなくなります。 + +## データフェデレーション + +データフェデレーションとは、データを移動せずにさまざまなソースのデータを統合し、クエリと分析のための統一されたビューを作成するプロセスです。 + +## データメッシュ + +データメッシュは、企業内のデータを各ビジネスドメインが自律的に管理し、データを効率的に利活用できるようにする分散型のデータアーキテクチャです。 + +## データ仮想化 + +データ仮想化は多くの点でデータフェデレーションに似ています。つまり、複数のデータソースを統一されたビューに仮想化し、データを移動せずにクエリを簡素化します。 + +## データベース異状 + +データベース異状とは、挿入、更新、削除などの操作が適切なトランザクション管理なしで実行されたときに発生する可能性があるデータの不整合またはエラーです。 + +## トランザクション + +データベース内のトランザクションは、単一の論理作業単位として扱われる一連の操作であり、一貫性と整合性を確保し、通常は ACID プロパティに準拠します。 + +## トランザクションマネージャー + +トランザクションマネージャーは、複数のシステムまたはデータベースにわたるトランザクションの実行を調整し、トランザクションのすべてのステップが1つの単位として成功または失敗することを保証します。 + +## フェデレーションエンジン + +フェデレーションエンジンは、多くの場合、データフェデレーションアーキテクチャの一部として、複数の異なるデータソース間でのデータ統合とクエリを容易にします。 + +## ポリストア + +ポリストアは、ユーザーが、特定のワークロードまたはデータタイプに合わせて最適化された複数の異種データストアを、あたかも単一のシステムであるかのように操作できるようにするデータベースアーキテクチャです。 + +## リレーショナルデータベース + +リレーショナルデータベースは、行と列を持つテーブルにデータを格納し、構造化クエリ言語 (SQL) を使用してデータを定義、クエリ、および操作します。 + +## レプリケーション + +データベースのレプリケーションでは、信頼性、可用性、およびフォールトトレランスを確保するために、複数のマシンまたは場所にデータをコピーして配布します。 + +## 線形化可能性 + +線形化可能性は、分散システムにおける強力な一貫性モデルであり、操作はリアルタイム順序付けと一致する順序でアトミックに発生し、各操作は開始から終了までの間に有効になります。 + +## 並行性制御 + +データベースの並行性制御は、通常、ロックやタイムスタンプ順序付けなどのメカニズムを通じて、データの不整合を引き起こすことなく複数のトランザクションが同時に発生することを保証します。 + +## 読み取りコミット分離 + +読み取りコミット分離は、各トランザクションがコミットされたデータのみを参照する分離レベルです。ダーティリードは防止されますが、反復不可能な読み取りは許可されます。 + +## 異種データベース + +異種データベースとは、異なるデータモデル、クエリ言語、およびトランザクションメカニズムを持つ可能性のある、異なるデータベーステクノロジで構成されたシステムのことです。 + +## 2フェーズコミット + +2フェーズコミットは、分散トランザクションのすべての参加者がトランザクションをコミットまたはロールバックし、システム間の一貫性を保証するためのプロトコルです。 + +## ACID + +原子性、一貫性、独立性、耐久性 (ACID) は、データベーストランザクションが確実に処理され、エラーやシステム障害が発生した場合でも整合性が維持されるようにする一連の特性です。 + +## HTAP + +ハイブリッドトランザクション/分析処理 (HTAP) とは、トランザクションワークロードと分析ワークロードの両方を同じデータセットで同時に処理できるシステムのことです。これにより、個別のデータベースが不要になります。 + +## JDBC + +Java Database Connectivity (JDBC) は、Java アプリケーションがデータベースと対話できるようにする API であり、リレーショナルデータベースでデータをクエリおよび更新するための方法を提供します。 + +## NoSQL データベース + +NoSQL データベースは、ドキュメント、キー値、ワイドカラム、グラフストアなどの特定のデータモデル向けに設計された非リレーショナルデータベースであり、大規模な分散データの処理によく使用されます。 + +## Paxos + +Paxos は、ノード障害が発生した場合でも合意を得るために分散システムで使用されるプロトコルのファミリーです。 + +## PITR + +ポイントインタイムリカバリ (PITR) を使用すると、通常はデータ破損などの意図しないイベントが発生した後に、データベースを特定の時間に以前の状態に復元できます。 + +## Saga + +Saga パターンは、分散システムで長時間実行されるトランザクションを管理する方法です。トランザクション内の各操作の後に、障害が発生した場合の補償アクションが続きます。 + +## TCC + +Try-Confirm/Cancel (TCC) は、操作を3つのステップに分割し、複数のシステム間での調整と回復を可能にする分散トランザクションのパターンです。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/conf/scalar-loki-stack-custom-values.yaml b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/conf/scalar-loki-stack-custom-values.yaml new file mode 100644 index 00000000..997537a5 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/conf/scalar-loki-stack-custom-values.yaml @@ -0,0 +1,80 @@ +promtail: + config: + snippets: + # -- `scapeConfigs` is exactly the part of https://grafana.com/docs/loki/latest/clients/promtail/configuration/#scrape_configs + # -- The value will be created as a Kubernetes ConfigMap and then mounted to the Promtail Pod. + # -- Not really need to change this value. It's set to scrape all logs of ScalarDL/DB Pods by using regular expression. + scrapeConfigs: | + # -- the `scalardl` job scrapes all the logs from Scalar Ledger Pods, Scalar Auditor Pods, and the corresponding Envoy Pods + - job_name: scalardl + pipeline_stages: + - docker: {} + kubernetes_sd_configs: + - role: pod + relabel_configs: + - source_labels: + - __meta_kubernetes_pod_node_name + target_label: __host__ + - action: replace + source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - action: keep + regex: (.*)scalardl-(.+) + source_labels: + - pod + - replacement: /var/log/pods/*$1/*.log + separator: / + source_labels: + - __meta_kubernetes_pod_uid + - __meta_kubernetes_pod_container_name + target_label: __path__ + # -- the `scalardb` job scrapes all the logs of ScalarDB Server Pods and the corresponding Envoy Pods + - job_name: scalardb + pipeline_stages: + - docker: {} + kubernetes_sd_configs: + - role: pod + relabel_configs: + - source_labels: + - __meta_kubernetes_pod_node_name + target_label: __host__ + - action: replace + source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - action: keep + regex: (.*)scalardb-(.+) + source_labels: + - pod + - replacement: /var/log/pods/*$1/*.log + separator: / + source_labels: + - __meta_kubernetes_pod_uid + - __meta_kubernetes_pod_container_name + target_label: __path__ + # -- the `scalar-admin-for-kubernetes` job scrapes all the logs of Scalar Admin for Kubernetes Pods + - job_name: scalar-admin-for-kubernetes + pipeline_stages: + - docker: {} + - cri: {} + kubernetes_sd_configs: + - role: pod + relabel_configs: + - source_labels: + - __meta_kubernetes_pod_node_name + target_label: __host__ + - action: replace + source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - action: keep + regex: (.*)scalar-admin-for-kubernetes-(.+) + source_labels: + - pod + - replacement: /var/log/pods/*$1/*.log + separator: / + source_labels: + - __meta_kubernetes_pod_uid + - __meta_kubernetes_pod_container_name + target_label: __path__ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/conf/scalar-prometheus-custom-values.yaml b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/conf/scalar-prometheus-custom-values.yaml new file mode 100644 index 00000000..816ead1b --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/conf/scalar-prometheus-custom-values.yaml @@ -0,0 +1,167 @@ +defaultRules: + # -- Default PrometheusRules are not enabled + create: false + +alertmanager: + # -- alertmanager is enabled + enabled: true + + # -- Only check own namespace + alertmanagerConfigNamespaceSelector: null + +grafana: + # -- grafana is enabled + enabled: true + + # -- Default Grafana dashboards are not enabled + defaultDashboardsEnabled: false + + sidecar: + datasources: + enabled: true + defaultDatasourceEnabled: false + label: grafana_datasource + labelValue: "1" + dashboards: + enabled: true + label: grafana_dashboard + labelValue: "1" + # -- Resource limits & requests + resources: {} + # requests: + # memory: 400Mi + + # -- Grafana's primary configuration + grafana.ini: + security: + # -- allow Grafana to be embedded (not set the X-Frame-Options header) + # -- If you use Scalar Manager, you need to set allow_embedding to true. + # -- https://grafana.com/docs/grafana/latest/administration/configuration/#allow_embedding + allow_embedding: false + + # -- Additional data source configurations + additionalDataSources: + - name: Prometheus + type: prometheus + uid: prometheus + url: http://scalar-monitoring-kube-pro-prometheus:9090/ + access: proxy + editable: false + isDefault: false + jsonData: + timeInterval: 30s + # - name: Loki + # type: loki + # uid: loki + # url: http://scalar-logging-loki:3100/ + # access: proxy + # editable: false + # isDefault: false + +kubeApiServer: + # -- Scraping kube-apiserver is disabled + enabled: false + +kubeControllerManager: + # -- Scraping kube-controller-manager is disabled + enabled: false + +coreDns: + # -- Scraping CoreDNS is disabled + enabled: false + +kubeEtcd: + # -- Scraping etcd is disabled + enabled: false + +kubeScheduler: + # -- Scraping kube-scheduler is disabled + enabled: false + +kubeProxy: + # -- Scraping kube-proxy is disabled + enabled: false + +kubelet: + # -- Scraping kubelet is disabled + enabled: false + +kubeStateMetrics: + # -- kube-state-metrics is disabled + enabled: false + +nodeExporter: + # -- node-exporter is disabled + enabled: false + +prometheusOperator: + # -- Prometheus Operator is enabled + enabled: true + + admissionWebhooks: + patch: + # -- Resource limits & requests + resources: {} + # requests: + # memory: 400Mi + + namespaces: + # -- Only check own namespace + releaseNamespace: true + + kubeletService: + # -- kubelet service for scraping kubelets is disabled + enabled: false + + ## -- Resource limits & requests + resources: {} + # requests: + # memory: 400Mi + +prometheus: + # -- Prometheus is enabled + enabled: true + + prometheusSpec: + # -- All PrometheusRules are enabled + ruleSelectorNilUsesHelmValues: false + + # -- Only check own namespace + ruleNamespaceSelector: {} + + # -- All ServiceMonitors are enabled + serviceMonitorSelectorNilUsesHelmValues: false + + # -- Only check own namespace + serviceMonitorNamespaceSelector: {} + + # -- All PodMonitors are enabled + podMonitorSelectorNilUsesHelmValues: false + + # -- Only check own namespace + podMonitorNamespaceSelector: {} + + # -- All Probes are enabled + probeSelectorNilUsesHelmValues: false + + # -- Only check own namespace + probeNamespaceSelector: {} + + ## -- Resource limits & requests + resources: {} + # requests: + # memory: 400Mi + + ## -- Prometheus StorageSpec for persistent data + ## ref: https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/user-guides/storage.md + storageSpec: {} + ## Using PersistentVolumeClaim + ## + # volumeClaimTemplate: + # spec: + # storageClassName: gluster + # accessModes: ["ReadWriteOnce"] + # resources: + # requests: + # storage: 50Gi + # selector: {} diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-envoy.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-envoy.mdx new file mode 100644 index 00000000..5bb4ae66 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-envoy.mdx @@ -0,0 +1,393 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar Envoy のカスタム値ファイルを構成する + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +このドキュメントでは、Scalar Envoy チャートのカスタム値ファイルを作成する方法について説明します。パラメータの詳細を知りたい場合は、Scalar Envoy チャートの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/envoy/README.md) を参照してください。 + +## Scalar Envoy チャートのカスタム値を構成する + +Scalar Envoy チャートは他のチャート (scalardb、scalardb-cluster、scalardl、scalardl-audit) 経由で使用されるため、Scalar Envoy チャートのカスタム値ファイルを作成する必要はありません。Scalar Envoy を設定したい場合は、`envoy.*` 設定を他のチャートに追加する必要があります。 + +たとえば、ScalarDB Server 用に Scalar Envoy を構成する場合は、次のように ScalarDB のカスタム値ファイルでいくつかの Scalar Envoy 構成を構成できます。 + +* 例 (scalardb-custom-values.yaml) + ```yaml + envoy: + configurationsForScalarEnvoy: + ... + + scalardb: + configurationsForScalarDB: + ... + ``` + +## 必要な構成 + +### サービス構成 + +Kubernetes のサービスリソースタイプを指定するには、`envoy.service.type` を設定する必要があります。 + +Kubernetes クラスターの内部からのみクライアントリクエストを受け入れる場合 (たとえば、クライアントアプリケーションを Scalar 製品と同じ Kubernetes クラスターにデプロイする場合)、`envoy.service.type` を `ClusterIP` に設定できます。この構成では、クラウドサービスプロバイダーが提供するロードバランサーは作成されません。 + +```yaml +envoy: + service: + type: ClusterIP +``` + +クラウドサービスプロバイダーが提供するロードバランサーを使用して、Kubernetes クラスターの外部からのクライアントリクエストを受け入れる場合は、`envoy.service.type` を `LoadBalancer` に設定する必要があります。 + +```yaml +envoy: + service: + type: LoadBalancer +``` + +アノテーションを介してロードバランサを設定したい場合は、アノテーションを `envoy.service.annotations` に設定することもできます。 + +```yaml +envoy: + service: + type: LoadBalancer + annotations: + service.beta.kubernetes.io/aws-load-balancer-internal: "true" + service.beta.kubernetes.io/aws-load-balancer-type: "nlb" +``` + +## オプションの構成 + +### リソース構成 (本番環境で推奨) + +Kubernetes のリクエストと制限を使用してポッドリソースを制御したい場合は、`envoy.resources` を使用できます。 + +これらは、Kubernetes のリクエストと制限と同じ構文を使用して構成できます。そのため、Kubernetes の要求と制限の詳細については、公式ドキュメント [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) を参照してください。 + +```yaml +envoy: + resources: + requests: + cpu: 1000m + memory: 2Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### アフィニティ構成 (運用環境で推奨) + +Kubernetes のアフィニティと反アフィニティを使用してポッドのデプロイメントを制御したい場合は、`envoy.affinity` を使用できます。 + +Kubernetes のアフィニティと同じ構文を使用して構成できます。そのため、Kubernetes のアフィニティ設定の詳細については、公式ドキュメント [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) を参照してください。 + +```yaml +envoy: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardb-cluster + - key: app.kubernetes.io/app + operator: In + values: + - envoy + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus および Grafana 構成 (実稼働環境で推奨) + +[kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) を使用して Scalar Envoy ポッドを監視する場合は、`envoy.grafanaDashboard.enabled`、`envoy.serviceMonitor` を使用して、kube-prometheus-stack の ConfigMap、ServiceMonitor、および PrometheusRule リソースをデプロイできます。`envoy.prometheusRule.enabled` と `envoy.prometheusRule.enabled`。 + +```yaml +envoy: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext 設定 (デフォルト値を推奨) + +Scalar Envoy ポッドに SecurityContext と PodSecurityContext を設定する場合は、`envoy.securityContext` と `envoy.podSecurityContext` を使用できます。 + +Kubernetes の SecurityContext や PodSecurityContext と同じ構文を使用して設定できます。したがって、Kubernetes の SecurityContext および PodSecurityContext 構成の詳細については、公式ドキュメント [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) を参照してください。 + +```yaml +envoy: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### 画像構成 (デフォルト値を推奨) + +イメージリポジトリとバージョンを変更したい場合は、`envoy.image.repository` を使用して、プルする Scalar Envoy コンテナイメージのコンテナリポジトリ情報を指定できます。 + +```yaml +envoy: + image: + repository: +``` + +AWS または Azure を使用している場合、詳細については次のドキュメントを参照してください。 + +* [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) +* [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +### TLS 構成 (環境に応じてオプション) + +以下の通信で TLS を有効にできます。 + +- クライアントと Scalar Envoy 間のダウンストリーム接続。 +- Scalar Envoy と Scalar 製品間のアップストリーム接続。 + +さらに、次の2つの観点からいくつかのオプションがあります。 + +1. 秘密鍵と証明書ファイルの管理 + 1. [cert-manager](https://cert-manager.io/docs/) を使用して秘密鍵と証明書ファイルを自動的に管理します。 + - メンテナンスや運用のコストを削減できます。たとえば、cert-manager は証明書の有効期限が切れる前に自動的に更新し、Scalar Helm Chart は秘密鍵と証明書ファイルを Scalar 製品ポッドに自動的にマウントします。 + - cert-manager がサポートしていない CA は使用できません。サポートされている発行元は [cert-manager ドキュメント](https://cert-manager.io/docs/configuration/issuers/)で確認できます。 + 1. 秘密鍵と証明書ファイルを手動で管理します。 + - ご自身のお好みの方法で、秘密鍵と証明書ファイルを発行・管理することができます。 + - cert-manager がサポートしていない場合でも、任意の証明書を使用できます。 + - 証明書の有効期限が切れた場合は、シークレットリソースを更新する必要があります。 +1. 証明書の種類 + 1. 信頼できる CA (サードパーティによる署名付き証明書) を使用します。 + - サードパーティの証明書発行者からの信頼できる証明書を使用できます。 + - パケットを暗号化できます。 + - 信頼できる証明書を発行するには費用を支払う必要があります。 + 1. 自己署名証明書を使用します。 + - 証明書発行にかかるコストを削減できます。 + - 証明書の信頼性は信頼できる CA よりも低くなりますが、パケットを暗号化できます。 + +つまり、次の4つのオプションがあります。 + +1. 自動管理で自己署名 CA を使用します。 +1. 自動管理で信頼できる CA を使用します。 +1. 手動管理で自己署名 CA を使用します。 +1. 手動管理で信頼できる CA を使用します。 + +セキュリティ要件に基づいて、どの方法を使用するかを検討する必要があります。各方法のガイダンスと関連ドキュメントについては、次の意思決定ツリーを参照してください。 + +```mermaid +flowchart TD + A[cert-manager を使用して
秘密鍵と証明書ファイルを
自動的に管理しますか?] + A -->|はい、証明書を自動的に
管理したいです。| B + A -->|いいえ、証明書は自分で手動で
管理したいです。| C + B[自己署名 CA と
信頼された CA の
どちらを使用しますか?] + C[自己署名 CA と
信頼された CA の
どちらを使用しますか?] + B -->|自己署名 CA を
使用したいです。| D + B -->|信頼できる CA
を使用したいです。| E + C -->|自己署名 CA
を使用したいです。| F + C -->|信頼できる CA
を使用したいです。| G + D[cert-manager で自己署名 CA を使用して
秘密鍵と証明書ファイルを管理する

を参照してください。] + E[cert-manager で信頼できる CA を使用して
秘密鍵と証明書ファイルを管理する

を参照してください。] + F[秘密鍵と証明書ファイルを使用するを参照し、
生成した自己署名証明書を使用します。] + G[秘密鍵と証明書ファイルを使用するを参照し、
第三者によって生成された
信頼できる証明書を使用します。] +``` + +#### ダウンストリーム接続で TLS を有効にする + +次の設定により、ダウンストリーム接続で TLS を有効にできます。 + +```yaml +envoy: + tls: + downstream: + enabled: true +``` + +##### 秘密鍵と証明書ファイルを使用する + +次の構成を使用して、秘密鍵と証明書ファイルを設定できます。 + +```yaml +envoy: + tls: + downstream: + enabled: true + certChainSecret: "envoy-tls-cert" + privateKeySecret: "envoy-tls-key" +``` + +この場合、次のように山括弧内の内容を置き換えて、Scalar Envoy の秘密鍵と証明書ファイルを含むシークレットリソースを作成する必要があります。 + +```console +kubectl create secret generic envoy-tls-cert --from-file=tls.crt=/ -n +kubectl create secret generic envoy-tls-key --from-file=tls.key=/ -n +``` + +秘密鍵と証明書ファイルの準備方法の詳細については、[Scalar 製品の秘密鍵と証明書ファイルの作成方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx)を参照してください。 + + +##### cert-manager で信頼できる CA を使用して秘密鍵と証明書ファイルを管理する + +次の構成を使用して、山括弧内の内容を説明に従って置き換えることで、cert-manager で秘密鍵と証明書ファイルを管理できます。 + +:::note + +* cert-manager を使用する場合は、cert-manager をデプロイし、`Issuers` リソースを準備する必要があります。詳細については、cert-manager のドキュメント、[インストール](https://cert-manager.io/docs/installation/)および[発行者構成](https://cert-manager.io/docs/configuration/)を参照してください。 +* デフォルトでは、Scalar Helm Chart は Scalar 製品の証明書要件を満たす `Certificate` リソースを作成します。デフォルトの証明書構成が推奨されますが、カスタム証明書構成を使用する場合は、Scalar 製品の証明書要件を満たす必要があります。詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements)を参照してください。 + +::: + +```yaml +envoy: + tls: + downstream: + enabled: true + certManager: + enabled: true + issuerRef: + name: + dnsNames: + - envoy.scalar.example.com +``` + +この場合、cert-manager は信頼できる発行者を使用して秘密鍵と証明書ファイルを発行します。cert-manager を使用すると、秘密鍵と証明書ファイルを手動でマウントする必要がなくなります。 + +##### cert-manager で自己署名 CA を使用して秘密鍵と証明書ファイルを管理する + +次の構成を使用して、cert-manager で秘密鍵と自己署名証明書ファイルを管理できます。 + +:::note + +* cert-manager を使用する場合は、cert-manager をデプロイする必要があります。詳細については、cert-manager のドキュメント [インストール](https://cert-manager.io/docs/installation/)を参照してください。 +* デフォルトでは、Scalar Helm Chart は Scalar 製品の証明書要件を満たす `Certificate` リソースを作成します。デフォルトの証明書構成が推奨されますが、カスタム証明書構成を使用する場合は、Scalar 製品の証明書要件を満たす必要があります。詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements)を参照してください。 + +::: + +```yaml +envoy: + tls: + downstream: + enabled: true + certManager: + enabled: true + selfSigned: + enabled: true + dnsNames: + - envoy.scalar.example.com +``` + +この場合、Scalar Helm Charts と cert-manager が秘密鍵と自己署名証明書ファイルを発行します。秘密鍵と証明書ファイルを手動でマウントする必要はありません。 + +#### アップストリーム接続で TLS を有効にする + +次の設定により、アップストリーム接続で TLS を有効にできます。 + +```yaml +envoy: + tls: + upstream: + enabled: true +``` + +また、アップストリーム Scalar 製品のルート CA 証明書ファイルを設定する必要があります。どのアプローチを取るべきかを判断するには、次の意思決定ツリーを参照してください。 + +```mermaid +flowchart TD + A[cert-manager を利用しますか?] + A -->|はい| B + A -->|いいえ| D + B[cert-manager で自己証明書を利用しますか?] + B -->|いいえ| C[cert-manager を使用して Envoy とアップストリームの Scalar 製品に同じ 信頼できる CAを利用しますか?] + C -->|いいえ| D[手動で アップストリームのScalar製品のルートCA証明書を設定する必要があります。] + C ---->|Yes| E[Scalar Helm Chart はルート CA 証明書を自動的に設定します。`envoy.tls.upstream.caRootCertSecret` を明示的に設定する必要はありません。] + B ---->|Yes| E +``` + +##### アップストリーム Scalar 製品のルート CA 証明書ファイルを設定する + +次の構成を使用して、ルート CA 証明書ファイルを設定できます。 + +```yaml +envoy: + tls: + upstream: + enabled: true + caRootCertSecret: "envoy-upstream-scalardb-cluster-root-ca" +``` + +この場合、次のように CA 証明書ファイルを含むシークレットリソースを作成する必要があります。使用するアップストリーム (ScalarDB Cluster、ScalarDL Ledger、または ScalarDL Auditor) に基づいてルート CA 証明書ファイルを設定する必要があります。説明されているように、山括弧内の内容を必ず置き換えてください。 + + + + ```console + kubectl create secret generic envoy-upstream-scalardb-cluster-root-ca --from-file=ca.crt=/ -n + ``` + + + ```console + kubectl create secret generic envoy-upstream-scalardl-ledger-root-ca --from-file=ca.crt=/ -n + ``` + + + ```console + kubectl create secret generic envoy-upstream-scalardl-auditor-root-ca --from-file=ca.crt=/ -n + ``` + + + +秘密鍵と証明書ファイルを準備する方法の詳細については、[Scalar 製品のキーと証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx)を参照してください。 + +##### TLS通信のカスタム権限を設定する + +`envoy.tls.upstream.overrideAuthority` を使用して、TLS 通信のカスタム権限を設定できます。この値によって、実際に接続されているホストが変わることはありません。この値はテスト用ですが、DNS オーバーライドの代替としてテスト以外でも安全に使用できます。たとえば、使用している製品に応じて、`scalardbCluster.tls.certChainSecret`、`ledger.tls.certChainSecret`、または `auditor.tls.certChainSecret` を使用して設定した証明書チェーンファイルに示されているホスト名を指定できます。Envoy はこの値を使用して、ScalarDB Cluster または ScalarDL との TLS 接続の証明書を検証します。 + +```yaml +envoy: + tls: + upstream: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" +``` + +### レプリカ構成 (環境に応じてオプション) + +Scalar Envoy のレプリカ (ポッド) の数は、`envoy.replicaCount` を使用して指定できます。 + +```yaml +envoy: + replicaCount: 3 +``` + +### 汚染と許容の構成 (環境に応じてオプション) + +Kubernetes のテイントと許容を使用してポッドのデプロイメントを制御したい場合は、`envoy.tolerations` を使用できます。 + +Kubernetes の許容と同じ構文を使用して、テイントと許容を構成できます。Kubernetes での許容設定の詳細については、Kubernetes の公式ドキュメント [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) を参照してください。 + +```yaml +envoy: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-file.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-file.mdx new file mode 100644 index 00000000..b2ddeb0c --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-file.mdx @@ -0,0 +1,25 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar Helm Charts のカスタム値ファイルを構成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Scalar Helm Chart を使用して Scalar 製品をデプロイする場合は、環境に基づいてカスタム値ファイルを準備する必要があります。各製品のカスタム値ファイルの作成方法の詳細については、次のドキュメントを参照してください。 + +* [ScalarDB Cluster](configure-custom-values-scalardb-cluster.mdx) +* [ScalarDB Analytics with PostgreSQL](configure-custom-values-scalardb-analytics-postgresql.mdx) +* [ScalarDL Ledger](configure-custom-values-scalardl-ledger.mdx) +* [ScalarDL Auditor](configure-custom-values-scalardl-auditor.mdx) +* [ScalarDL Schema Loader](configure-custom-values-scalardl-schema-loader.mdx) +* [Scalar Admin for Kubernetes](configure-custom-values-scalar-admin-for-kubernetes.mdx) +* [Scalar Manager](configure-custom-values-scalar-manager.mdx) +* [Envoy](configure-custom-values-envoy.mdx) +* [[Deprecated] ScalarDB Server](configure-custom-values-scalardb.mdx) +* [[Deprecated] ScalarDB GraphQL](configure-custom-values-scalardb-graphql.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalar-admin-for-kubernetes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalar-admin-for-kubernetes.mdx new file mode 100644 index 00000000..a25f7733 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalar-admin-for-kubernetes.mdx @@ -0,0 +1,140 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar Admin for Kubernetes のカスタム値ファイルを構成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Scalar Admin for Kubernetes チャートのカスタム値ファイルを作成する方法について説明します。パラメーターの詳細については、Scalar Admin for Kubernetes チャートの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalar-admin-for-kubernetes/README.md) を参照してください。 + +## 必要な構成 + +このセクションでは、Scalar Admin for Kubernetes のカスタム値ファイルをセットアップするときに必要な構成について説明します。 + +### フラグ設定 + +Scalar Admin for Kubernetes を実行するには、配列として `scalarAdminForKubernetes.commandArgs` にいくつかのオプションを指定する必要があります。オプションの詳細については、Scalar Admin for Kubernetes の [README](https://github.com/scalar-labs/scalar-admin-for-kubernetes/blob/main/README.md) を参照してください。 + +```yaml +scalarAdminForKubernetes: + commandArgs: + - -r + - + - -n + - + - -d + - + - -z + - +``` + +## オプションの構成 + +このセクションでは、Scalar Admin for Kubernetes のカスタム値ファイルをセットアップするときのオプションの構成について説明します。 + +### CronJob 構成 (環境に応じてオプション) + +デフォルトでは、Scalar Admin for Kubernetes チャートは、Scalar Admin for Kubernetes CLI ツールを1回実行するための [Job](https://kubernetes.io/docs/concepts/workloads/controllers/job/) リソースを作成します。[CronJob](https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/) を使用して Scalar Admin for Kubernetes CLI ツールを定期的に実行する場合は、`scalarAdminForKubernetes.jobType` を `cronjob` に設定できます。また、CronJob リソースのいくつかの構成を設定することもできます。 + +```yaml +scalarAdminForKubernetes: + cronJob: + timeZone: "Etc/UTC" + schedule: "0 0 * * *" +``` + +### リソース構成 (実稼働環境で推奨) + +Kubernetes でリクエストと制限を使用してポッドリソースを制御するには、`scalarAdminForKubernetes.resources` を使用できます。 + +Kubernetes のリクエストと制限と同じ構文を使用して、リクエストと制限を構成できます。Kubernetes のリクエストと制限の詳細については、[Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) を参照してください。 + +```yaml +scalarAdminForKubernetes: + resources: + requests: + cpu: 1000m + memory: 2Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### SecurityContext 設定 (デフォルト値を推奨) + +Scalar Admin for Kubernetes ポッドの SecurityContext と PodSecurityContext を設定するには、`scalarAdminForKubernetes.securityContext` と `scalarAdminForKubernetes.podSecurityContext` を使用できます。 + +Kubernetes の SecurityContext および PodSecurityContext と同じ構文を使用して、SecurityContext および PodSecurityContext を構成できます。Kubernetes の SecurityContext および PodSecurityContext 構成の詳細については、[Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) を参照してください。 + +```yaml +scalarAdminForKubernetes: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### 画像構成 (デフォルト値を推奨) + +イメージリポジトリを変更する場合は、`scalarAdminForKubernetes.image.repository` を使用して、プルする Scalar Admin for Kubernetes イメージのコンテナリポジトリ情報を指定できます。 + +```yaml +scalarAdminForKubernetes: + image: + repository: +``` + +### 汚染と許容の構成 (環境に応じてオプション) + +Kubernetes のテイントと許容を使用してポッドのデプロイメントを制御したい場合は、`scalarAdminForKubernetes.tolerations` を使用できます。 + +Kubernetes の許容と同じ構文を使用して、テイントと許容を構成できます。Kubernetes での許容設定の詳細については、Kubernetes の公式ドキュメント [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) を参照してください。 + +```yaml +scalarAdminForKubernetes: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb-analytics-postgresql +``` + +### TLS 構成 (環境に応じてオプション) + +次のような設定を実施することで、Scalar Admin for Kubernetes と一時停止ターゲット (ScalarDB Cluster または ScalarDL) の間での TLS 通信を有効にすることができます。 + +```yaml +scalarAdminForKubernetes: + commandArgs: + - (omit other options) + - --tls + - --ca-root-cert-path + - /tls/certs/ca.crt + - --override-authority + - cluster.scalardb.example.com +``` + +シークレットリソースを使用して、`/tls/certs/ca.crt` ファイルをポッドにマウントできます。`scalarAdminForKubernetes.tls.caRootCertSecret` にルート CA 証明書ファイルを含むシークレットリソースの名前を指定してください。 + +```yaml +scalarAdminForKubernetes: + tls: + caRootCertSecret: "scalar-admin-tls-ca" +``` + +この場合、次のように、一時停止ターゲット (ScalarDB Cluster または ScalarDL) のルート CA 証明書ファイルを含むシークレットリソースを作成する必要があります。 + +```console +kubectl create secret generic scalar-admin-tls-ca --from-file=ca.crt=/path/to/your/ca/certificate/file -n +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalar-manager.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalar-manager.mdx new file mode 100644 index 00000000..ea7864ea --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalar-manager.mdx @@ -0,0 +1,153 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# Scalar Manager のカスタム値ファイルを設定する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Scalar Manager Helm Chart のカスタム値ファイルを設定する方法について説明します。使用可能なパラメータの詳細については、Scalar Manager チャートリポジトリの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalar-manager/README.md) を参照してください。 + +## 必要な設定 + +このセクションでは、Scalar Manager の値ファイルに含める必要があるサービス、イメージ、および Scalar Manager の設定について説明します。 + +### サービス設定 + +Kubernetes の Service リソースのタイプを定義するには、`web.service.type` を設定する必要があります。クラウドサービスプロバイダーがサービスを公開するために提供するロードバランサーを使用するには、`web.service.type` を `LoadBalancer` に設定します。 + +```yaml +web: + service: + type: LoadBalancer + # other web configurations +``` + +#### Scalar Manager を公開する際のセキュリティ上の考慮事項 + +`web.service.type` を `LoadBalancer` に設定すると、デフォルトでは Scalar Manager が `HTTP` 経由で外部に公開されます。信頼できないネットワーク上に公開する場合は、暗号化されていないトラフィックによるセキュリティリスクが発生します。外部アクセスが不要な場合は、プライベートネットワークを使用するか、Kubernetes クラスターへのネットワークアクセスを適切に設定することをお勧めします。 + +Scalar Manager は、認証および認可メカニズムをサポートしています。これらのメカニズムを設定することで、Scalar 製品を一時停止するジョブのスケジュール設定などの機能に対して認可されたアクションを確実に実行できます。詳細については、[Scalar Manager の認証設定](#scalar-manager-の認証設定) を参照してください。 + +### コンテナイメージ設定 + +`api.image.repository` と `web.image.repository` を設定する必要があります。これらの設定は Scalar Manager コンテナイメージを指定し、コンテナリポジトリからそれらをプルできるようにします。 + +```yaml +api: + image: + repository: +web: + image: + repository: +``` + +## オプション設定 + +このセクションでは、Scalar Manager の値ファイルをカスタマイズするためのオプションの設定について説明します。 + +### Scalar Manager 設定 (環境に応じてオプション) + +`api.applicationProperties` の設定を上書きして、デフォルトの Scalar Manager 設定を変更できます。 + +```yaml +api: + applicationProperties: | + prometheus.kubernetes-service-label-name="app" + prometheus.kubernetes-service-label-value="kube-prometheus-stack-prometheus" + prometheus.kubernetes-service-port-name="http-web" + # other application properties +``` + +Scalar Manager には、クラスター内の Scalar 製品のデプロイメントと Prometheus サービスを検出するためのデフォルト設定が含まれています。ほとんどのシナリオでは、特にガイドに従って `kube-prometheus-stack` と `loki-stack` をデプロイする場合は、これらのデフォルト設定で十分であり、変更する必要はありません。 + +#### `api.applicationProperties` で設定可能なプロパティ + +Scalar Manager の設定は、Java アプリケーションプロパティの形式で、key=valueのペアです。これらのアプリケーションプロパティは、Scalar Manager Helm Chart の api.applicationProperties カスタム値を使用して設定できます。 + +| 名前 | 説明 | デフォルト値 | +|:--------------------------------------------------------------------|:------------------------------------------------------------------|:---------------------------------------------------------------------------| +| `prometheus.kubernetes-service-label-name` | Kubernetes で Prometheus サービスを検出するために使用されるラベル名 | `app` | +| `prometheus.kubernetes-service-label-value` | `prometheus.kubernetes-service-label-name` に対応するラベル値 | `kube-prometheus-stack-prometheus` | +| `prometheus.kubernetes-service-port-name` | Kubernetes で Prometheus サービスポートを検出するために使用されるポート名 | `http-web` | +| `springdoc.swagger-ui.enabled` | Swagger UI を有効にするかどうか | `false` | +| `springdoc.swagger-ui.path` | Swagger UI のパス | `/swagger-ui.html` | +| `app.cors.allowed-origins` | CORS の許可されたオリジン | `*` | +| `app.cors.allowed-methods` | CORS で許可されるメソッド | `*` | +| `app.cors.allowed-headers` | CORS で許可されるヘッダー | `*` | +| `authentication.providers.static-jwt.secret` | JWT トークンの署名に使用される秘密鍵。最小 32 文字 | `example-jwt-secret-with-minimum-32-characters` | +| `authentication.providers.static-jwt.issuer-uri` | JWT トークンの発行者 URI | `https://scalar-manager.example.com` | +| `authentication.providers.static-jwt.access-token-expiration-time` | アクセストークンの有効期限 | `1h` | +| `authentication.providers.static-jwt.refresh-token-expiration-time` | リフレッシュトークンの有効期限 | `3d` | +| `app.initial-admin-user.enabled` | 初期管理者ユーザーを有効にするかどうか | `true` | +| `app.initial-admin-user.email` | 初期管理者ユーザーのメールアドレス | `admin@example.com` | +| `app.initial-admin-user.name` | 初期管理者ユーザーの名前 | `Administrator` | +| `app.initial-admin-user.password` | 初期管理者ユーザーのパスワード | `Password@123!` | +| `spring.jpa.hibernate.ddl-auto` | Hibernate の DDL モード | `update` | +| `spring.jpa.show-sql` | SQL クエリを表示するかどうか | `false` | +| `spring.jpa.properties.hibernate.format_sql` | SQL クエリをフォーマットするかどうか | `false` | +| `spring.datasource.url` | データベースの URL | `jdbc:postgresql://scalar-manager-postgres-postgresql:5432/scalar-manager` | +| `spring.datasource.username` | データベースのユーザー名 | `scalar-manager` | +| `spring.datasource.password` | データベースのパスワード | `scalar-manager` | +| `spring.datasource.driver-class-name` | データベースのドライバークラス名 | `org.postgresql.Driver` | + +:::note + +`api.applicationProperties` では、JPA、Hibernate、Spring Data に関して設定できる項目が他にもあります。これらの設定に精通している場合は、データベース接続と Scalar Manager の動作をカスタマイズするように設定できます。 + +::: + +#### Scalar Manager の認証設定 + +デフォルトでは、Scalar Manager にアクセスするには、ユーザー名とパスワードを使用して認証する必要があります。 + +認証を設定するための前提条件は次のとおりです。 + +- 独自の PostgreSQL データベース、またはクラウドサービスプロバイダーがホストする PostgreSQL データベースが必要です。たとえば、[PostgreSQL 用の Bitnami パッケージ](https://artifacthub.io/packages/helm/bitnami/postgresql) を使用して、Kubernetes クラスターに PostgreSQL データベースをデプロイできます。 +- `authentication.providers.static-jwt.secret` 設定を設定する必要があります。この設定は JWT トークンの署名に使用され、シークレットの文字数は最小 32 文字です。 + +以下は、上記の前提条件を適用するために `api.applicationProperties` で設定する必要がある追加の設定の例です。環境に合わせて設定を必ず変更してください。 + +```properties +# JWT configuration +# Secret key used for signing JWT tokens, minimum 32 characters +authentication.providers.static-jwt.secret=${AUTHENTICATION_PROVIDERS_STATIC_JWT_SECRET:example-jwt-secret-with-minimum-32-characters} +authentication.providers.static-jwt.issuer-uri=${AUTHENTICATION_PROVIDERS_STATIC_JWT_ISSUER_URI:https://scalar-manager.example.com} +authentication.providers.static-jwt.access-token-expiration-time=${AUTHENTICATION_PROVIDERS_STATIC_JWT_ACCESS_TOKEN_EXPIRATION_TIME:1h} +authentication.providers.static-jwt.refresh-token-expiration-time=${AUTHENTICATION_PROVIDERS_STATIC_JWT_REFRESH_TOKEN_EXPIRATION_TIME:3d} + +# Initial admin configuration +app.initial-admin-user.enabled=${APP_INITIAL_ADMIN_USER_ENABLED:true} +app.initial-admin-user.email=${APP_INITIAL_ADMIN_USER_EMAIL:admin@example.com} +app.initial-admin-user.name=${APP_INITIAL_ADMIN_USER_NAME:Administrator} +app.initial-admin-user.password=${APP_INITIAL_ADMIN_USER_PASSWORD:Password@123!} + +# JPA configuration +spring.jpa.hibernate.ddl-auto=${SPRING_JPA_HIBERNATE_DDL_AUTO:update} +spring.jpa.show-sql=${SPRING_JPA_SHOW_SQL:false} +spring.jpa.properties.hibernate.format_sql=${SPRING_JPA_PROPERTIES_HIBERNATE_FORMAT_SQL:false} + +# Database configuration +spring.datasource.url=jdbc:postgresql://${DATABASE_HOST:scalar-manager-postgres-postgresql}:${DATABASE_PORT:5432}/${DATABASE_NAME:scalar-manager} +spring.datasource.username=${DATABASE_USERNAME:scalar-manager} +spring.datasource.password=${DATABASE_PASSWORD:scalar-manager} +spring.datasource.driver-class-name=org.postgresql.Driver +``` + +#### サービスディスカバリー + +Scalar Manager はラベルを使用して Kubernetes 内の Prometheus サービスを検出し、ポート名を使用してサービスに接続します。`prometheus.kubernetes-service-label-name`、`prometheus.kubernetes-service-label-value`、および `prometheus.kubernetes-service-port-name` を設定することで、ラベルとポート名を変更できます。 + +一般的に、これらの設定を変更する必要はありません。ただし、Prometheus サービスの Helm Chart をインストールする際にラベルまたはポート名をカスタマイズした場合は、カスタマイズに合わせてこれらの設定を調整する必要があります。 + +#### `web.env` で設定可能な環境変数 + +| Name | Description |Default Value | +|:---------------------|:---------------------------------------------|:---------------------------------------------------------------------| +| `GRAFANA_SERVER_URL` | Kubernetes クラスター内の Grafana サービスの URL | `http://scalar-monitoring-grafana.monitoring.svc.cluster.local:3000` | + +現在、`GRAFANA_SERVER_URL` 変数を `web.env` で設定して、Scalar Manager Web UI から Grafana UI へのプロキシをカスタマイズできます。デフォルトでは、変数は `monitoring` 名前空間にインストールされた Grafana サービス `scalar-monitoring-grafana` に設定されています。Grafana を別の名前空間にインストールした場合、または Grafana サービスの名前を変更した場合は、それに応じて `GRAFANA_SERVER_URL` 変数を更新する必要があります。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-analytics-postgresql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-analytics-postgresql.mdx new file mode 100644 index 00000000..0c6b8bf9 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-analytics-postgresql.mdx @@ -0,0 +1,193 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics with PostgreSQL のカスタム値ファイルを構成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、PostgreSQL チャートを使用した ScalarDB Analytics のカスタム値ファイルを作成する方法について説明します。パラメーターの詳細については、ScalarDB Analytics with PostgreSQL チャートの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardb-analytics-postgresql/README.md) を参照してください。 + +## 必要な構成 + +このセクションでは、ScalarDB Analytics with PostgreSQL のカスタム値ファイルを設定するときに必要な構成について説明します。 + +### データベース構成 + +ScalarDB Analytics with PostgreSQL 経由でデータベースにアクセスするには、`database.properties` ファイルの構成に使用するのと同じ構文に従って、`scalardbAnalyticsPostgreSQL.databaseProperties` パラメータを設定する必要があります。設定の詳細については、[ScalarDB Configurations](https://scalardb.scalar-labs.com/docs/latest/configurations/) を参照してください。 + +```yaml +scalardbAnalyticsPostgreSQL: + databaseProperties: | + scalar.db.contact_points=localhost + scalar.db.username=${env:SCALAR_DB_USERNAME:-} + scalar.db.password=${env:SCALAR_DB_PASSWORD:-} + scalar.db.storage=cassandra +``` + +### データベース名前空間の構成 + +ScalarDB Analytics with PostgreSQL 経由で読み取りたいテーブルを含むすべてのデータベース名前空間に `schemaImporter.namespaces` を設定する必要があります。 + +```yaml +schemaImporter: + namespaces: + - namespace1 + - namespace2 + - namespace3 +``` + +## オプションの構成 + +このセクションでは、ScalarDB Analytics with PostgreSQL のカスタム値ファイルを設定する場合のオプションの構成について説明します。 + +### リソース構成 (実稼働環境で推奨) + +Kubernetes でリクエストと制限を使用してポッドリソースを制御するには、`scalardbAnalyticsPostgreSQL.resources` を使用できます。 + +Kubernetes のリクエストと制限と同じ構文を使用して、リクエストと制限を構成できます。Kubernetes のリクエストと制限の詳細については、[Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) を参照してください。 + +```yaml +scalardbAnalyticsPostgreSQL: + resources: + requests: + cpu: 1000m + memory: 2Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### シークレット構成 (運用環境で推奨) + +環境変数を使用して `scalardbAnalyticsPostgreSQL.databaseProperties` で資格情報などのいくつかのプロパティを設定するには、`scalardbAnalyticsPostgreSQL.secretName` を使用していくつかの資格情報を含むシークレットリソースを指定します。 + +たとえば、環境変数を使用してバックエンドデータベースの資格情報 (`scalar.db.username` および `scalar.db.password`) を設定できるため、ポッドの安全性が高まります。 + +シークレットリソースの使用方法の詳細については、[シークレットリソースを使用して資格情報を環境変数としてプロパティファイルに渡す方法(./use-secret-for-credentials.mdx)を参照してください。 + +```yaml +scalardbAnalyticsPostgreSQL: + secretName: "scalardb-analytics-postgresql-credentials-secret" +``` + +### アフィニティ構成 (運用環境で推奨) + +Kubernetes でアフィニティとアンチアフィニティを使用してポッドのデプロイメントを制御するには、`scalardbAnalyticsPostgreSQL.affinity` を使用できます。 + +Kubernetes のアフィニティとアンチアフィニティと同じ構文を使用して、アフィニティとアンチアフィニティを構成できます。Kubernetes でのアフィニティの構成の詳細については、[Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) を参照してください。 + +```yaml +scalardbAnalyticsPostgreSQL: + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardb-analytics-postgresql + - key: app.kubernetes.io/app + operator: In + values: + - scalardb-analytics-postgresql + topologyKey: kubernetes.io/hostname +``` + +### SecurityContext 設定 (デフォルト値を推奨) + +PostgreSQL ポッドを使用して ScalarDB Analytics の SecurityContext と PodSecurityContext を設定するには、`scalardbAnalyticsPostgreSQL.securityContext`、`scalardbAnalyticsPostgreSQL.podSecurityContext`、および `schemaImporter.securityContext` を使用できます。 + +Kubernetes の SecurityContext および PodSecurityContext と同じ構文を使用して、SecurityContext および PodSecurityContext を構成できます。Kubernetes の SecurityContext および PodSecurityContext 構成の詳細については、[Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) を参照してください。 + +```yaml +scalardbAnalyticsPostgreSQL: + podSecurityContext: + fsGroup: 201 + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + runAsUser: 999 + allowPrivilegeEscalation: false + +schemaImporter: + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### 画像構成 (デフォルト値を推奨) + +イメージリポジトリを変更する場合は、`scalardbAnalyticsPostgreSQL.image.repository` と `schemaImporter.image.repository` を使用して、プルする ScalarDB Analytics with PostgreSQL および Schema Importer イメージのコンテナリポジトリ情報を指定できます。 + +```yaml +scalardbAnalyticsPostgreSQL: + image: + repository: + +schemaImporter: + image: + repository: +``` + +### レプリカ構成 (環境に応じてオプション) + +`scalardbAnalyticsPostgreSQL.replicaCount` を使用して、PostgreSQL レプリカ (ポッド) を使用した ScalarDB Analytics の数を指定できます。 + +```yaml +scalardbAnalyticsPostgreSQL: + replicaCount: 3 +``` + +### PostgreSQL データベース名の構成 (環境に応じてオプション) + +PostgreSQL で作成するデータベース名を指定できます。Schema Importer は、ScalarDB Analytics with PostgreSQL のビューなど、いくつかのオブジェクトをこのデータベースに作成します。 + +```yaml +scalardbAnalyticsPostgreSQL: + postgresql: + databaseName: scalardb +``` + +### PostgreSQL スーパーユーザーのパスワード設定 (環境に応じてオプション) + +PostgreSQL のスーパーユーザーのパスワードを含むシークレット名を指定できます。 + +```yaml +scalardbAnalyticsPostgreSQL: + postgresql: + secretName: scalardb-analytics-postgresql-superuser-password +``` + +:::note + +ScalarDB Analytics with PostgreSQL をデプロイする前に、この名前 (デフォルトでは `scalardb-analytics-postgresql-superuser-password`) でシークレットリソースを作成する必要があります。詳細については、[シークレットリソースを準備する](how-to-deploy-scalardb-analytics-postgresql.mdx#シークレットリソースを準備する)を参照してください。 + +::: + +### 汚染と許容の構成 (環境に応じてオプション) + +Kubernetes でテイントと許容を使用してポッドのデプロイメントを制御したい場合は、`scalardbAnalyticsPostgreSQL.tolerations` を使用できます。 + +Kubernetes の許容と同じ構文を使用して、テイントと許容を構成できます。Kubernetes での許容設定の詳細については、Kubernetes の公式ドキュメント [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) を参照してください。 + +```yaml +scalardbAnalyticsPostgreSQL: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb-analytics-postgresql +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-cluster.mdx new file mode 100644 index 00000000..37cc07f1 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-cluster.mdx @@ -0,0 +1,402 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster のカスタム値ファイルを構成する + +このドキュメントでは、ScalarDB Cluster チャートのカスタム値ファイルを作成する方法について説明します。パラメータの詳細については、ScalarDB Cluster チャートの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardb-cluster/README.md) を参照してください。 + +## 必要な構成 + +### 画像構成 + +`scalardbCluster.image.repository`を設定する必要があります。コンテナーリポジトリからイメージをプルできるように、必ず ScalarDB Cluster コンテナーイメージを指定してください。 + +```yaml +scalardbCluster: + image: + repository: +``` + +### データベース構成 + +`scalardbCluster.scalardbClusterNodeProperties` を設定する必要があります。このパラメータには `scalardb-cluster-node.properties` を設定してください。ScalarDB Cluster の構成の詳細については、[ScalarDB Cluster Configurations](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-configurations/) を参照してください。 + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} + scalar.db.contact_points=localhost + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + scalar.db.storage=cassandra +``` + +Scalar Helm Chart を使用して Kubernetes 環境に ScalarDB Cluster をデプロイする場合は、次の3つのプロパティを常に設定する必要があることに注意してください。これらのプロパティは固定値です。プロパティは個別の環境に依存しないため、以下の値をコピーして `scalardbCluster.scalardbClusterNodeProperties` に貼り付けることで同じ値を設定できます。 + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} +``` + +## オプションの構成 + +### リソース構成 (実稼働環境で推奨) + +Kubernetes でリクエストと制限を使用してポッドリソースを制御するには、`scalardbCluster.resources` を使用できます。 + +商用ライセンスの場合、Scalar 製品の各ポッドのリソースは 2vCPU / 4GB メモリに制限されることに注意してください。また、AWS Marketplace が提供する従量課金制のコンテナを使用する場合、`resources.limits` の 2vCPU / 4GB メモリ構成を超えるコンテナを実行することはできません。このリソース制限を超えると、ポッドは自動的に停止します。 + +Kubernetes のリクエストと制限と同じ構文を使用して、リクエストと制限を構成できます。Kubernetes のリクエストと制限の詳細については、[Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) を参照してください。 + +```yaml +scalardbCluster: + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### シークレット構成 (運用環境で推奨) + +環境変数を使用して `scalardbCluster.scalardbClusterNodeProperties` 内の一部のプロパティ (資格情報など) を設定するには、`scalardbCluster.secretName` を使用して、いくつかの資格情報を含む Secret リソースを指定します。 + +たとえば、環境変数を使用してバックエンドデータベースの資格情報 (`scalar.db.username` および `scalar.db.password`) を設定できるため、ポッドの安全性が高まります。 + +Secret リソースの使用方法の詳細については、[Secret リソースを使用して資格情報を環境変数としてプロパティファイルに渡す方法](use-secret-for-credentials.mdx)を参照してください。 + +```yaml +scalardbCluster: + secretName: "scalardb-cluster-credentials-secret" +``` + +### アフィニティ構成 (運用環境で推奨) + +Kubernetes でアフィニティとアンチアフィニティを使用してポッドのデプロイメントを制御するには、`scalardbCluster.affinity` を使用できます。 + +Kubernetes のアフィニティとアンチアフィニティと同じ構文を使用して、アフィニティとアンチアフィニティを構成できます。Kubernetes でのアフィニティの構成の詳細については、[Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) を参照してください。 + +```yaml +scalardbCluster: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardb-cluster + - key: app.kubernetes.io/app + operator: In + values: + - scalardb-cluster + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus および Grafana 構成 (実稼働環境で推奨) + +[kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) を使用して ScalarDB Cluster ポッドを監視するには、`scalardbCluster.grafanaDashboard.enabled`、`scalardbCluster.serviceMonitor.enabled`、`scalardbCluster.prometheusRule.enabled` を `true` に設定します。これらの構成を `true` に設定すると、チャートは必要なリソースをデプロイし、kube-prometheus-stack が自動的に監視を開始します。 + +```yaml +scalardbCluster: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext 設定 (デフォルト値を推奨) + +ScalarDB Cluster ポッドの SecurityContext と PodSecurityContext を設定するには、`scalardbCluster.securityContext` と `scalardbCluster.podSecurityContext` を使用できます。 + +Kubernetes の SecurityContext および PodSecurityContext と同じ構文を使用して、SecurityContext および PodSecurityContext を構成できます。Kubernetes の SecurityContext および PodSecurityContext 構成の詳細については、[Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) を参照してください。 + +```yaml +scalardbCluster: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### TLS 構成 (環境に応じてオプション) + +TLS は、次の通信で有効にできます: + +- ScalarDB Cluster ノードとクライアント間の通信。 +- すべての ScalarDB Cluster ノード間の通信 (クラスターの内部通信)。 + +さらに、証明書管理にはいくつかのオプションがあります。詳細については、[Envoy の TLS 構成](./configure-custom-values-envoy.mdx#tls-構成-環境に応じてオプション)を参照してください。 + +セキュリティ要件に基づいて、どの方法を使用するかを検討する必要があります。各方法のガイダンスと関連ドキュメントについては、次の意思決定ツリーを参照してください。 + +```mermaid +flowchart TD + A[cert-manager を使用して
秘密鍵と証明書ファイルを
自動的に管理しますか?] + A -->|はい、証明書を自動的に
管理したいです。| B + A -->|いいえ、証明書は自分で手動で
管理したいです。| C + B[自己署名 CA と
信頼された CA の
どちらを使用しますか?] + C[自己署名 CA と
信頼された CA の
どちらを使用しますか?] + B -->|自己署名 CA を
使用したいです。| D + B -->|信頼できる CA
を使用したいです。| E + C -->|自己署名 CA
を使用したいです。| F + C -->|信頼できる CA
を使用したいです。| G + D[cert-manager で自己署名 CA を使用して
秘密鍵と証明書ファイルを管理する

を参照してください。] + E[cert-manager で信頼できる CA を使用して
秘密鍵と証明書ファイルを管理する

を参照してください。] + F[秘密鍵と証明書ファイルを使用するを参照し、
生成した自己署名証明書を使用します。] + G[秘密鍵と証明書ファイルを使用するを参照し、
第三者によって生成された
信頼できる証明書を使用します。] +``` + +#### TLS を有効にする + +次の構成を使用して、すべての ScalarDB Cluster 接続で TLS を有効にできます。 + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + ...(omit)... + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/tls/scalardb-cluster/certs/ca.crt + scalar.db.cluster.node.tls.cert_chain_path=/tls/scalardb-cluster/certs/tls.crt + scalar.db.cluster.node.tls.private_key_path=/tls/scalardb-cluster/certs/tls.key + scalar.db.cluster.tls.override_authority= + tls: + enabled: true +``` + +##### シークレットキーと証明書ファイルを使用する + +次の構成を使用して、秘密鍵と証明書ファイルを設定できます。 + +```yaml +scalardbCluster: + tls: + enabled: true + caRootCertSecret: "scalardb-cluster-tls-ca" + certChainSecret: "scalardb-cluster-tls-cert" + privateKeySecret: "scalardb-cluster-tls-key" +``` + +この場合、次のように山括弧内の内容を置き換えて、ScalarDB Cluster の秘密鍵と証明書ファイルを含むシークレットリソースを作成する必要があります。 + +```console +kubectl create secret generic scalardb-cluster-tls-ca --from-file=ca.crt=/ -n +kubectl create secret generic scalardb-cluster-tls-cert --from-file=tls.crt=/ -n +kubectl create secret generic scalardb-cluster-tls-key --from-file=tls.key=/ -n +``` + +秘密鍵と証明書ファイルを準備する方法の詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx)を参照してください。 + +##### cert-manager で信頼できる CA を使用して秘密鍵と証明書ファイルを管理する + +次の構成を使用して、山括弧内の内容を説明に従って置き換えることで、cert-manager で秘密鍵と証明書ファイルを管理できます。 + +:::note + +* cert-manager を使用する場合は、cert-manager をデプロイし、`Issuers` リソースを準備する必要があります。詳細については、cert-manager のドキュメント、[インストール](https://cert-manager.io/docs/installation/)および[発行者構成](https://cert-manager.io/docs/configuration/)を参照してください。 +* デフォルトでは、Scalar Helm Chart は Scalar 製品の証明書要件を満たす `Certificate` リソースを作成します。デフォルトの証明書構成が推奨されますが、カスタム証明書構成を使用する場合は、Scalar 製品の証明書要件を満たす必要があります。詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements)を参照してください。 + +::: + +```yaml +scalardbCluster: + tls: + enabled: true + certManager: + enabled: true + issuerRef: + name: + dnsNames: + - cluster.scalardb.example.com +``` + +この場合、cert-manager は信頼できる発行者を使用して秘密鍵と証明書ファイルを発行します。秘密鍵と証明書ファイルを手動でマウントする必要はありません。 + +##### cert-manager で自己署名 CA を使用して秘密鍵と証明書ファイルを管理する + +次の構成を使用して、cert-manager で秘密鍵と自己署名証明書ファイルを管理できます。 + +:::note + +* cert-manager を使用する場合は、cert-manager をデプロイする必要があります。詳細については、cert-manager のドキュメント[インストール](https://cert-manager.io/docs/installation/)を参照してください。 +* デフォルトでは、Scalar Helm Chart は Scalar 製品の証明書要件を満たす `Certificate` リソースを作成します。デフォルトの証明書構成が推奨されますが、カスタム証明書構成を使用する場合は、Scalar 製品の証明書要件を満たす必要があります。詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements)を参照してください。 + +::: + +```yaml +scalardbCluster: + tls: + enabled: true + certManager: + enabled: true + selfSigned: + enabled: true + dnsNames: + - cluster.scalardb.example.com +``` + +この場合、Scalar Helm Charts と cert-manager が秘密鍵と自己署名証明書ファイルを発行します。秘密鍵と証明書ファイルを手動でマウントする必要はありません。 + +##### TLS通信のカスタム権限を設定する + +`scalardbCluster.tls.overrideAuthority` を使用して、TLS 通信のカスタム権限を設定できます。この値によって、実際に接続されているホストが変わることはありません。この値はテスト用ですが、DNS オーバーライドの代替としてテスト以外でも安全に使用できます。たとえば、`scalardbCluster.tls.certChainSecret` を使用して設定した証明書チェーンファイルで提示されるホスト名を指定できます。このチャートでは、`startupProbe` と `livenessProbe` にこの値を使用しています。 + +```yaml +scalardbCluster: + tls: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" +``` + +### レプリカ構成 (環境に応じてオプション) + +`scalardbCluster.replicaCount` を使用して、ScalarDB Cluster のレプリカ (ポッド) の数を指定できます。 + +```yaml +scalardbCluster: + replicaCount: 3 +``` + +### ロギング構成 (環境に応じてオプション) + +ScalarDB Cluster のログレベルを変更するには、`scalardbCluster.logLevel` を使用できます。 + +```yaml +scalardbCluster: + logLevel: INFO +``` + +### GraphQL 構成 (環境に応じてオプション) + +ScalarDB Cluster で GraphQL 機能を使用するには、`scalardbCluster.graphql.enabled` を `true` に設定して、GraphQL 機能用のリソースをデプロイします。GraphQL 機能を使用する場合は、`scalardbCluster.scalardbClusterNodeProperties` で `scalar.db.graphql.enabled=true` を設定する必要があることに注意してください。 + +```yaml +scalardbCluster: + graphql: + enabled: true +``` + +また、クライアントからの GraphQL リクエストを受け入れる `Service` リソースを設定することもできます。 + +```yaml +scalardbCluster: + graphql: + service: + type: ClusterIP + annotations: {} + ports: + graphql: + port: 8080 + targetPort: 8080 + protocol: TCP +``` + +### SQL 構成 (環境に応じてオプション) + +ScalarDB Cluster で SQL 機能を使用するために、カスタム値ファイルに必要な構成はありません。この機能は、`scalardbCluster.scalardbClusterNodeProperties` で `scalar.db.sql.enabled=true` を設定することで使用できます。 + +### Scalar Envoy 構成 (環境に応じてオプション) + +ScalarDB Cluster を `indirect` モードで使用するには、次のように Envoy を有効にする必要があります。 + +```yaml +envoy: + enabled: true +``` + +また、ScalarDB Cluster のカスタム値ファイルに Scalar Envoy 構成を設定する必要があります。これは、`indirect` モードで Kubernetes 環境に ScalarDB Cluster をデプロイする場合、クライアントは gRPC リクエストのロードバランサーとして Scalar Envoy を介して ScalarDB Cluster にリクエストを送信する必要があるためです。 + +Scalar Envoy 構成の詳細については、[Scalar Envoy のカスタム値ファイルの構成](configure-custom-values-envoy.mdx)を参照してください。 + +```yaml +envoy: + configurationsForScalarEnvoy: + ... + +scalardbCluster: + configurationsForScalarDbCluster: + ... +``` + +### 汚染と許容の構成 (環境に応じてオプション) + +Kubernetes のテイントと許容を使用してポッドのデプロイメントを制御したい場合は、`scalardbCluster.tolerations` を使用できます。 + +Kubernetes の許容と同じ構文を使用して、テイントと許容を構成できます。Kubernetes での許容設定の詳細については、Kubernetes の公式ドキュメント [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) を参照してください。 + +```yaml +scalardbCluster: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb-cluster +``` + +### 暗号化設定 (環境に応じてオプション) + +[保存時の暗号化](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/encrypt-data-at-rest/)を有効にして、バックエンドデータベース内のデータを保護できます。暗号化機能を使用する場合、次の 2つのデプロイメントオプションがあります。 + +1. HashiCorp Vault (HashiCorp Cloud Platform (HCP) Vault Dedicated) を使用して、DEK を管理および保存します。 +1. ScalarDB Cluster を使用して DEK を管理し、Kubernetes Secrets に保存します。 + +#### HashiCorp Vaultを使用する + +HashiCorp Vault (HCP Vault Dedicated) を使用してデータを暗号化できます。山括弧内の内容は説明に応じて置き換えます。 + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + ...(omit)... + scalar.db.cluster.encryption.enabled=true + scalar.db.cluster.encryption.type=vault + scalar.db.cluster.encryption.vault.address=https://: + scalar.db.cluster.encryption.vault.token= + scalar.db.cluster.encryption.vault.transit_secrets_engine_path= + encryption: + enabled: true + type: "vault" +``` + +#### ScalarDB Cluster と Kubernetes Secrets を使用する + +ScalarDB Cluster と Kubernetes Secrets を使用して、次のようにデータを暗号化できます。山括弧内の内容は説明に応じて置き換えます。 + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + ...(omit)... + scalar.db.cluster.encryption.enabled=true + scalar.db.cluster.encryption.type=self + scalar.db.cluster.encryption.self.kubernetes.secret.namespace_name=${env:SCALAR_DB_CLUSTER_ENCRYPTION_SELF_KUBERNETES_SECRET_NAMESPACE_NAME} + encryption: + enabled: true + type: "self" +``` + +この場合、ScalarDB Cluster の Helm Chart は名前空間情報を環境変数として自動的に設定するため、`${env:SCALAR_DB_CLUSTER_ENCRYPTION_SELF_KUBERNETES_SECRET_NAMESPACE_NAME}` を置き換える必要はありません。このため、`${env:SCALAR_DB_CLUSTER_ENCRYPTION_SELF_KUBERNETES_SECRET_NAMESPACE_NAME}` の値はそのままにしておいてかまいません。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-graphql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-graphql.mdx new file mode 100644 index 00000000..2d8ea5e2 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb-graphql.mdx @@ -0,0 +1,228 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# [非推奨] ScalarDB GraphQL のカスタム値ファイルを構成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +:::note + +ScalarDB GraphQL サーバーは非推奨になりました。代わりに [ScalarDB Cluster](configure-custom-values-scalardb-cluster.mdx) を使用してください。 + +::: + +このドキュメントでは、ScalarDB GraphQL チャートのカスタム値ファイルを作成する方法について説明します。パラメータの詳細を知りたい場合は、ScalarDB GraphQL チャートの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardb-graphql/README.md) を参照してください。 + +## 必要な構成 + +### イングレス構成 + +クライアントリクエストをリッスンするには `ingress` を設定する必要があります。複数の GraphQL サーバーをデプロイする場合、トランザクションを適切に処理するにはセッションアフィニティが必要です。これは、GraphQL サーバーがトランザクションをメモリ内に保持するため、継続トランザクションを使用する GraphQL クエリは、トランザクションを開始したのと同じサーバーにルーティングする必要があるためです。 + +たとえば、NGINX Ingress Controller を使用する場合、次のように Ingress 構成を設定できます。 + +```yaml +ingress: + enabled: true + className: nginx + annotations: + nginx.ingress.kubernetes.io/session-cookie-path: / + nginx.ingress.kubernetes.io/affinity: cookie + nginx.ingress.kubernetes.io/session-cookie-name: INGRESSCOOKIE + nginx.ingress.kubernetes.io/session-cookie-hash: sha1 + nginx.ingress.kubernetes.io/session-cookie-max-age: "300" + hosts: + - host: "" + paths: + - path: /graphql + pathType: Exact +``` + +AWSのALBを利用する場合、以下のようにIngress設定を行うことができます。 + +```yaml +ingress: + enabled: true + className: alb + annotations: + alb.ingress.kubernetes.io/scheme: internal + alb.ingress.kubernetes.io/target-group-attributes: stickiness.enabled=true,stickiness.lb_cookie.duration_seconds=60 + alb.ingress.kubernetes.io/target-type: ip + alb.ingress.kubernetes.io/healthcheck-path: /graphql?query=%7B__typename%7D + hosts: + - host: "" + paths: + - path: /graphql + pathType: Exact +``` + +### 画像構成 + +`image.repository`を設定する必要があります。コンテナーリポジトリからイメージをプルできるように、ScalarDB GraphQL コンテナーイメージを必ず指定してください。 + +```yaml +image: + repository: +``` + +AWS または Azure を使用している場合、詳細については次のドキュメントを参照してください。 + +* [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) +* [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +### データベース構成 + +`scalarDbGraphQlConfiguration`を設定する必要があります。 + +ScalarDB Server を ScalarDB GraphQL とともに使用する場合 (推奨)、ScalarDB Server ポッドにアクセスするように構成を設定する必要があります。 + +```yaml +scalarDbGraphQlConfiguration: + contactPoints: + contactPort: 60051 + storage: "grpc" + transactionManager: "grpc" + namespaces: +``` + +## オプションの構成 + +### リソース構成 (本番環境で推奨) + +Kubernetes のリクエストと制限を使用してポッドリソースを制御したい場合は、`resources` を使用できます。 + +商用ライセンスの観点から、Scalar 製品の1つのポッドのリソースは 2vCPU / 4GB メモリに制限されていることに注意してください。また、AWS Marketplace から提供される従量課金制のコンテナを取得する場合、`resources.limits` で 2vCPU / 4GB を超えるメモリ構成でそれらのコンテナを実行することはできません。この制限を超えると、ポッドは自動的に停止されます。 + +これらは、Kubernetes のリクエストと制限と同じ構文を使用して構成できます。そのため、Kubernetes の要求と制限の詳細については、公式ドキュメント [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) を参照してください。 + +```yaml +resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### アフィニティ構成 (運用環境で推奨) + +Kubernetes のアフィニティと反アフィニティを使用してポッドのデプロイメントを制御したい場合は、`affinity` を使用できます。 + +Kubernetes のアフィニティと同じ構文を使用して構成できます。そのため、Kubernetes のアフィニティ設定の詳細については、公式ドキュメント [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) を参照してください。 + +```yaml +affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/app + operator: In + values: + - scalardb-graphql + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus/Grafana 構成 (運用環境で推奨) + +[kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) を使用して ScalarDB GraphQL ポッドを監視する場合は、`grafanaDashboard.enabled`、`serviceMonitor.enabled`、および `prometheusRule.enabled`。 + +```yaml +grafanaDashboard: + enabled: true + namespace: monitoring +serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s +prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext 設定 (デフォルト値を推奨) + +ScalarDB GraphQL ポッドに SecurityContext と PodSecurityContext を設定したい場合は、`securityContext` と `podSecurityContext` を使用できます。 + +KubernetesのSecurityContextやPodSecurityContextと同じ構文を使用して設定できます。したがって、Kubernetes の SecurityContext および PodSecurityContext 構成の詳細については、公式ドキュメント [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) を参照してください。 + +```yaml +podSecurityContext: + seccompProfile: + type: RuntimeDefault + +securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### GraphQL サーバー構成 (環境に応じてオプション) + +graphql クエリを実行するパスを変更したい場合は、`scalarDbGraphQlConfiguration.path` を使用できます。デフォルトでは、`http://:80/graphql` を使用して graphql クエリを実行できます。 + +`scalarDbGraphQlConfiguration.graphiql` を使用して [GraphiQL](https://github.com/graphql/graphiql/tree/main/packages/graphiql) を有効/無効にすることもできます。 + +```yaml +scalarDbGraphQlConfiguration: + path: /graphql + graphiql: "true" +``` + +### TLS 構成 (環境に応じてオプション) + +クライアントとイングレスの間で TLS を使用したい場合は、`ingress.tls` を使用できます。 + +秘密鍵と証明書ファイルを含むシークレットリソースを作成する必要があります。Ingress の Secret リソースの詳細については、公式ドキュメント [Ingress - TLS](https://kubernetes.io/docs/concepts/services-networking/ingress/#tls) を参照してください。 + +```yaml +ingress: + tls: + - hosts: + - foo.example.com + - bar.example.com + - bax.example.com + secretName: graphql-ingress-tls +``` + +### レプリカ構成 (環境に応じてオプション) + +ScalarDB GraphQL のレプリカ (ポッド) の数は、`replicaCount` を使用して指定できます。 + +```yaml +replicaCount: 3 +``` + +### ロギング構成 (環境に応じてオプション) + +ScalarDB GraphQL のログレベルを変更したい場合は、`scalarDbGraphQlConfiguration.logLevel` を使用できます。 + +```yaml +scalarDbGraphQlConfiguration: + logLevel: INFO +``` + +### 汚染と許容の構成 (環境に応じてオプション) + +Kubernetes のテイントと許容範囲を使用してポッドのデプロイメントを制御したい場合は、`tolerations` を使用できます。 + +Kubernetes の許容と同じ構文を使用して、テイントと許容を構成できます。Kubernetes での許容設定の詳細については、Kubernetes の公式ドキュメント [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) を参照してください。 + +```yaml +tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb.mdx new file mode 100644 index 00000000..139f7bfe --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardb.mdx @@ -0,0 +1,206 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsJapanese +--- + +# [非推奨] ScalarDB Server のカスタム値ファイルを構成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +:::note + +ScalarDB Server は非推奨になりました。代わりに [ScalarDB Cluster](configure-custom-values-scalardb-cluster.mdx) を使用してください。 + +::: + +このドキュメントでは、ScalarDB Server チャートのカスタム値ファイルを作成する方法について説明します。パラメータの詳細を知りたい場合は、ScalarDB Server チャートの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardb/README.md) を参照してください。 + +## 必要な構成 + +### Scalar Envoy 構成 + +ScalarDB Server のカスタム値ファイルに Scalar Envoy 構成を設定する必要があります。これは、ScalarDB Server を Kubernetes 環境にデプロイする場合、クライアントリクエストが gRPC リクエストのロードバランサーとして Scalar Envoy 経由で ScalarDB Server に送信されるためです。 + +Scalar Envoy 構成の詳細については、ドキュメント [Scalar Envoy のカスタム値ファイルの構成](configure-custom-values-envoy.mdx)を参照してください。 + +```yaml +envoy: + configurationsForScalarEnvoy: + ... + +scalardb: + configurationsForScalarDB: + ... +``` + +### 画像構成 + +`scalardb.image.repository`を設定する必要があります。コンテナーリポジトリからイメージをプルできるように、必ず ScalarDB Server コンテナーイメージを指定してください。 + +```yaml +scalardb: + image: + repository: +``` + +AWS または Azure を使用している場合、詳細については次のドキュメントを参照してください。 + +* [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) +* [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +### データベース構成 + +`scalardb.databaseProperties` を設定する必要があります。`database.properties` をこのパラメータに設定してください。ScalarDB Server の設定の詳細については、[Configure ScalarDB Server](https://scalardb.scalar-labs.com/docs/latest/scalardb-server.mdx#configure-scalardb-server) を参照してください。 + +```yaml +scalardb: + databaseProperties: | + scalar.db.server.port=60051 + scalar.db.server.prometheus_exporter_port=8080 + scalar.db.server.grpc.max_inbound_message_size= + scalar.db.server.grpc.max_inbound_metadata_size= + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + scalar.db.storage=cassandra + scalar.db.transaction_manager=consensus-commit + scalar.db.consensus_commit.isolation_level=SNAPSHOT + scalar.db.consensus_commit.serializable_strategy= + scalar.db.consensus_commit.include_metadata.enabled=false +``` + +## オプションの構成 + +### リソース構成 (本番環境で推奨) + +Kubernetes のリクエストと制限を使用してポッドリソースを制御したい場合は、`scalardb.resources` を使用できます。 + +商用ライセンスの観点から、Scalar 製品の1つのポッドのリソースは 2vCPU / 4GB メモリに制限されていることに注意してください。また、AWS Marketplace から提供される従量課金制のコンテナを取得する場合、`resources.limits` で 2vCPU / 4GB を超えるメモリ構成でそれらのコンテナを実行することはできません。この制限を超えると、ポッドは自動的に停止されます。 + +これらは、Kubernetes のリクエストと制限と同じ構文を使用して構成できます。そのため、Kubernetes の要求と制限の詳細については、公式ドキュメント [Pod およびコンテナーのリソース管理](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/)を参照してください。 + +```yaml +scalardb: + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### シークレット構成 (運用環境で推奨) + +環境変数を使用して `scalardb.databaseProperties` 内の一部のプロパティ (資格情報など) を設定したい場合は、`scalardb.secretName` を使用して、いくつかの資格情報を含む Secret リソースを指定できます。 + +たとえば、環境変数を使用してバックエンドデータベースの資格情報 (`scalar.db.username` および `scalar.db.password`) を設定でき、これによりポッドの安全性が高まります。 + +Secret リソースの使用方法の詳細については、ドキュメント [Secret リソースを使用して資格情報を環境変数としてプロパティファイルに渡す方法](use-secret-for-credentials.mdx)を参照してください。 + +```yaml +scalardb: + secretName: "scalardb-credentials-secret" +``` + +### アフィニティ構成 (運用環境で推奨) + +Kubernetes のアフィニティと反アフィニティを使用してポッドのデプロイメントを制御したい場合は、`scalardb.affinity` を使用できます。 + +Kubernetes のアフィニティと同じ構文を使用して構成できます。そのため、Kubernetes のアフィニティ設定の詳細については、公式ドキュメント [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) を参照してください。 + +```yaml +scalardb: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardb + - key: app.kubernetes.io/app + operator: In + values: + - scalardb + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus/Grafana 構成 (運用環境で推奨) + +[kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) を使用して ScalarDB Server ポッドを監視する場合は、`scalardb.grafanaDashboard.enabled`、`scalardb.serviceMonitor` を使用して、kube-prometheus-stack の ConfigMap、ServiceMonitor、および PrometheusRule リソースをデプロイできます。`enabled`および `scalardb.prometheusRule.enabled`。 + +```yaml +scalardb: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext 設定 (デフォルト値を推奨) + +ScalarDB Server ポッドに SecurityContext と PodSecurityContext を設定したい場合は、`scalardb.securityContext` と `scalardb.podSecurityContext` を使用できます。 + +KubernetesのSecurityContextやPodSecurityContextと同じ構文を使用して設定できます。したがって、Kubernetes の SecurityContext および PodSecurityContext 構成の詳細については、公式ドキュメント [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) を参照してください。 + +```yaml +scalardb: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### レプリカ構成 (環境に応じてオプション) + +`scalardb.replicaCount` を使用して、ScalarDB Serverのレプリカ(ポッド)の数を指定できます。 + +```yaml +scalardb: + replicaCount: 3 +``` + +### ロギング構成 (環境に応じてオプション) + +ScalarDB Server のログレベルを変更したい場合は、`scalardb.storageConfiguration.dbLogLevel` を使用できます。 + +```yaml +scalardb: + storageConfiguration: + dbLogLevel: INFO +``` + +### 汚染と許容の構成 (環境に応じてオプション) + +Kubernetes のテイントと許容を使用してポッドのデプロイメントを制御したい場合は、`scalardb.tolerations` を使用できます。 + +Kubernetes の許容と同じ構文を使用して、テイントと許容を構成できます。Kubernetes での許容設定の詳細については、Kubernetes の公式ドキュメント [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) を参照してください。 + +```yaml +scalardb: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-auditor.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-auditor.mdx new file mode 100644 index 00000000..da5c4e81 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-auditor.mdx @@ -0,0 +1,348 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Auditor のカスタム値ファイルを構成する + +このドキュメントでは、ScalarDL Auditor チャートのカスタム値ファイルを作成する方法について説明します。パラメータの詳細を知りたい場合は、ScalarDL Auditor チャートの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardl-audit/README.md) を参照してください。 + +## 必要な構成 + +### Scalar Envoy 構成 + +ScalarDL Auditor のカスタム値ファイルで Scalar Envoy 構成を設定する必要があります。これは、ScalarDL Auditor を Kubernetes 環境にデプロイする場合、クライアントリクエストが gRPC リクエストのロードバランサーとして Scalar Envoy 経由で ScalarDL Auditor に送信されるためです。 + +Scalar Envoy 構成の詳細については、ドキュメント [Scalar Envoy のカスタム値ファイルの構成](configure-custom-values-envoy.mdx)を参照してください。 + +```yaml +envoy: + configurationsForScalarEnvoy: + ... + +auditor: + configurationsForScalarDLAuditor: + ... +``` + +### 画像構成 + +`auditor.image.repository` を設定する必要があります。コンテナーリポジトリからイメージをプルできるように、必ず ScalarDL Auditor コンテナーイメージを指定してください。 + +```yaml +auditor: + image: + repository: +``` + +Scalar 製品のコンテナリポジトリの詳細については、[Scalar 製品のコンテナイメージを取得する方法](../scalar-kubernetes/HowToGetContainerImages.mdx)を参照してください。 + +### Auditor / データベースの構成 + +`auditor.auditorProperties` を設定する必要があります。`auditor.properties` をこのパラメータに設定してください。ScalarDL Auditor の設定の詳細については、[auditor.properties](https://github.com/scalar-labs/scalar/blob/master/auditor/conf/auditor.properties) を参照してください。 + +```yaml +auditor: + auditorProperties: | + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + scalar.db.storage=cassandra + scalar.dl.auditor.ledger.host= + scalar.dl.auditor.private_key_path=/keys/auditor-key-file + scalar.dl.auditor.cert_path=/keys/auditor-cert-file +``` + +### キー/証明書の構成 + +秘密鍵ファイルを `scalar.dl.auditor.private_key_path` に設定し、証明書ファイルを `scalar.dl.auditor.cert_path` に設定する必要があります。 + +秘密鍵ファイルと証明書ファイルも ScalarDL Auditor ポッドにマウントする必要があります。 + +秘密鍵ファイルと証明書ファイルをマウントする方法の詳細については、[ScalarDL Helm Charts のポッドに秘密鍵ファイルと証明書ファイルをマウントする](mount-files-or-volumes-on-scalar-pods.mdx#scalardl-helm-charts-のポッドにキーファイルと証明書ファイルをマウントする)を参照してください。 + +## オプションの構成 + +### リソース構成 (本番環境で推奨) + +Kubernetes のリクエストと制限を使用してポッドリソースを制御したい場合は、`auditor.resources` を使用できます。 + +商用ライセンスの観点から、Scalar 製品の1つのポッドのリソースは 2vCPU / 4GB メモリに制限されていることに注意してください。また、AWS Marketplace から提供される従量課金制のコンテナを取得する場合、`resources.limits` で 2vCPU / 4GB を超えるメモリ構成でそれらのコンテナを実行することはできません。この制限を超えると、ポッドは自動的に停止されます。 + +これらは、Kubernetes のリクエストと制限と同じ構文を使用して構成できます。そのため、Kubernetes の要求と制限の詳細については、公式ドキュメント [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) を参照してください。 + +```yaml +auditor: + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### シークレット構成 + +環境変数を使用して `auditor.auditorProperties` 内の一部のプロパティ (資格情報など) を設定したい場合は、`auditor.secretName` を使用して、いくつかの資格情報を含む Secret リソースを指定できます。 + +たとえば、環境変数を使用してバックエンドデータベースの資格情報 (`scalar.db.username` および `scalar.db.password`) を設定でき、これによりポッドの安全性が高まります。 + +Secret リソースの使用方法の詳細については、ドキュメント [Secret リソースを使用して資格情報を環境変数としてプロパティファイルに渡す方法](use-secret-for-credentials.mdx)を参照してください。 + +```yaml +auditor: + secretName: "auditor-credentials-secret" +``` + +### Affinity configurations (Recommended in the production environment) + +Kubernetes のアフィニティと反アフィニティを使用してポッドのデプロイメントを制御したい場合は、`auditor.affinity` を使用できます。 + +Kubernetes のアフィニティと同じ構文を使用して構成できます。そのため、Kubernetes のアフィニティ設定の詳細については、公式ドキュメント [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) を参照してください。 + +```yaml +auditor: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardl-audit + - key: app.kubernetes.io/app + operator: In + values: + - auditor + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus/Grafana 構成 (運用環境で推奨) + +[kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) を使用して ScalarDL Auditor ポッドを監視する場合は、`auditor.grafanaDashboard.enabled`、`auditor.serviceMonitor` を使用して、kube-prometheus-stack の ConfigMap、ServiceMonitor、および PrometheusRule リソースをデプロイできます。`enabled` および `auditor.prometheusRule.enabled`。 + +```yaml +auditor: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext 設定 (デフォルト値を推奨) + +ScalarDL Auditor ポッドに SecurityContext と PodSecurityContext を設定したい場合は、`auditor.securityContext` と `auditor.podSecurityContext` を使用できます。 + +KubernetesのSecurityContextやPodSecurityContextと同じ構文を使用して設定できます。したがって、Kubernetes の SecurityContext および PodSecurityContext 構成の詳細については、公式ドキュメント [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) を参照してください。 + +```yaml +auditor: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### TLS 構成 (環境に応じてオプション) + +TLS は、次の通信で有効にできます: + +- ScalarDL Auditor とクライアント間の通信。 +- ScalarDL Ledger と ScalarDL Auditor 間の通信。 + +さらに、証明書管理にはいくつかのオプションがあります。詳細については、[Envoy の TLS 構成](./configure-custom-values-envoy.mdx#tls-構成-環境に応じてオプション)を参照してください。 + +セキュリティ要件に基づいて、どの方法を使用するかを検討する必要があります。各方法のガイダンスと関連ドキュメントについては、次の意思決定ツリーを参照してください。 + +```mermaid +flowchart TD + A[cert-manager を使用して
秘密鍵と証明書ファイルを
自動的に管理しますか?] + A -->|はい、証明書を自動的に
管理したいです。| B + A -->|いいえ、証明書は自分で手動で
管理したいです。| C + B[自己署名 CA と
信頼された CA の
どちらを使用しますか?] + C[自己署名 CA と
信頼された CA の
どちらを使用しますか?] + B -->|自己署名 CA を
使用したいです。| D + B -->|信頼できる CA
を使用したいです。| E + C -->|自己署名 CA
を使用したいです。| F + C -->|信頼できる CA
を使用したいです。| G + D[cert-manager で自己署名 CA を使用して
秘密鍵と証明書ファイルを管理する

を参照してください。] + E[cert-manager で信頼できる CA を使用して
秘密鍵と証明書ファイルを管理する

を参照してください。] + F[秘密鍵と証明書ファイルを使用するを参照し、
生成した自己署名証明書を使用します。] + G[秘密鍵と証明書ファイルを使用するを参照し、
第三者によって生成された
信頼できる証明書を使用します。] +``` + +#### TLS を有効にする + +次の構成を使用して、すべての ScalarDL Auditor 接続で TLS を有効にすることができます。 + +```yaml +auditor: + auditorProperties: | + ...(omit)... + scalar.dl.auditor.server.tls.enabled=true + scalar.dl.auditor.server.tls.cert_chain_path=/tls/scalardl-auditor/certs/tls.crt + scalar.dl.auditor.server.tls.private_key_path=/tls/scalardl-auditor/certs/tls.key + scalar.dl.auditor.tls.enabled=true + scalar.dl.auditor.tls.ca_root_cert_path=/tls/scalardl-ledger/certs/ca.crt + scalar.dl.auditor.tls.override_authority=envoy.scalar.example.com + tls: + enabled: true +``` + +##### 秘密鍵と証明書ファイルを使用する + +次の構成を使用して、秘密鍵と証明書ファイルを設定できます。 + +```yaml +auditor: + tls: + enabled: true + caRootCertSecret: "scalardl-auditor-tls-ca" + certChainSecret: "scalardl-auditor-tls-cert" + privateKeySecret: "scalardl-auditor-tls-key" +``` + +この場合、次のように、山括弧内の内容を置き換えて、ScalarDL Ledger および ScalarDL Auditor の秘密鍵と証明書ファイルを含むシークレットリソースを作成する必要があります。 + +```console +kubectl create secret generic scalardl-auditor-tls-ca --from-file=ca.crt=/ -n +kubectl create secret generic scalardl-auditor-tls-cert --from-file=tls.crt=/ -n +kubectl create secret generic scalardl-auditor-tls-key --from-file=tls.key=/ -n +kubectl create secret generic scalardl-auditor-tls-ca-for-ledger --from-file=ca.crt=/ -n +``` + +秘密鍵と証明書ファイルを準備する方法の詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx)を参照してください。 + +##### cert-manager で信頼できる CA を使用して秘密鍵と証明書ファイルを管理する + +次の構成を使用して、山括弧内の内容を説明に従って置き換えることで、cert-manager で秘密鍵と証明書ファイルを管理できます。 + +:::note + +* cert-manager を使用する場合は、cert-manager をデプロイし、`Issuers` リソースを準備する必要があります。詳細については、cert-manager のドキュメント、[インストール](https://cert-manager.io/docs/installation/)および[発行者構成](https://cert-manager.io/docs/configuration/)を参照してください。 +* デフォルトでは、Scalar Helm Chart は Scalar 製品の証明書要件を満たす `Certificate` リソースを作成します。デフォルトの証明書構成が推奨されますが、カスタム証明書構成を使用する場合は、Scalar 製品の証明書要件を満たす必要があります。詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements)を参照してください。 + +::: + +```yaml +auditor: + tls: + enabled: true + certManager: + enabled: true + issuerRef: + name: + dnsNames: + - auditor.scalardl.example.com +``` + +この場合、cert-manager は信頼できる発行者を使用して秘密鍵と証明書ファイルを発行します。秘密鍵と証明書ファイルを手動でマウントする必要はありません。 + +##### cert-manager で自己署名 CA を使用して秘密鍵と証明書ファイルを管理する + +次の構成を使用して、cert-manager で秘密鍵と自己署名証明書ファイルを管理できます。 + +:::note + +* cert-manager を使用する場合は、cert-manager をデプロイする必要があります。詳細については、cert-manager のドキュメント[インストール](https://cert-manager.io/docs/installation/)を参照してください。 +* デフォルトでは、Scalar Helm Chart は Scalar 製品の証明書要件を満たす `Certificate` リソースを作成します。デフォルトの証明書構成が推奨されますが、カスタム証明書構成を使用する場合は、Scalar 製品の証明書要件を満たす必要があります。詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements)を参照してください。 + +::: + +```yaml +auditor: + tls: + enabled: true + certManager: + enabled: true + selfSigned: + enabled: true + dnsNames: + - auditor.scalardl.example.com +``` + +この場合、Scalar Helm Charts と cert-manager が秘密鍵と自己署名証明書ファイルを発行します。秘密鍵と証明書ファイルを手動でマウントする必要はありません。 + +#### ScalarDL Ledger のルート CA 証明書を設定する + +ScalarDL Ledger 側で TLS を有効にする場合は、ScalarDL Auditor からアクセスできるように、ScalarDL Ledger の前にある Envoy のルート CA 証明書ファイルを設定する必要があります。どのアプローチを取るべきかを判断するには、次の意思決定ツリーを参照してください。 + +```mermaid +flowchart TD + A[cert-manager を利用しますか?] + A -->|はい| B + A -->|いいえ| D + B[cert-manager で自己証明書を利用しますか?] + B -->|いいえ| C[cert-manager を使用して ScalarDL Ledger と ScalarDL Auditor に同じ 信頼できる CAを利用しますか??] + C -->|いいえ| D[ScalarDL Ledger 用の Envoy のルート CA 証明書を手動で設定する必要があります。] + C ---->|はい| E[Scalar Helm Chart はルート CA 証明書を自動的に設定します。`auditor.tls.upstream.caRootCertSecret` を明示的に設定する必要はありません。] +``` + +Envoy のルート CA 証明書ファイルを手動で設定する必要がある場合は、次の構成を使用して設定できます。 + +```yaml +auditor: + tls: + enabled: true + caRootCertForLedgerSecret: "scalardl-auditor-tls-ca-for-ledger" +``` + +この場合、次のように山括弧内の内容を置き換えて、ルート CA 証明書ファイルを含むシークレットリソースを作成する必要があります。 + +```console +kubectl create secret generic scalardl-auditor-tls-ca-for-ledger --from-file=ca.crt=//scalardl-ledger -n +``` + +##### TLS通信のカスタム権限を設定する + +`auditor.tls.overrideAuthority` を使用して、TLS 通信のカスタム権限を設定できます。この値によって、実際に接続されているホストが変わることはありません。この値はテスト用ですが、DNS オーバーライドの代替としてテスト以外でも安全に使用できます。たとえば、`auditor.tls.certChainSecret` を使用して設定した証明書チェーンファイルで提示されるホスト名を指定できます。このチャートでは、`startupProbe` と `livenessProbe` にこの値を使用しています。 + +### レプリカ構成 (環境に応じてオプション) + +ScalarDL Auditor のレプリカ (ポッド) の数は、`auditor.replicaCount` を使用して指定できます。 + +```yaml +auditor: + replicaCount: 3 +``` + +### ロギング構成 (環境に応じてオプション) + +ScalarDL Auditor のログレベルを変更したい場合は、`auditor.scalarAuditorConfiguration.auditorLogLevel` を使用できます。 + +```yaml +auditor: + scalarAuditorConfiguration: + auditorLogLevel: INFO +``` + +### 汚染と許容の構成 (環境に応じてオプション) + +Kubernetes のテイントと許容を使用してポッドのデプロイメントを制御したい場合は、`auditor.tolerations` を使用できます。 + +Kubernetes の許容と同じ構文を使用して、テイントと許容を構成できます。Kubernetes での許容設定の詳細については、Kubernetes の公式ドキュメント [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) を参照してください。 + +```yaml +auditor: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardl-auditor +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-ledger.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-ledger.mdx new file mode 100644 index 00000000..d43adee8 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-ledger.mdx @@ -0,0 +1,323 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger のカスタム値ファイルを構成する + +このドキュメントでは、ScalarDL Ledger チャートのカスタム値ファイルを作成する方法について説明します。パラメータの詳細を知りたい場合は、ScalarDL Ledger chartの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardl/README.md) を参照してください。 + +## 必要な構成 + +### Scalar Envoy 構成 + +ScalarDL Ledger のカスタム値ファイルで Scalar Envoy 構成を設定する必要があります。これは、ScalarDL Ledger を Kubernetes 環境にデプロイする場合、クライアントリクエストが gRPC リクエストのロードバランサーとして Scalar Envoy 経由で ScalarDL Ledger に送信されるためです。 + +Scalar Envoy 構成の詳細については、ドキュメント [Scalar Envoy のカスタム値ファイルの構成](configure-custom-values-envoy.mdx)を参照してください。 + +```yaml +envoy: + configurationsForScalarEnvoy: + ... + +ledger: + configurationsForScalarDLLedger: + ... +``` + +### 画像構成 + +`ledger.image.repository` を設定する必要があります。コンテナリポジトリからイメージをプルできるように、ScalarDL Ledger コンテナイメージを必ず指定してください。 + +```yaml +ledger: + image: + repository: +``` + +Scalar 製品のコンテナリポジトリの詳細については、[Scalar 製品のコンテナイメージを取得する方法](../scalar-kubernetes/HowToGetContainerImages.mdx)を参照してください。 + +### Ledger/データベースの構成 + +`ledger.ledgerProperties` を設定する必要があります。`ledger.properties` をこのパラメータに設定してください。ScalarDL Ledger の構成の詳細については、[ledger.properties](https://github.com/scalar-labs/scalar/blob/master/ledger/conf/ledger.properties) を参照してください。 + +```yaml +ledger: + ledgerProperties: | + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + scalar.db.storage=cassandra + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/ledger-key-file +``` + +### キー/証明書の構成 + +`scalar.dl.ledger.proof.enabled` を `true` に設定した場合 (この設定は ScalarDL Auditor を使用する場合に必要です)、秘密鍵ファイルを `scalar.dl.ledger.proof.private_key_path` に設定する必要があります。 + +この場合、秘密鍵ファイルを ScalarDL Ledger ポッドにマウントする必要があります。 + +秘密鍵ファイルをマウントする方法の詳細については、[ScalarDL Helm Charts のポッドに秘密鍵ファイルと証明書ファイルをマウントする](mount-files-or-volumes-on-scalar-pods.mdx#scalardl-helm-charts-のポッドにキーファイルと証明書ファイルをマウントする)を参照してください。 + +## オプションの構成 + +### リソース構成 (本番環境で推奨) + +Kubernetes のリクエストと制限を使用してポッドリソースを制御したい場合は、`ledger.resources` を使用できます。 + +商用ライセンスの観点から、Scalar 製品の1つのポッドのリソースは 2vCPU / 4GB メモリに制限されていることに注意してください。また、AWS Marketplace から提供される従量課金制のコンテナを取得する場合、`resources.limits` で 2vCPU / 4GB を超えるメモリ構成でそれらのコンテナを実行することはできません。この制限を超えると、ポッドは自動的に停止されます。 + +これらは、Kubernetes のリクエストと制限と同じ構文を使用して構成できます。そのため、Kubernetes の要求と制限の詳細については、公式ドキュメント [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) を参照してください。 + +```yaml +ledger: + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### シークレット構成 (運用環境で推奨) + +環境変数を使用して `ledger.ledgerProperties` 内の一部のプロパティ (資格情報など) を設定したい場合は、`ledger.secretName` を使用して、いくつかの資格情報を含む Secret リソースを指定できます。 + +たとえば、環境変数を使用してバックエンドデータベースの資格情報 (`scalar.db.username` および `scalar.db.password`) を設定でき、これによりポッドの安全性が高まります。 + +Secret リソースの使用方法の詳細については、ドキュメント [Secret リソースを使用して資格情報を環境変数としてプロパティファイルに渡す方法](use-secret-for-credentials.mdx)を参照してください。 + +```yaml +ledger: + secretName: "ledger-credentials-secret" +``` + +### アフィニティ構成 (運用環境で推奨) + +Kubernetes のアフィニティと反アフィニティを使用してポッドのデプロイメントを制御したい場合は、`ledger.affinity` を使用できます。 + +Kubernetes のアフィニティと同じ構文を使用して構成できます。そのため、Kubernetes のアフィニティ設定の詳細については、公式ドキュメント [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) を参照してください。 + +```yaml +ledger: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardl + - key: app.kubernetes.io/app + operator: In + values: + - ledger + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus/Grafana 構成 (運用環境で推奨) + +[kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) を使用して ScalarDL Ledger ポッドを監視する場合は、`ledger.grafanaDashboard.enabled`、`ledger.serviceMonitor` を使用して、kube-prometheus-stack の ConfigMap、ServiceMonitor、および PrometheusRule リソースをデプロイできます。`enabled` および `ledger.prometheusRule.enabled`。 + +```yaml +ledger: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext 設定 (デフォルト値を推奨) + +ScalarDL Ledger ポッドに SecurityContext と PodSecurityContext を設定したい場合は、`ledger.securityContext` と `ledger.podSecurityContext` を使用できます。 + +KubernetesのSecurityContextやPodSecurityContextと同じ構文を使用して設定できます。したがって、Kubernetes の SecurityContext および PodSecurityContext 構成の詳細については、公式ドキュメント [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) を参照してください。 + +```yaml +ledger: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### TLS 構成 (環境に応じてオプション) + +TLS は、次の通信で有効にできます: + +- ScalarDL Ledger とクライアント間の通信。 +- ScalarDL Ledger と ScalarDL Auditor 間の通信。 + +また、証明書管理にはいくつかのオプションがあります。詳細については、[Envoy ドキュメント側の TLS 構成](./configure-custom-values-envoy.mdx#tls-configurations-optional-based-on-your-environment)を参照してください。 + +Please consider which you use based on your security requirements. According to your decision, you can see the related document as follows: + +セキュリティ要件に基づいてどちらを使用するかを検討してください。決定に応じて、次の関連ドキュメントを参照できます。 + +```mermaid +flowchart TD + A[cert-manager を使用して
秘密鍵と証明書ファイルを
自動的に管理しますか?] + A -->|はい、証明書を自動的に
管理したいです。| B + A -->|いいえ、証明書は自分で手動で
管理したいです。| C + B[自己署名 CA と
信頼された CA の
どちらを使用しますか?] + C[自己署名 CA と
信頼された CA の
どちらを使用しますか?] + B -->|自己署名 CA を
使用したいです。| D + B -->|信頼できる CA
を使用したいです。| E + C -->|自己署名 CA
を使用したいです。| F + C -->|信頼できる CA
を使用したいです。| G + D[cert-manager で自己署名 CA を使用して
秘密鍵と証明書ファイルを管理する

を参照してください。] + E[cert-manager で信頼できる CA を使用して
秘密鍵と証明書ファイルを管理する

を参照してください。] + F[秘密鍵と証明書ファイルを使用するを参照し、
生成した自己署名証明書を使用します。] + G[秘密鍵と証明書ファイルを使用するを参照し、
第三者によって生成された
信頼できる証明書を使用します。] +``` + +#### TLSを有効にする + +次の設定を使用して、すべての ScalarDL Ledger 接続で TLS を有効にすることができます。 + +```yaml +ledger: + ledgerProperties: | + ...(omit)... + scalar.dl.ledger.server.tls.enabled=true + scalar.dl.ledger.server.tls.cert_chain_path=/tls/scalardl-ledger/certs/tls.crt + scalar.dl.ledger.server.tls.private_key_path=/tls/scalardl-ledger/certs/tls.key + tls: + enabled: true +``` + +##### 秘密鍵と証明書ファイルを使用する + +次の構成を使用して、秘密鍵と証明書ファイルを設定できます。 + +```yaml +ledger: + tls: + enabled: true + caRootCertSecret: "scalardl-ledger-tls-ca" + certChainSecret: "scalardl-ledger-tls-cert" + privateKeySecret: "scalardl-ledger-tls-key" +``` + +この場合、次のように山括弧内の内容を置き換えて、ScalarDL Ledger の秘密鍵と証明書ファイルを含むシークレットリソースを作成する必要があります。 + +```console +kubectl create secret generic scalardl-ledger-tls-ca --from-file=ca.crt=/ -n +kubectl create secret generic scalardl-ledger-tls-cert --from-file=tls.crt=/ -n +kubectl create secret generic scalardl-ledger-tls-key --from-file=tls.key=/ -n +``` + +秘密鍵と証明書ファイルを準備する方法の詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx)を参照してください。 + +##### cert-manager で信頼できる CA を使用して秘密鍵と証明書ファイルを管理する + +次の構成を使用して、cert-manager で秘密鍵と証明書を管理できます。 + +:::note + +* cert-manager を使用する場合は、cert-manager をデプロイし、`Issuers` リソースを準備する必要があります。詳細については、cert-manager のドキュメント、[インストール](https://cert-manager.io/docs/installation/)および[発行者構成](https://cert-manager.io/docs/configuration/)を参照してください。 +* デフォルトでは、Scalar Helm Chart は Scalar 製品の証明書要件を満たす `Certificate` リソースを作成します。デフォルトの証明書構成が推奨されますが、カスタム証明書構成を使用する場合は、Scalar 製品の証明書要件を満たす必要があります。詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements)を参照してください。 + +::: + +```yaml +ledger: + tls: + enabled: true + certManager: + enabled: true + issuerRef: + name: your-trusted-ca + dnsNames: + - ledger.scalardl.example.com +``` + +この場合、cert-manager は信頼できる発行者を使用して秘密鍵と証明書を発行します。秘密鍵と証明書のファイルを手動でマウントする必要はありません。 + +##### cert-manager で自己署名 CA を使用して秘密鍵と証明書ファイルを管理する + +次の構成を使用して、cert-manager で秘密鍵と自己署名証明書を管理できます。 + +:::note + +* cert-manager を使用する場合は、cert-manager をデプロイする必要があります。詳細については、cert-manager のドキュメント[インストール](https://cert-manager.io/docs/installation/)を参照してください。 +* デフォルトでは、Scalar Helm Chart は Scalar 製品の証明書要件を満たす `Certificate` リソースを作成します。デフォルトの証明書構成が推奨されますが、カスタム証明書構成を使用する場合は、Scalar 製品の証明書要件を満たす必要があります。詳細については、[Scalar 製品の秘密鍵と証明書ファイルを作成する方法](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements)を参照してください。 + +::: + +```yaml +ledger: + tls: + enabled: true + certManager: + enabled: true + selfSigned: + enabled: true + dnsNames: + - ledger.scalardl.example.com +``` + +この場合、Scalar Helm Charts と cert-manager が秘密鍵と自己署名証明書を発行します。秘密鍵と証明書ファイルを手動でマウントする必要はありません。 + +##### TLS通信のカスタム権限を設定する + +`ledger.tls.overrideAuthority` を使用して、TLS 通信のカスタム権限を設定できます。この値によって、実際に接続されているホストが変わることはありません。この値はテスト用ですが、DNS オーバーライドの代替としてテスト以外でも安全に使用できます。たとえば、`ledger.tls.certChainSecret` を使用して設定した証明書チェーンファイルで提示されるホスト名を指定できます。このチャートでは、`startupProbe` と `livenessProbe` にこの値を使用しています。 + +```yaml +ledger: + tls: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" +``` + +### レプリカ構成 (環境に応じてオプション) + +`ledger.replicaCount` を使用して ScalarDL Ledger のレプリカ(ポッド)の数を指定できます。 + +```yaml +ledger: + replicaCount: 3 +``` + +### ロギング構成 (環境に応じてオプション) + +ScalarDL Ledger のログレベルを変更したい場合は、`ledger.scalarLedgerConfiguration.ledgerLogLevel` を使用できます。 + +```yaml +ledger: + scalarLedgerConfiguration: + ledgerLogLevel: INFO +``` + +### 汚染と許容の構成 (環境に応じてオプション) + +Kubernetes のテイントと許容を使用してポッドのデプロイメントを制御したい場合は、`ledger.tolerations` を使用できます。 + +Kubernetes の許容と同じ構文を使用して、テイントと許容を構成できます。Kubernetes での許容設定の詳細については、Kubernetes の公式ドキュメント [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) を参照してください。 + +```yaml +ledger: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardl-ledger +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-schema-loader.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-schema-loader.mdx new file mode 100644 index 00000000..bb352ad4 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/configure-custom-values-scalardl-schema-loader.mdx @@ -0,0 +1,94 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Schema Loader のカスタム値ファイルを構成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDL Schema Loader チャートのカスタム値ファイルを作成する方法について説明します。パラメータの詳細を知りたい場合は、ScalarDL Schema Loader チャートの [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/schema-loading/README.md) を参照してください。 + +## 必要な構成 + +### データベース構成 + +`schemaLoading.databaseProperties` を設定する必要があります。バックエンドデータベースにアクセスするには、`database.properties` をこのパラメータに設定してください。ScalarDB のデータベース構成の詳細については、[Getting Started with ScalarDB](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb) を参照してください。 + +```yaml +schemaLoading: + databaseProperties: | + scalar.db.contact_points=cassandra + scalar.db.contact_port=9042 + scalar.db.username=cassandra + scalar.db.password=cassandra + scalar.db.storage=cassandra +``` + +### スキーマタイプの構成 + +`schemaLoading.schemaType` を設定する必要があります。 + +ScalarDL Ledger のスキーマを作成する場合は `ledger` を設定してください。 + +```yaml +schemaLoading: + schemaType: ledger +``` + +ScalarDL Auditor のスキーマを作成する場合は `auditor` を設定してください。 + +```yaml +schemaLoading: + schemaType: auditor +``` + +## オプションの構成 + +### シークレット構成 (運用環境で推奨) + +環境変数を使用して `schemaLoading.databaseProperties` 内の一部のプロパティ (資格情報など) を設定したい場合は、`schemaLoading.secretName` を使用して、いくつかの資格情報を含む Secret リソースを指定できます。 + +たとえば、環境変数を使用してバックエンドデータベースの資格情報 (`scalar.db.username` および `scalar.db.password`) を設定でき、これによりポッドの安全性が高まります。 + +Secret リソースの使用方法の詳細については、ドキュメント [Secret リソースを使用して資格情報を環境変数としてプロパティファイルに渡す方法](use-secret-for-credentials.mdx)を参照してください。 + +```yaml +schemaLoading: + secretName: "schema-loader-credentials-secret" +``` + +### 画像構成 (デフォルト値を推奨) + +イメージリポジトリを変更する場合は、`schemaLoading.image.repository` を使用して、プルする ScalarDL Schema Loader コンテナイメージのコンテナリポジトリ情報を指定できます。 + +```yaml +schemaLoading: + image: + repository: +``` + +### フラグ設定 (環境に応じてオプション) + +複数のフラグを配列として指定できます。フラグの詳細については、ドキュメント [ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader) を参照してください。 + +```yaml +schemaLoading: + commandArgs: + - "--alter" + - "--compaction-strategy" + - "" + - "--delete-all" + - "--no-backup" + - "--no-scaling" + - "--repair-all" + - "--replication-factor" + - "" + - "--replication-strategy" + - "" + - "--ru" + - "" +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-logging.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-logging.mdx new file mode 100644 index 00000000..2b25b193 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-logging.mdx @@ -0,0 +1,101 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# Helm Charts をはじめよう (Loki スタックを使用したロギング) + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Grafana Loki (Promtail を使用) を使用して、Kubernetes 上で Scalar 製品のログ集約を開始する方法について説明します。 + +Scalar 製品の[モニタリングの開始](getting-started-monitoring.mdx)をすでに読み、kube-prometheus-stack をインストールしていることを前提としています。 + +## 私たちが作るもの + +次のように、次のコンポーネントを Kubernetes クラスターにデプロイします。 + +``` ++--------------------------------------------------------------------------------------------------+ +| +------------------------------------+ | +| | loki-stack | | +| | | +-----------------+ | +| | +--------------+ +--------------+ | <-----------------(ログ)-------------- | Scalar 製品 | | +| | | Loki | | Promtail | | | | | +| | +--------------+ +--------------+ | | +-----------+ | | +| +------------------------------------+ | | ScalarDB | | | +| | +-----------+ | | +| +------------------------------------------------------+ | | | +| | kube-prometheus-stack | | +-----------+ | | +| | | | | ScalarDL | | | +| | +--------------+ +--------------+ +--------------+ | -----(監視)----> | +-----------+ | | +| | | Prometheus | | Alertmanager | | Grafana | | +-----------------+ | +| | +-------+------+ +------+-------+ +------+-------+ | | +| | | | | | | +| | +----------------+-----------------+ | | +| | | | | +| +--------------------------+---------------------------+ | +| | | +| | Kubernetes | ++----------------------------+---------------------------------------------------------------------+ + | <- localhost (127.0.0.1) に公開するか、ロードバランサーなどを使用してアクセスします + | + (HTTP 経由でダッシュボードにアクセスする) + | + +----+----+ + | ブラウザ | + +---------+ +``` + +## ステップ1. カスタム値ファイルを準備する + +1. `loki-stack` helm chart のサンプルファイル [scalar-loki-stack-custom-values.yaml](./conf/scalar-loki-stack-custom-values.yaml) を取得します。 + +## ステップ2. `loki-stack` をデプロイする + +1. `grafana` helm リポジトリを追加します。 + ```console + helm repo add grafana https://grafana.github.io/helm-charts + ``` + +1. `loki-stack` helm chart をデプロイします。 + ```console + helm install scalar-logging-loki grafana/loki-stack -n monitoring -f scalar-loki-stack-custom-values.yaml + ``` + +## ステップ3. Grafana 構成に Loki データソースを追加する + +1. Loki データソースの設定を `scalar-prometheus-custom-values.yaml` ファイルに追加します。 + ```yaml + grafana: + additionalDataSources: + - name: Loki + type: loki + uid: loki + url: http://scalar-logging-loki:3100/ + access: proxy + editable: false + isDefault: false + ``` + +1. 構成を適用します (`kube-prometheus-stack` のデプロイメントをアップグレードします)。 + ```console + helm upgrade scalar-monitoring prometheus-community/kube-prometheus-stack -n monitoring -f scalar-prometheus-custom-values.yaml + ``` + +## ステップ4. Grafana ダッシュボードにアクセスする + +1. Loki をデータソースとして追加する + - Grafana http://localhost:3000 に移動します (minikube を使用する場合) + - `Explore` に移動して、追加された Loki を見つけます + - 収集されたログは `Explore` ページで確認できます。 + +## ステップ5. `loki-stack` helm chartを削除する + +1. `loki-stack` をアンインストールします。 + ```console + helm uninstall scalar-logging-loki -n monitoring + ``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-monitoring.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-monitoring.mdx new file mode 100644 index 00000000..1010b668 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-monitoring.mdx @@ -0,0 +1,271 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング) + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Prometheus Operator (kube-prometheus-stack) を使用して Kubernetes 上で Scalar 製品の監視を開始する方法について説明します。ここでは、テスト用の Mac または Linux 環境がすでにあることを前提としています。このドキュメントでは **Minikube** を使用しますが、これから説明する手順はどの Kubernetes クラスターでも機能するはずです。 + +## 私たちが作るもの + +次のように、次のコンポーネントを Kubernetes クラスターにデプロイします。 + +``` ++--------------------------------------------------------------------------------------------------+ +| +------------------------------------------------------+ +-----------------+ | +| | kube-prometheus-stack | | Scalar 製品 | | +| | | | | | +| | +--------------+ +--------------+ +--------------+ | -----(監視)----> | +-----------+ | | +| | | Prometheus | | Alertmanager | | Grafana | | | | ScalarDB | | | +| | +-------+------+ +------+-------+ +------+-------+ | | +-----------+ | | +| | | | | | | +-----------+ | | +| | +----------------+-----------------+ | | | ScalarDL | | | +| | | | | +-----------+ | | +| +--------------------------+---------------------------+ +-----------------+ | +| | | +| | Kubernetes | ++----------------------------+---------------------------------------------------------------------+ + | <- localhost (127.0.0.1) に公開するか、ロードバランサーなどを使用してアクセスします + | + (HTTP 経由でダッシュボードにアクセスする) + | + +----+----+ + | ブラウザ | + +---------+ +``` + +## ステップ1. Kubernetes クラスターを開始する + +まず、Kubernetes クラスターを準備する必要があります。**minikube** 環境を使用する場合は、[Scalar Helm Charts をはじめよう](getting-started-scalar-helm-charts.mdx)を参照してください。すでに Kubernetes クラスターを開始している場合は、この手順をスキップできます。 + +## ステップ2. カスタム値ファイルを準備する + +1. `kube-prometheus-stack` のサンプルファイル [scalar-prometheus-custom-values.yaml](./conf/scalar-prometheus-custom-values.yaml) を保存します。 + +1. 次のように `scalar-prometheus-custom-values.yaml` にカスタム値を追加します。 + * 設定 + * `prometheus.service.type` を `LoadBalancer` に設定します。 + * `alertmanager.service.type` を `LoadBalancer` に設定します。 + * `grafana.service.type` を `LoadBalancer` に設定します。 + * `grafana.service.port` を `3000` に設定します。 + * 例 + ```yaml + alertmanager: + + service: + type: LoadBalancer + + ... + + grafana: + + service: + type: LoadBalancer + port: 3000 + + ... + + prometheus: + + service: + type: LoadBalancer + + ... + ``` + * 注記: + * Helm Chart を使用して Prometheus Operator デプロイメントをカスタマイズする場合は、Scalar 製品を監視するために次の構成を設定する必要があります。 + * Prometheus Operator が Scalar 製品の `ServiceMonitor` および `PrometheusRule` を検出できるように、`serviceMonitorSelectorNilUsesHelmValues` および `ruleSelectorNilUsesHelmValues` を `false` (デフォルトでは `true`) に設定します。 + + * Scalar Manager を使用する場合は、Scalar Manager が CPU およびメモリリソースを収集できるように次の構成を設定する必要があります。 + * `kubeStateMetrics.enabled`、`nodeExporter.enabled`、および `kubelet.enabled` を `true` に設定します。 + + * Scalar Manager を使用する場合は、Scalar Manager が Grafana を組み込みきるように次の構成を設定する必要があります。 + * `grafana.ini.security.allow_embedding` および `grafana.ini.auth.anonymous.enabled` を `true` に設定します。 + * `grafana.ini.auth.anonymous.org_name` を使用中の組織に設定します。Scalar のサンプルを使う場合では、`Main Org.` に設定します。 + * `grafana.ini.auth.anonymous.org_role` を `Editor` に設定します。 + +## ステップ3. `kube-prometheus-stack` をデプロイする + +1. `prometheus-community` helm リポジトリを追加します。 + ```console + helm repo add prometheus-community https://prometheus-community.github.io/helm-charts + ``` + +1. Kubernetes 上に名前空間 `monitoring` を作成します。 + ```console + kubectl create namespace monitoring + ``` + +1. `kube-prometheus-stack` をデプロイします。 + ```console + helm install scalar-monitoring prometheus-community/kube-prometheus-stack -n monitoring -f scalar-prometheus-custom-values.yaml + ``` + +## ステップ4. Helm Chart を使用して Scalar 製品をデプロイ (またはアップグレード) + +* 注記: + * 最低限の手順を説明します。ScalarDB および ScalarDL のデプロイメントについて詳しく知りたい場合は、以下のドキュメントを参照してください。 + * [Helm Charts 入門 (ScalarDB Server)](getting-started-scalardb.mdx) + * [Helm Charts 入門 (ScalarDL Ledger / Ledger のみ)](getting-started-scalardl-ledger.mdx) + * [Helm Charts 入門 (ScalarDL Ledger および Auditor / Auditor モード)](getting-started-scalardl-auditor.mdx) + +1. Scalar 製品の Prometheus 監視を有効にするには、カスタム値ファイルで次の構成に `true` を設定します。 + * 構成 + * `*.prometheusRule.enabled` + * `*.grafanaDashboard.enabled` + * `*.serviceMonitor.enabled` + * サンプル設定ファイル + * ScalarDB (scalardb-custom-values.yaml) + ```yaml + envoy: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + + scalardb: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + ``` + * ScalarDL Ledger (scalardl-ledger-custom-values.yaml) + ```yaml + envoy: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + + ledger: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + ``` + * ScalarDL Auditor (scalardl-auditor-custom-values.yaml) + ```yaml + envoy: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + + auditor: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + ``` + +1. 上記のカスタム値ファイルを含む Helm Charts を使用して、Scalar 製品をデプロイ (またはアップグレード) します。 + * 例 + * ScalarDB + ```console + helm install scalardb scalar-labs/scalardb -f ./scalardb-custom-values.yaml + ``` + ```console + helm upgrade scalardb scalar-labs/scalardb -f ./scalardb-custom-values.yaml + ``` + * ScalarDL Ledger + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + ```console + helm upgrade scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + * ScalarDL Auditor + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + ```console + helm upgrade scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + +## ステップ5. ダッシュボードにアクセスする + +### minikube を使用する場合 + +1. 各サービスリソースを `localhost (127.0.0.1)` として公開するには、別のターミナルを開き、`minikube tunnel` コマンドを実行します。 + ```console + minikube tunnel + ``` + + `minikube tunnel` コマンドを実行すると、各サービスリソースの EXTERNAL-IP が `127.0.0.1` として表示されます。 + ```console + kubectl get svc -n monitoring scalar-monitoring-kube-pro-prometheus scalar-monitoring-kube-pro-alertmanager scalar-monitoring-grafana + ``` + 【コマンド実行結果】 + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + scalar-monitoring-kube-pro-prometheus LoadBalancer 10.98.11.12 127.0.0.1 9090:30550/TCP 26m + scalar-monitoring-kube-pro-alertmanager LoadBalancer 10.98.151.66 127.0.0.1 9093:31684/TCP 26m + scalar-monitoring-grafana LoadBalancer 10.103.19.4 127.0.0.1 3000:31948/TCP 26m + ``` + +1. 各ダッシュボードにアクセスします。 + * Prometheus + ```console + http://localhost:9090/ + ``` + * Alertmanager + ```console + http://localhost:9093/ + ``` + * Grafana + ```console + http://localhost:3000/ + ``` + * 注記: + * Grafana のユーザーとパスワードは以下で確認できます。 + * ユーザー + ```console + kubectl get secrets scalar-monitoring-grafana -n monitoring -o jsonpath='{.data.admin-user}' | base64 -d + ``` + * パスワード + ```console + kubectl get secrets scalar-monitoring-grafana -n monitoring -o jsonpath='{.data.admin-password}' | base64 -d + ``` + +### minikube 以外の Kubernetes を使用する場合 + +minikube 以外の Kubernetes クラスターを使用する場合は、各 Kubernetes クラスターの方式に従って LoadBalancer サービスにアクセスする必要があります。たとえば、クラウドサービスによって提供されるロードバランサーや `kubectl port-forward` コマンドを使用します。 + +## ステップ6. すべてのリソースを削除する + +Kubernetes クラスターでのモニタリングテストが完了したら、すべてのリソースを削除します。 + +1. `minikube tunnel` コマンドを終了します。(minikubeを使用する場合) + ```console + Ctrl + C + ``` + +1. `kube-prometheus-stack` をアンインストールします。 + ```console + helm uninstall scalar-monitoring -n monitoring + ``` + +1. minikube を削除します。(オプション / minikube を使用する場合) + ```console + minikube delete --all + ``` + * 注記: + * ScalarDB または ScalarDL をデプロイする場合は、minikube を削除する前にそれらを削除する必要があります。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalar-helm-charts.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalar-helm-charts.mdx new file mode 100644 index 00000000..3d6e5ef6 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalar-helm-charts.mdx @@ -0,0 +1,82 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar Helm Charts をはじめよう + +このドキュメントでは、Kubernetes クラスター上でテスト環境として Scalar Helm Chart を開始する方法について説明します。ここでは、テスト用の Mac または Linux 環境がすでにあることを前提としています。このドキュメントでは **Minikube** を使用しますが、これから説明する手順はどの Kubernetes クラスターでも機能するはずです。 + +## ツール + +テストには次のツールを使用します。 + +1. minikube (他の Kubernetes ディストリビューションを使用する場合、minikube は必要ありません。) +1. kubectl +1. Helm +1. cfssl / cfssljson + +## ステップ1. ツールをインストールする + +まず、このガイドで使用する次のツールをインストールする必要があります。 + +1. [minikubeドキュメント](https://minikube.sigs.k8s.io/docs/start/)に従って minikube をインストールします。 + +1. [Kubernetesドキュメント](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/)に従って kubectl をインストールします。 + +1. [Helmドキュメント](https://helm.sh/docs/intro/install/)に従って helm コマンドをインストールします。 + +1. [CFSSLドキュメント](https://github.com/cloudflare/cfssl)に従って cfssl と cfssljson をインストールします。 + +:::note + +以下のスタートガイドの手順を実行する場合は、`cfssl` および `cfssljson` コマンドをインストールする必要があります。 + +* [TLS を使用した ScalarDB Cluster](getting-started-scalardb-cluster-tls.mdx) +* [TLS を使用した ScalarDL Ledger および Auditor (Auditor モード)](getting-started-scalardl-auditor-tls.mdx) +* [ScalarDL Ledger (Ledger のみ)](getting-started-scalardl-ledger.mdx) +* [ScalarDL Ledger と Auditor (Auditor モード)](getting-started-scalardl-auditor.mdx) + +::: + +## ステップ2. docker ドライバーで minikube を起動する (オプション / minikube を使用する場合) + +1. minikube を起動します。 + ```console + minikube start + ``` + +1. minikube とポッドのステータスを確認します。 + ```console + kubectl get pod -A + ``` + 【コマンド実行結果】 + ```console + NAMESPACE NAME READY STATUS RESTARTS AGE + kube-system coredns-64897985d-lbsfr 1/1 Running 1 (20h ago) 21h + kube-system etcd-minikube 1/1 Running 1 (20h ago) 21h + kube-system kube-apiserver-minikube 1/1 Running 1 (20h ago) 21h + kube-system kube-controller-manager-minikube 1/1 Running 1 (20h ago) 21h + kube-system kube-proxy-gsl6j 1/1 Running 1 (20h ago) 21h + kube-system kube-scheduler-minikube 1/1 Running 1 (20h ago) 21h + kube-system storage-provisioner 1/1 Running 2 (19s ago) 21h + ``` + minikube が適切に起動すると、いくつかのポッドが kube-system 名前空間で**実行中**であることがわかります。 + +## ステップ3。 + +Kubernetes クラスターが起動したら、そのクラスター上で各 Scalar Helm Charts を試すことができます。詳細については、以下のドキュメントを参照してください。 + +* [TLS を使用した ScalarDB Cluster](getting-started-scalardb-cluster-tls.mdx) +* [cert-manager を使用した TLS 対応 ScalarDB Cluster](getting-started-scalardb-cluster-tls-cert-manager.mdx) +* [ScalarDB Analytics with PostgreSQL](getting-started-scalardb-analytics-postgresql.mdx) +* [TLS を使用した ScalarDL Ledger および Auditor (Auditor モード)](getting-started-scalardl-auditor-tls.mdx) +* [cert-manager を使用した TLS による ScalarDL Ledger と ScalarDL Auditor (Auditor モード)](getting-started-scalardl-auditor-tls-cert-manager.mdx) +* [ScalarDL Ledger (Ledger のみ)](getting-started-scalardl-ledger.mdx) +* [ScalarDL Ledger と Auditor (Auditor モード)](getting-started-scalardl-auditor.mdx) +* [Prometheus Operator を使用した監視](getting-started-monitoring.mdx) + * [Loki スタックを使用したロギング](getting-started-logging.mdx) + * [Scalar Manager](getting-started-scalar-manager.mdx) +* [[非推奨] ScalarDB Server](getting-started-scalardb.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalar-manager.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalar-manager.mdx new file mode 100644 index 00000000..8c1991ae --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalar-manager.mdx @@ -0,0 +1,223 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# Scalar Manager をデプロイする + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +[Scalar Manager](../scalar-manager/overview.mdx) は、Kubernetes クラスター環境内の ScalarDB および ScalarDL を集中管理および監視するソリューションです。これにより、次のことが可能になります。 + +- ScalarDB または ScalarDL が利用可能な状態かを監視します。 +- ScalarDB または ScalarDL が使用するデータベースでトランザクションの一貫性のある期間を作成する一時停止ジョブをスケジュールまたは実行します。 +- Grafana ダッシュボードを介して ScalarDB または ScalarDL の時系列メトリックとログを確認します。 + +このガイドでは、Scalar Helm Charts を使用して Kubernetes クラスターに Scalar Manager をデプロイしてアクセスする方法について説明します。 + +## 前提条件 + +Scalar Manager をデプロイする前に、次の操作を行う必要があります。 + +- [Scalar Helm Charts をはじめよう](getting-started-scalar-helm-charts.mdx)に記載されているツールをインストールします。 +- [Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング)](getting-started-monitoring.mdx)の手順に従って、`kube-prometheus-stack` をデプロイします。 +- [Helm Charts をはじめよう (Loki Stack を使用したログ記録)](getting-started-logging.mdx)の手順に従って、`loki-stack` をデプロイします。 + +## デプロイアーキテクチャ図 + +以下は、Kubernetes クラスターにデプロイされたコンポーネントのアーキテクチャ図です。 + +``` ++----------------------------------------------------------------------------------------------------------------------+ +| +----------------------------+ | +| | scalar-manager | | +| | | | +| | +------------------+ | ---------------------------------(Manage)--------------------------+ | +| +---+--->| Scalar Manager | | | | +| | | +---+--------------+ | | | +| | | | | | | +| | +--------+-------------------+ | | +| | | | | +| | +----+------------------------------------------+ | | +| | | | | | +| | +--------+------------------------------------------+---------+ | | +| | | | kube-prometheus-stack | | V | +| | | V V | +-----------------+ | +| | | +--------------+ +--------------+ +--------------+ | -----(Monitor)----> | Scalar Products | | +| | | | Prometheus | <---+ | Alertmanager | | Grafana | | | | | +| | | +------+-------+ | +--------------+ +------+-------+ | | +-----------+ | | +| | | | | | | | ScalarDB | | | +| | | +----------------------------+ | | +-----------+ | | +| | | | | | | | +| | +---------------------------------------------------+---------+ | +-----------+ | | +| | | | | ScalarDL | | | +| | +------------------------------------------+ +---------- | +-----------+ | | +| | | | +-----------------+ | +| | +--------+---------------------------+ | | +| | | | loki-stack | | | +| | | V | | | +| | | +--------------+ +--------------+ | <----------------(Log)-----------+ | +| | | | Loki | | Promtail | | | +| | | +--------------+ +--------------+ | | +| | +------------------------------------+ | +| | | +| | Kubernetes | ++----+-----------------------------------------------------------------------------------------------------------------+ + | + Expose the environment to localhost (127.0.0.1) or use a load balancer to access it + | + (Access the dashboard through HTTP) + | ++----+----+ +| Browser | ++---------+ + +``` + +## ステップ1. minikube を起動します + +**Terminal** を開き、次のコマンドを実行して minikube を起動します。 + +```console +minikube start +``` + +## ステップ 2. `kube-prometheus-stack` をアップグレードして、認証プロキシを使用した Grafana 認証を有効にします + +Scalar Manager にログインした後でユーザーが Grafana にアクセスできるようにするには、認証プロキシを使用した Grafana 認証を有効にする必要があります。 + +`kube-prometheus-stack` のカスタム値ファイル (たとえば、`scalar-prometheus-custom-values.yaml`) で、次の設定を追加または修正します。 + +```yaml +kubeStateMetrics: + enabled: true + +nodeExporter: + enabled: true + +kubelet: + enabled: true + +grafana: + grafana.ini: + users: + allow_sign_up: false + auto_assign_org: true + auto_assign_org_role: Editor + auth.proxy: + enabled: true + header_name: X-WEBAUTH-USER + header_property: username + auto_sign_up: true + server: + root_url: "%(protocol)s://%(domain)s:%(http_port)s/grafana" +``` + +次に、次のコマンドを実行して Helm インストールをアップグレードします。 + +```console +helm upgrade scalar-monitoring prometheus-community/kube-prometheus-stack -n monitoring -f scalar-prometheus-custom-values.yaml +``` + +## ステップ3. 環境変数を設定する + +Scalar Manager の次の環境変数を設定し、山括弧内の内容を説明に従って置き換えます。 + +```console +SCALAR_MANAGER_RELEASE_NAME= +SCALAR_MANAGER_NAMESPACE= +SCALAR_MANAGER_CUSTOM_VALUES_FILE= +SCALAR_MANAGER_CHART_VERSION= +``` + +## ステップ4. カスタム値ファイルを準備する + +Scalar Manager のカスタム値ファイルを準備します。 + +1. `scalar-manager-custom-values.yaml` という名前の空のファイルを作成します。 +2. [Scalar Manager のカスタム値ファイルを設定する](configure-custom-values-scalar-manager.mdx)の手順に従います。 + +## ステップ5. デプロイする + +次のコマンドを実行して、`scalar-manager` Helm Chart をデプロイします。 + +```console +helm install ${SCALAR_MANAGER_RELEASE_NAME} scalar-labs/scalar-manager -n ${SCALAR_MANAGER_NAMESPACE} -f ${SCALAR_MANAGER_CUSTOM_VALUES_FILE} --version ${SCALAR_MANAGER_CHART_VERSION} +``` + +## ステップ6. Scalar Manager にアクセスする + +Scalar Manager にアクセスする方法は、Kubernetes クラスターによって異なります。 + + + + Scalar Manager をローカルホスト (127.0.0.1) で公開するには、別のターミナルを開いて `minikube tunnel` コマンドを実行します。 + + ```console + minikube tunnel + ``` + + 次に、http://localhost:8000 で Scalar Manager にアクセスします。 + + + minikube 以外の Kubernetes クラスターを使用している場合は、クラスターの説明に従って `LoadBalancer` サービスにアクセスします。たとえば、クラウドサービスプロバイダーのロードバランサーを使用するか、`kubectl port-forward` コマンドを使用します。 + + + +## 追加の詳細 + +このセクションでは、設定とリソース検出に関する追加の詳細について説明します。 + +### Scalar Manager をアップグレードする + +Scalar Manager をアップグレードするには、次のコマンドを実行します。 + +```console +helm upgrade ${SCALAR_MANAGER_RELEASE_NAME} scalar-labs/scalar-manager -n ${SCALAR_MANAGER_NAMESPACE} -f ${SCALAR_MANAGER_CUSTOM_VALUES_FILE} --version ${SCALAR_MANAGER_CHART_VERSION} +``` + +### Scalar Manager をアンインストールする + +Scalar Manager をアンインストールするには、次のコマンドを実行します。 + +```console +helm uninstall ${SCALAR_MANAGER_RELEASE_NAME} -n ${SCALAR_MANAGER_NAMESPACE} +``` + +### オプションの Scalar Manager 設定 + +Scalar Manager に設定できるオプションの設定については、[オプション設定](./configure-custom-values-scalar-manager.mdx#オプション設定)を参照してください。 + +### リソースの検出 + +Scalar Manager は、特定のラベルセレクターを使用して、クラスター内の次の Kubernetes リソースを検出します。 + +- 依存関係 + - Prometheus サービス +- ターゲット + - ScalarDB Cluster のデプロイメント + - ScalarDL Ledger のデプロイメント + - ScalarDL Auditor のデプロイメント + +次のセクションでは、Scalar Manager がこれらのリソースを検出する方法について説明します。 + +#### 依存関係 + +Scalar Manager は、[kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) Helm Chart に設定されているデフォルトのラベルと値を検索します。Scalar Manager が依存関係を検出するために使用するデフォルトのラベルと値の詳細については、[`api.applicationProperties` で設定できるプロパティ](./configure-custom-values-scalar-manager.mdx#apiapplicationProperties-で設定できるプロパティ)を参照してください。 + +また、`kube-prometheus-stack` のインストール時に値をカスタマイズした場合は、Scalar Manager のカスタム値 `api.applicationProperties` のラベルセレクターを更新する必要があります。 + +#### ターゲット + +Scalar Manager は、次のラベルと値を使用して、ScalarDB Cluster、ScalarDL Ledger、および ScalarDL Auditor のデプロイメントを検索します。 + +- **ScalarDB Cluster:** `app.kubernetes.io/app=scalardb-cluster` +- **ScalarDL Ledger:** `app.kubernetes.io/app=ledger` +- **ScalarDL Auditor:** `app.kubernetes.io/app=auditor` + +Scalar Helm Charts は、ScalarDB Cluster、ScalarDL Ledger、および ScalarDL Auditor のデプロイメントに固定のラベルと値を使用するため、[Scalar Helm Charts](https://github.com/scalar-labs/helm-charts) を使用して ScalarDB と ScalarDL をインストールすると、Scalar Manager はこれらのデプロイメントを自動的に検出します。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-analytics-postgresql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-analytics-postgresql.mdx new file mode 100644 index 00000000..57f8d795 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-analytics-postgresql.mdx @@ -0,0 +1,533 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# Helm Charts をはじめよう (ScalarDB Analytics with PostgreSQL) + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、Kubernetes クラスターの Helm Chart をテスト環境として使用して、ScalarDB Analytics with PostgreSQL を開始する方法について説明します。さらに、このガイドの内容は、テスト用に Mac または Linux 環境がすでにセットアップされていることを前提としています。**minikube** について言及していますが、説明されている手順はどの Kubernetes クラスターでも機能するはずです。 + +## あなたが作成するもの + +次のコンポーネントを Kubernetes クラスターにデプロイします。 + +``` ++-------------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes クラスター] | +| | +| [ポッド] [ポッド] [ポッド] | +| | +| +------------------------------------+ | +| +---> | ScalarDB Analytics with PostgreSQL | ---+ +-----------------------------+ | +| | +------------------------------------+ | +---> | MySQL (「顧客」スキーマ) | <---+ | +| | | | +-----------------------------+ | | +| +-------------+ +---------+ | +------------------------------------+ | | | | +| | OLAP クライアント | ---> | サービス | ---+---> | ScalarDB Analytics with PostgreSQL | ---+---+ +---+ | +| +-------------+ +---------+ | +------------------------------------+ | | | | | +| | | | +-----------------------------+ | | | +| | +------------------------------------+ | +---> | PostgreSQL (「順序」スキーマ) | <---+ | | +| +---> | ScalarDB Analytics with PostgreSQL | ---+ +-----------------------------+ | | +| +------------------------------------+ | | +| | | +| +-------------+ | | +| | OLTP クライアント | ---(テスト OLTP ワークロードでサンプルデータをロードする)-----------------------------------------------------------------------+ | +| +-------------+ | +| | ++-------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ステップ1. Kubernetes クラスターを開始する + +まず、Kubernetes クラスターを準備する必要があります。**minikube** 環境を使用している場合は、[Scalar Helm Charts をはじめよう](getting-started-scalar-helm-charts.mdx)を参照してください。すでに Kubernetes クラスターを開始している場合は、この手順をスキップできます。 + +## ステップ2. MySQL および PostgreSQL ポッドを開始する + +ScalarDB Analytics with PostgreSQL を含むScalarDBは、バックエンドデータベースとして数種類のデータベースシステムを利用できます。このガイドでは、MySQL と PostgreSQL を使用します。 + +次のようにして、Kubernetes クラスターに MySQL と PostgreSQL をデプロイできます。 + +1. Bitnami Helm リポジトリを追加します。 + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Helm リポジトリを更新します。 + + ```console + helm repo update bitnami + ``` + +1. MySQLをデプロイします。 + + ```console + helm install mysql-scalardb bitnami/mysql \ + --set auth.rootPassword=mysql \ + --set primary.persistence.enabled=false + ``` + +1. PostgreSQLをデプロイします。 + + ```console + helm install postgresql-scalardb bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. MySQL および PostgreSQL ポッドが実行されているかどうかを確認します。 + + ```console + kubectl get pod + ``` + + 次の出力が表示されるはずです。 + + ```console + kubectl get pod + ``` + + 次のような結果が表示されます: + + ```console + NAME READY STATUS RESTARTS AGE + mysql-scalardb-0 1/1 Running 0 3m17s + postgresql-scalardb-0 1/1 Running 0 3m12s + ``` + +## ステップ3. 作業ディレクトリを作成する + +いくつかの構成ファイルをローカルに作成するので、それらのファイル用の作業ディレクトリを作成します。 + + ```console + mkdir -p ~/scalardb-analytics-postgresql-test/ + ``` + +## ステップ4. ScalarDB、ScalarDB Analytics with PostgreSQL、およびチャートのバージョンを設定します + +以下の3つの環境変数を設定します。別のバージョンの ScalarDB および ScalarDB Analytics with PostgreSQL を使用する場合は、必ず使用するバージョンに設定してください。 + +:::note + +ScalarDB Analytics with PostgreSQL のマイナーバージョン (例: 3.10.x) を ScalarDB と同じにする必要がありますが、パッチのバージョンを一致させる必要はありません。たとえば、ScalarDB 3.10.1と ScalarDB Analytics with PostgreSQL 3.10.3を併用できます。 + +::: + +```console +SCALARDB_VERSION=3.10.1 +``` + +```console +SCALARDB_ANALYTICS_WITH_POSTGRESQL_VERSION=3.10.3 +``` + +```console +CHART_VERSION=$(helm search repo scalar-labs/scalardb-analytics-postgresql -l | grep -e ${SCALARDB_ANALYTICS_WITH_POSTGRESQL_VERSION} | awk '{print $2}' | sort --version-sort -r | head -n 1) +``` + +## ステップ5. OLTP トランザクションを実行して、サンプルデータを MySQL および PostgreSQL にロードします + +ScalarDB Analytics with PostgreSQL を導入する前に、OLTPトランザクションを実行してサンプルデータを作成します。 + +1. Kubernetes クラスターで OLTP クライアントポッドを開始します。 + + ```console + kubectl run oltp-client --image eclipse-temurin:8-jdk-jammy --env SCALARDB_VERSION=${SCALARDB_VERSION} -- sleep inf + ``` + +1. OLTP クライアントポッドが実行されているかどうかを確認します。 + + ```console + kubectl get pod oltp-client + ``` + + 次の出力が表示されるはずです。 + + ```console + kubectl get pod oltp-client + ``` + + 次のような結果が表示されます: + + ```console + NAME READY STATUS RESTARTS AGE + oltp-client 1/1 Running 0 17s + ``` + +1. OLTP クライアントポッドで bash を実行します。 + + ```console + kubectl exec -it oltp-client -- bash + ``` + + この手順の後、OLTP クライアントポッドで各コマンドを実行します。 + +1. git および curl コマンドを OLTP クライアントポッドにインストールします。 + + ```console + apt update && apt install -y curl git + ``` + +1. ScalarDB サンプルリポジトリのクローンを作成します。 + + ```console + git clone https://github.com/scalar-labs/scalardb-samples.git + ``` + +1. ディレクトリ `scalardb-samples/multi-storage-transaction-sample/` に移動します。 + + ```console + cd scalardb-samples/multi-storage-transaction-sample/ + ``` + + ```console + pwd + ``` + + 次の出力が表示されるはずです。 + + ```console + # pwd + /scalardb-samples/multi-storage-transaction-sample + ``` + +1. Kubernetes クラスター内の MySQL および PostgreSQL にアクセスするための構成ファイル (`database.properties`) を作成します。 + + ```console + cat << 'EOF' > database.properties + scalar.db.storage=multi-storage + scalar.db.multi_storage.storages=storage0,storage1 + + # Storage 0 + scalar.db.multi_storage.storages.storage0.storage=jdbc + scalar.db.multi_storage.storages.storage0.contact_points=jdbc:mysql://mysql-scalardb.default.svc.cluster.local:3306/ + scalar.db.multi_storage.storages.storage0.username=root + scalar.db.multi_storage.storages.storage0.password=mysql + + # Storage 1 + scalar.db.multi_storage.storages.storage1.storage=jdbc + scalar.db.multi_storage.storages.storage1.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.multi_storage.storages.storage1.username=postgres + scalar.db.multi_storage.storages.storage1.password=postgres + + scalar.db.multi_storage.namespace_mapping=customer:storage0,order:storage1 + scalar.db.multi_storage.default_storage=storage1 + EOF + ``` + +1. [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) から Schema Loader をダウンロードします。 + + ```console + curl -OL https://github.com/scalar-labs/scalardb/releases/download/v${SCALARDB_VERSION}/scalardb-schema-loader-${SCALARDB_VERSION}.jar + ``` + +1. Schema Loader を実行してサンプルテーブルを作成します。 + + ```console + java -jar scalardb-schema-loader-${SCALARDB_VERSION}.jar --config database.properties --schema-file schema.json --coordinator + ``` + +1. サンプルワークロードの初期データをロードします。 + + ```console + ./gradlew run --args="LoadInitialData" + ``` + +1. OLTP トランザクションのサンプルワークロードを実行します。これらのコマンドを実行すると、サンプルデータとしていくつかの `order` エントリが作成されます。 + + ```console + ./gradlew run --args="PlaceOrder 1 1:3,2:2" + ``` + + ```console + ./gradlew run --args="PlaceOrder 1 5:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 2 3:1,4:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 2 2:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 3 1:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 3 2:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 3 3:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 3 5:1" + ``` + + +1. OLTPクライアントを終了します。 + + ```console + exit + ``` + +## ステップ6. ScalarDB Analytics with PostgreSQL のデプロイ + +バックエンドデータベースにScalarDB経由でサンプルデータを作成した後、ScalarDB Analytics with PostgreSQL をデプロイします。 + +1. ScalarDB Analytics with PostgreSQL のカスタム値ファイル (`scalardb-analytics-postgresql-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ~/scalardb-analytics-postgresql-test/scalardb-analytics-postgresql-custom-values.yaml + scalardbAnalyticsPostgreSQL: + databaseProperties: | + scalar.db.storage=multi-storage + scalar.db.multi_storage.storages=storage0,storage1 + + # Storage 0 + scalar.db.multi_storage.storages.storage0.storage=jdbc + scalar.db.multi_storage.storages.storage0.contact_points=jdbc:mysql://mysql-scalardb.default.svc.cluster.local:3306/ + scalar.db.multi_storage.storages.storage0.username=root + scalar.db.multi_storage.storages.storage0.password=mysql + + # Storage 1 + scalar.db.multi_storage.storages.storage1.storage=jdbc + scalar.db.multi_storage.storages.storage1.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.multi_storage.storages.storage1.username=postgres + scalar.db.multi_storage.storages.storage1.password=postgres + + scalar.db.multi_storage.namespace_mapping=customer:storage0,order:storage1 + scalar.db.multi_storage.default_storage=storage1 + schemaImporter: + namespaces: + - customer + - order + EOF + ``` + +1. PostgreSQL のスーパーユーザーパスワードを設定するためのシークレットリソースを作成します。 + + ```console + kubectl create secret generic scalardb-analytics-postgresql-superuser-password --from-literal=superuser-password=scalardb-analytics + ``` + +1. ScalarDB Analytics with PostgreSQL を導入します。 + + ```console + helm install scalardb-analytics-postgresql scalar-labs/scalardb-analytics-postgresql -n default -f ~/scalardb-analytics-postgresql-test/scalardb-analytics-postgresql-custom-values.yaml --version ${CHART_VERSION} + ``` + +## ステップ7. OLAP クライアントポッドを実行する + +ScalarDB Analytics with PostgreSQL を介して一部のクエリを実行するには、OLAP クライアントポッドを実行します。 + +1. Kubernetes クラスターで OLAP クライアントポッドを開始します。 + + ```console + kubectl run olap-client --image postgres:latest -- sleep inf + ``` + +1. OLAP クライアントポッドが実行されているかどうかを確認します。 + + ```console + kubectl get pod olap-client + ``` + + 次の出力が表示されるはずです。 + + ```console + kubectl get pod olap-client + ``` + + 次のような結果が表示されます: + + ```console + NAME READY STATUS RESTARTS AGE + olap-client 1/1 Running 0 10s + ``` + +## ステップ8. ScalarDB Analytics with PostgreSQL を介してサンプルクエリを実行する + +OLAP クライアントポッドを実行した後、ScalarDB Analytics with PostgreSQL を介していくつかのクエリを実行できます。 + +1. OLAP クライアントポッドで bash を実行します。 + + ```console + kubectl exec -it olap-client -- bash + ``` + + この手順の後、OLAP クライアントポッドで各コマンドを実行します。 + +1. psqlコマンドを実行して ScalarDB Analytics with PostgreSQL にアクセスします。 + + ```console + psql -h scalardb-analytics-postgresql -p 5432 -U postgres -d scalardb + ``` + + パスワードは `scalardb-analytics` です。 + +1. `customer.customers` テーブルのサンプルデータを読み取ります。 + + ```sql + SELECT * FROM customer.customers; + ``` + + 次の出力が表示されるはずです。 + + ```sql + customer_id | name | credit_limit | credit_total + -------------+---------------+--------------+-------------- + 1 | Yamada Taro | 10000 | 10000 + 2 | Yamada Hanako | 10000 | 9500 + 3 | Suzuki Ichiro | 10000 | 8500 + (3 rows) + ``` + +1. `order.orders` テーブルのサンプルデータを読み取ります。 + + ```sql + SELECT * FROM "order".orders; + ``` + + 次の出力が表示されるはずです。 + + ```sql + scalardb=# SELECT * FROM "order".orders; + customer_id | timestamp | order_id + -------------+---------------+-------------------------------------- + 1 | 1700124015601 | 5ae2a41b-990d-4a16-9700-39355e29adf8 + 1 | 1700124021273 | f3f23d93-3862-48be-8a57-8368b7c8689e + 2 | 1700124028182 | 696a895a-8998-4c3b-b112-4d5763bfcfd8 + 2 | 1700124036158 | 9215d63a-a9a2-4471-a990-45897f091ca5 + 3 | 1700124043744 | 9be70cd4-4f93-4753-9d89-68e250b2ac51 + 3 | 1700124051162 | 4e8ce2d2-488c-40d6-aa52-d9ecabfc68a8 + 3 | 1700124058096 | 658b6682-2819-41f2-91ee-2802a1f02857 + 3 | 1700124071240 | 4e2f94f4-53ec-4570-af98-7c648d8ed80f + (8 rows) + ``` + +1. `order.statements` テーブルのサンプルデータを読み取ります。 + + ```sql + SELECT * FROM "order".statements; + ``` + + 次の出力が表示されるはずです。 + + ```sql + scalardb=# SELECT * FROM "order".statements; + order_id | item_id | count + --------------------------------------+---------+------- + 5ae2a41b-990d-4a16-9700-39355e29adf8 | 2 | 2 + 5ae2a41b-990d-4a16-9700-39355e29adf8 | 1 | 3 + f3f23d93-3862-48be-8a57-8368b7c8689e | 5 | 1 + 696a895a-8998-4c3b-b112-4d5763bfcfd8 | 4 | 1 + 696a895a-8998-4c3b-b112-4d5763bfcfd8 | 3 | 1 + 9215d63a-a9a2-4471-a990-45897f091ca5 | 2 | 1 + 9be70cd4-4f93-4753-9d89-68e250b2ac51 | 1 | 1 + 4e8ce2d2-488c-40d6-aa52-d9ecabfc68a8 | 2 | 1 + 658b6682-2819-41f2-91ee-2802a1f02857 | 3 | 1 + 4e2f94f4-53ec-4570-af98-7c648d8ed80f | 5 | 1 + (10 rows) + ``` + +1. `order.items` テーブルのサンプルデータを読み取ります。 + + ```sql + SELECT * FROM "order".items; + ``` + + 次の出力が表示されるはずです。 + + ```sql + scalardb=# SELECT * FROM "order".items; + item_id | name | price + ---------+--------+------- + 5 | Melon | 3000 + 2 | Orange | 2000 + 4 | Mango | 5000 + 1 | Apple | 1000 + 3 | Grape | 2500 + (5 rows) + ``` + +1. `JOIN` クエリを実行します。例えば以下のように各ユーザーのクレジット残高情報を確認できます。 + + ```sql + SELECT * FROM ( + SELECT c.name, c.credit_limit - c.credit_total AS remaining, array_agg(i.name) OVER (PARTITION BY c.name) AS items + FROM "order".orders o + JOIN customer.customers c ON o.customer_id = c.customer_id + JOIN "order".statements s ON o.order_id = s.order_id + JOIN "order".items i ON s.item_id = i.item_id + ) AS remaining_info GROUP BY name, remaining, items; + ``` + + 次の出力が表示されるはずです。 + + ```sql + scalardb=# SELECT * FROM ( + scalardb(# SELECT c.name, c.credit_limit - c.credit_total AS remaining, array_agg(i.name) OVER (PARTITION BY c.name) AS items + scalardb(# FROM "order".orders o + scalardb(# JOIN customer.customers c ON o.customer_id = c.customer_id + scalardb(# JOIN "order".statements s ON o.order_id = s.order_id + scalardb(# JOIN "order".items i ON s.item_id = i.item_id + scalardb(# ) AS remaining_info GROUP BY name, remaining, items; + name | remaining | items + ---------------+-----------+---------------------------- + Suzuki Ichiro | 1500 | {Grape,Orange,Apple,Melon} + Yamada Hanako | 500 | {Orange,Grape,Mango} + Yamada Taro | 0 | {Orange,Melon,Apple} + (3 rows) + ``` + +1. psql コマンドを終了します。 + + ```console + \q + ``` + +1. OLAP クライアントポッドを終了します。 + + ```console + exit + ``` + +## ステップ9. すべてのリソースを削除する + +Kubernetes クラスターで ScalarDB Analytics with PostgreSQL テストを完了したら、すべてのリソースを削除します。 + +1. MySQL、PostgreSQL、および ScalarDB Analytics with PostgreSQL をアンインストールします。 + + ```console + helm uninstall mysql-scalardb postgresql-scalardb scalardb-analytics-postgresql + ``` + +1. クライアントポッドを削除します。 + + ```console + kubectl delete pod oltp-client olap-client --grace-period 0 + ``` + +1. シークレットリソースを削除します。 + + ```console + kubectl delete secrets scalardb-analytics-postgresql-superuser-password + ``` + +1. 作業ディレクトリとサンプルファイルを削除します。 + + ```console + cd ~ + ``` + + ```console + rm -rf ~/scalardb-analytics-postgresql-test/ + ``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls-cert-manager.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls-cert-manager.mdx new file mode 100644 index 00000000..988ef514 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls-cert-manager.mdx @@ -0,0 +1,596 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Helm Chart をはじめよう (cert-manager を使用した TLS 対応 ScalarDB Cluster) + +このチュートリアルでは、テスト環境の Kubernetes クラスターで Helm Charts と cert-manager を使用して、TLS 構成の ScalarDB Cluster を開始する方法について説明します。開始する前に、テスト用の Mac または Linux 環境がすでに用意されている必要があります。また、このチュートリアルでは **minikube** の使用について説明していますが、説明されている手順はどの Kubernetes クラスターでも機能するはずです。 + +## 要件 + +* ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) が必要です。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。 +* TLS をサポートする ScalarDB Cluster 3.12以降を使用する必要があります。 + +## 作成するもの + +このチュートリアルでは、次の方法で Kubernetes クラスターに次のコンポーネントをデプロイします。 + +``` ++----------------------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +------------------------+ | +| +---> | Envoy | ---+ +---> | ScalarDB Cluster node | ---+ | +| [Pod] | +-------+ | | +------------------------+ | | +| | | | | | +| +-----------+ +---------+ | +-------+ | +--------------------+ | +------------------------+ | +---------------+ | +| | Client | ---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | ScalarDB Cluster node | ---+---> | PostgreSQL | | +| | (SQL CLI) | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | +------------------------+ | | (For Ledger) | | +| +-----------+ +---------+ | | +--------------------+ | | +---------------+ | +| | +-------+ | | +------------------------+ | | +| +---> | Envoy | ---+ +---> | ScalarDB Cluster node | ---+ | +| +-------+ +------------------------+ | +| | +| +----------------------------------------------------------------------------------+ +---------------------+ | +| | cert-manager (create private key and certificate for Envoy and ScalarDB Cluster) | | Issuer (Private CA) | | +| +----------------------------------------------------------------------------------+ +---------------------+ | +| | ++----------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +cert-manager は、TLS 接続用に次の秘密鍵と証明書ファイルを自動的に作成します。 + +``` + +----------------------+ + +---> | For Scalar Envoy | + | +----------------------+ + | | tls.key | + | | tls.crt | ++-------------------------+ | +----------------------+ +| Issuer (Self-signed CA) | ---(Sign certificates)---+ ++-------------------------+ | +----------------------+ +| tls.key | +---> | For ScalarDB Cluster | +| tls.crt | +----------------------+ +| ca.crt | | tls.key | ++-------------------------+ | tls.crt | + +----------------------+ +``` + +Scalar Helm Charts は、Envoy および ScalarDB Cluster の各秘密鍵と証明書ファイルを次のように自動的にマウントし、各接続で TLS を有効にします。ルート CA 証明書ファイルはクライアントに手動でマウントします。 + +``` ++-------------------------------------+ +------------------------------------------------+ +--------------------------------+ +| Client | ---(CRUD/SQL requests)---> | Envoy for ScalarDB Cluster | ---> | ScalarDB Cluster nodes | ++-------------------------------------+ +------------------------------------------------+ +--------------------------------+ +| ca.crt (to verify tls.crt of Envoy) | | tls.key | | tls.key | ++-------------------------------------+ | tls.crt | | tls.crt | + | ca.crt (to verify tls.crt of ScalarDB Cluster) | | ca.crt (to check health) | + +------------------------------------------------+ +--------------------------------+ +``` + +ScalarDB Cluster 関連コンポーネント間には、次の接続が存在します。 + +* **`クライアント - ScalarDB Cluster の Envoy`:** CRUD API または SQL API 関数を実行すると、クライアントは ScalarDB Cluster の Envoy にアクセスします。 +* **`ScalarDB Cluster の Envoy - ScalarDB Cluster`:** Envoy は ScalarDB Cluster の前で L7 (gRPC) ロードバランサーとして機能します。 +* **`ScalarDB Cluster ノード - ScalarDB Cluster ノード`:** ScalarDB Cluster ノードは他の ScalarDB Cluster ノードにアクセスします。つまり、クラスターの内部通信はすべての ScalarDB Cluster ノード間で行われます。 + +## ステップ1. Kubernetesクラスターを起動してツールをインストールする + +Kubernetes クラスターを準備し、いくつかのツール (`kubectl`、`helm`、`cfssl`、および `cfssljson`) をインストールする必要があります。インストール方法の詳細については、[Scalar Helm Charts の使用開始](getting-started-scalar-helm-charts.mdx)を参照してください。 + +## ステップ2. PostgreSQLコンテナを起動する + +ScalarDB Cluster では、バックエンドデータベースとして何らかのデータベースシステムを使用する必要があります。このチュートリアルでは、PostgreSQL を使用します。 + +次のようにして Kubernetes クラスターに PostgreSQL をデプロイできます。 + +1. Bitnami helm リポジトリを追加します。 + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. ScalarDB Cluster 用に PostgreSQL をデプロイします。 + + ```console + helm install postgresql-scalardb-cluster bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. PostgreSQL コンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 34s + ``` + +## ステップ3. 作業ディレクトリを作成する + +ローカルにいくつかの設定ファイルを作成します。必ずそれらのファイル用の作業ディレクトリを作成してください。 + +1. 作業ディレクトリを作成します。 + + ```console + mkdir -p ${HOME}/scalardb-cluster-test/ + ``` + +## ステップ4. cert-manager と issuer リソースをデプロイする + +このチュートリアルでは、cert-manager を使用して秘密鍵と証明書を発行および管理します。次のようにして、Kubernetes クラスターに cert-manager をデプロイできます。 + +1. Jetstack helm リポジトリを追加します。 + + ```console + helm repo add jetstack https://charts.jetstack.io + ``` + +1. cert-manager をデプロイします。 + + ```console + helm install cert-manager jetstack/cert-manager \ + --create-namespace \ + --set installCRDs=true \ + -n cert-manager + ``` + +1. cert-manager コンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod -n cert-manager + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + cert-manager-6dc66985d4-6lvtt 1/1 Running 0 26s + cert-manager-cainjector-c7d4dbdd9-xlrpn 1/1 Running 0 26s + cert-manager-webhook-847d7676c9-ckcz2 1/1 Running 0 26s + ``` + +1. 作業ディレクトリを `${HOME}/scalardb-cluster-test/` に変更します。 + + ```console + cd ${HOME}/scalardb-cluster-test/ + ``` + +1. プライベート CA のカスタム値ファイル (`private-ca-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/private-ca-custom-values.yaml + apiVersion: cert-manager.io/v1 + kind: Issuer + metadata: + name: self-signed-issuer + spec: + selfSigned: {} + --- + apiVersion: cert-manager.io/v1 + kind: Certificate + metadata: + name: self-signed-ca-cert + spec: + isCA: true + commonName: self-signed-ca + secretName: self-signed-ca-cert-secret + privateKey: + algorithm: ECDSA + size: 256 + issuerRef: + name: self-signed-issuer + kind: Issuer + group: cert-manager.io + --- + apiVersion: cert-manager.io/v1 + kind: Issuer + metadata: + name: self-signed-ca + spec: + ca: + secretName: self-signed-ca-cert-secret + EOF + ``` + +1. 自己署名 CA を展開します。 + + ```console + kubectl apply -f ./private-ca-custom-values.yaml + ``` + +1. 発行者リソースが `True` であるかどうかを確認します。 + + ```console + kubectl get issuer + ``` + + [コマンド実行結果] + + ```console + NAME READY AGE + self-signed-ca True 6s + self-signed-issuer True 6s + ``` + +## ステップ5. Helm Charts を使用して Kubernetes クラスターに ScalarDB Cluster をデプロイする + +1. Scalar Helm Charts リポジトリを追加します。 + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. ライセンスキーと証明書を環境変数として設定します。ライセンスキーがない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。`` の値の詳細については、[製品ライセンスキーを構成する方法](https://scalardb.scalar-labs.com/docs/latest/scalar-licensing/)を参照してください。 + + ```console + SCALAR_DB_CLUSTER_LICENSE_KEY='' + SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM='' + ``` + +1. ScalarDB Cluster のカスタム値ファイル (`scalardb-cluster-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/scalardb-cluster-custom-values.yaml + envoy: + + enabled: true + + tls: + downstream: + enabled: true + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - envoy.scalar.example.com + upstream: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" + + scalardbCluster: + + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium" + + scalardbClusterNodeProperties: | + ### Necessary configurations for deployment on Kuberetes + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} + + ### Storage configurations + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb-cluster.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DB_CLUSTER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DB_CLUSTER_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + + ### SQL configurations + scalar.db.sql.enabled=true + + ### Auth configurations + scalar.db.cluster.auth.enabled=true + scalar.db.cross_partition_scan.enabled=true + + ### TLS configurations + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/tls/scalardb-cluster/certs/ca.crt + scalar.db.cluster.node.tls.cert_chain_path=/tls/scalardb-cluster/certs/tls.crt + scalar.db.cluster.node.tls.private_key_path=/tls/scalardb-cluster/certs/tls.key + scalar.db.cluster.tls.override_authority=cluster.scalardb.example.com + + ### License key configurations + scalar.db.cluster.node.licensing.license_key=${env:SCALAR_DB_CLUSTER_LICENSE_KEY} + scalar.db.cluster.node.licensing.license_check_cert_pem=${env:SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - cluster.scalardb.example.com + + secretName: "scalardb-credentials-secret" + EOF + ``` + +1. 資格情報とライセンスキーを含む `scalardb-credentials-secret` という名前のシークレットリソースを作成します。 + + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DB_CLUSTER_LICENSE_KEY="${SCALAR_DB_CLUSTER_LICENSE_KEY}" \ + --from-file=SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. ScalarDB Cluster のチャートバージョンを設定します。 + + ```console + SCALAR_DB_CLUSTER_VERSION=3.12.2 + SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. ScalarDB Cluster をデプロイします。 + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f ${HOME}/scalardb-cluster-test/scalardb-cluster-custom-values.yaml --version ${SCALAR_DB_CLUSTER_CHART_VERSION} -n default + ``` + +1. ScalarDB Cluster ポッドがデプロイされているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 4m30s + scalardb-cluster-envoy-7cc948dfb-4rb8l 1/1 Running 0 18s + scalardb-cluster-envoy-7cc948dfb-hwt96 1/1 Running 0 18s + scalardb-cluster-envoy-7cc948dfb-rzbrx 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-445kj 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-4z54q 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-vcv96 1/1 Running 0 18s + ``` + + ScalarDB Cluster ポッドが適切にデプロイされている場合、それらのポッドの `STATUS` 列には `Running` と表示されます。 + +1. ScalarDB Cluster サービスがデプロイされているかどうかを確認します。 + + ```console + kubectl get svc -n default + ``` + + [コマンド実行結果] + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 7h34m + postgresql-scalardb-cluster ClusterIP 10.96.92.27 5432/TCP 4m52s + postgresql-scalardb-cluster-hl ClusterIP None 5432/TCP 4m52s + scalardb-cluster-envoy ClusterIP 10.96.250.175 60053/TCP 40s + scalardb-cluster-envoy-metrics ClusterIP 10.96.40.197 9001/TCP 40s + scalardb-cluster-headless ClusterIP None 60053/TCP 40s + scalardb-cluster-metrics ClusterIP 10.96.199.135 9080/TCP 40s + ``` + + ScalarDB Cluster サービスが適切にデプロイされている場合は、`CLUSTER-IP` 列にプライベート IP アドレスが表示されます。 + +:::note + +`postgresql-scalardb-cluster-hl` と `scalardb-cluster-headless` の `CLUSTER-IP` 値は、IP アドレスがないため `None` になります。 + +::: + +## ステップ6. クライアントコンテナを起動する + +CA 証明書ファイルはクライアントコンテナーで使用します。そのため、シークレットリソースを作成し、それをクライアントコンテナーにマウントする必要があります。 + +1. `client-ca-cert` という名前のシークレットリソースを作成します。 + + ```console + kubectl create secret generic client-ca-cert --from-file=ca.crt=<(kubectl get secret self-signed-ca-cert-secret -o "jsonpath={.data['ca\.crt']}" | base64 -d) -n default + ``` + +1. クライアントポッドのマニフェストファイル (`scalardb-cluster-client-pod.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml + apiVersion: v1 + kind: Pod + metadata: + name: "scalardb-cluster-client" + spec: + containers: + - name: scalardb-cluster-client + image: eclipse-temurin:8-jre-jammy + command: ['sleep'] + args: ['inf'] + env: + - name: SCALAR_DB_CLUSTER_VERSION + value: SCALAR_DB_CLUSTER_CLIENT_POD_SCALAR_DB_CLUSTER_VERSION + volumeMounts: + - name: "client-ca-cert" + mountPath: "/certs/" + readOnly: true + volumes: + - name: "client-ca-cert" + secret: + secretName: "client-ca-cert" + restartPolicy: Never + EOF + ``` + +1. マニフェストファイルで ScalarDB Cluster のバージョンを設定します。 + + ```console + sed -i s/SCALAR_DB_CLUSTER_CLIENT_POD_SCALAR_DB_CLUSTER_VERSION/${SCALAR_DB_CLUSTER_VERSION}/ ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml + ``` + +1. クライアントポッドをデプロイします。 + + ```console + kubectl apply -f ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml -n default + ``` + +1. クライアントコンテナーが実行されているかどうかを確認します。 + + ```console + kubectl get pod scalardb-cluster-client -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + scalardb-cluster-client 1/1 Running 0 26s + ``` + +## ステップ7. クライアントコンテナで ScalarDB Cluster SQL CLI を実行する + +1. クライアントコンテナーで bash を実行します。 + + ```console + kubectl exec -it scalardb-cluster-client -n default -- bash + ``` + + 次の手順のコマンドは、クライアントコンテナーで実行する必要があります。 + +1. [リリース](https://github.com/scalar-labs/scalardb/releases)から ScalarDB Cluster SQL CLI をダウンロードします。 + + ```console + curl -OL https://github.com/scalar-labs/scalardb/releases/download/v${SCALAR_DB_CLUSTER_VERSION}/scalardb-cluster-sql-cli-${SCALAR_DB_CLUSTER_VERSION}-all.jar + ``` + +1. `database.properties` ファイルを作成し、設定を追加します。 + + ```console + cat << 'EOF' > /database.properties + # ScalarDB Cluster configurations + scalar.db.sql.connection_mode=cluster + scalar.db.sql.cluster_mode.contact_points=indirect:scalardb-cluster-envoy.default.svc.cluster.local + + # Auth configurations + scalar.db.cluster.auth.enabled=true + scalar.db.sql.cluster_mode.username=admin + scalar.db.sql.cluster_mode.password=admin + + # TLS configurations + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/certs/ca.crt + scalar.db.cluster.tls.override_authority=envoy.scalar.example.com + EOF + ``` + +1. ScalarDB Cluster SQL CLI を実行します。 + + ```console + java -jar /scalardb-cluster-sql-cli-${SCALAR_DB_CLUSTER_VERSION}-all.jar --config /database.properties + ``` + +1. `ns` という名前のサンプル名前空間を作成します。 + + ```sql + CREATE NAMESPACE ns; + ``` + +1. 名前空間 `ns` の下に `tbl` という名前のサンプルテーブルを作成します。 + + ```sql + CREATE TABLE ns.tbl (a INT, b INT, c INT, PRIMARY KEY(a, b)); + ``` + +1. サンプルレコードを挿入します。 + + ```sql + INSERT INTO ns.tbl VALUES (1,2,3), (4,5,6), (7,8,9); + ``` + +1. 挿入したサンプルレコードを選択します。 + + ```sql + SELECT * FROM ns.tbl; + ``` + + [コマンド実行結果] + + ```sql + 0: scalardb> SELECT * FROM ns.tbl; + +---+---+---+ + | a | b | c | + +---+---+---+ + | 7 | 8 | 9 | + | 1 | 2 | 3 | + | 4 | 5 | 6 | + +---+---+---+ + 3 rows selected (0.059 seconds) + ``` + +1. ScalarDB Cluster SQL CLI を終了するには、`Ctrl + D` を押します。 + + ```console + ^D + ``` + +1. クライアントコンテナーを終了します。 + + ```console + exit + ``` + +## ステップ8. すべてのリソースを削除する + +Kubernetes クラスターで ScalarDB Cluster テストを完了したら、すべてのリソースを削除します。 + +1. ScalarDB Cluster と PostgreSQL をアンインストールします。 + + ```console + helm uninstall -n default scalardb-cluster postgresql-scalardb-cluster + ``` + +1. 自己署名 CA を削除します。 + + ``` + kubectl delete -f ./private-ca-custom-values.yaml + ``` + +1. cert-manager をアンインストールします。 + + ```console + helm uninstall -n cert-manager cert-manager + ``` + +1. クライアントコンテナを削除します。 + + ``` + kubectl delete pod scalardb-cluster-client --grace-period 0 -n default + ``` + +1. シークレットリソースを削除します。 + + ``` + kubectl delete secrets scalardb-credentials-secret self-signed-ca-cert-secret scalardb-cluster-envoy-tls-cert scalardb-cluster-tls-cert client-ca-cert + ``` + +1. ネームスペース `cert-manager` を削除します。 + + ``` + kubectl delete ns cert-manager + ``` + +1. 作業ディレクトリとサンプル構成ファイルを削除します。 + + ```console + cd ${HOME} + ``` + + ```console + rm -rf ${HOME}/scalardb-cluster-test/ + ``` + +## 参考文献 + +Scalar 製品の監視またはログ記録を開始する方法については、次のチュートリアルを参照してください。 + +* [Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング)](getting-started-monitoring.mdx) +* [Helm Charts をはじめよう (Loki Stack を使用したログ記録)](getting-started-logging.mdx) +* [Helm Charts をはじめよう (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls.mdx new file mode 100644 index 00000000..52e928be --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls.mdx @@ -0,0 +1,625 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Helm Charts をはじめよう (TLS を使用した ScalarDB Cluster) + +このドキュメントでは、Kubernetes クラスター上の Helm Chart をテスト環境として使用して、TLS 構成で ScalarDB Cluster を開始する方法について説明します。ここでは、テスト用の Mac または Linux 環境がすでにあることを前提としています。このドキュメントでは **minikube** を使用しますが、これから説明する手順はどの Kubernetes クラスターでも機能するはずです。 + +## 要件 + +* ScalarDB Cluster のライセンスキー (トライアルライセンスまたは商用ライセンス) を取得する必要があります。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)してください。 +* TLSをサポートするScalarDB Cluster v3.12以降を使用する必要があります。 + +## 作成するもの + +次のように、次のコンポーネントを Kubernetes クラスターにデプロイします。 + +``` ++----------------------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +------------------------+ | +| +---> | Envoy | ---+ +---> | ScalarDB Cluster node | ---+ | +| [Pod] | +-------+ | | +------------------------+ | | +| | | | | | +| +-----------+ +---------+ | +-------+ | +--------------------+ | +------------------------+ | +---------------+ | +| | Client | ---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | ScalarDB Cluster node | ---+---> | PostgreSQL | | +| | (SQL CLI) | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | +------------------------+ | | (For Ledger) | | +| +-----------+ +---------+ | | +--------------------+ | | +---------------+ | +| | +-------+ | | +------------------------+ | | +| +---> | Envoy | ---+ +---> | ScalarDB Cluster node | ---+ | +| +-------+ +------------------------+ | +| | ++----------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +TLS 接続用に次の秘密鍵ファイルと証明書ファイルを作成します。 + +``` + +-------------------------------+ + +---> | For Scalar Envoy | + | +-------------------------------+ + | | envoy-key.pem | + | | envoy.pem | ++----------------------+ | +-------------------------------+ +| Self-signed CA | ---(Sign certificates)---+ ++----------------------+ | +-------------------------------+ +| ca-key.pem | +---> | For ScalarDB Cluster | +| ca.pem | +-------------------------------+ ++----------------------+ | scalardb-cluster-key.pem | + | scalardb-cluster.pem | + +-------------------------------+ +``` + +各接続で TLS を有効にするために、各秘密鍵と証明書ファイルを次のように設定します。 + +``` ++--------------------------------+ +-----------------------------------------+ +-----------------------------------------+ +| Client | ---(CRUD/SQL requests)---> | Envoy for ScalarDB Cluster | ---> | ScalarDB Cluster nodes | ++--------------------------------+ +-----------------------------------------+ +-----------------------------------------+ +| ca.pem (to verify envoy.pem) | | envoy-key.pem | | scalardb-cluster-key.pem | ++--------------------------------+ | envoy.pem | | scalardb-cluster.pem | + | ca.pem (to verify scalardb-cluster.pem) | | ca.pem (used for health check) | + +-----------------------------------------+ +-----------------------------------------+ +``` + +ScalarDB Cluster 関連コンポーネント間には、次の接続があります。 + +* **`クライアント - ScalarDB Cluster の Envoy`:** 一部のCRUD APIやSQL APIを実行すると、クライアントはEnvoy for ScalarDB Clusterにアクセスします。 +* **`ScalarDB Cluster の Envoy - ScalarDB Cluster`:** Envoy は、ScalarDB Cluster の前の L7 (gRPC) ロードバランサーとして機能します。 +* **`ScalarDB Cluster ノード - ScalarDB Cluster ノード`:** ScalarDB Cluster ノードから別の ScalarDB Cluster ノードにアクセスします。言い換えれば、すべての ScalarDB Cluster ノード間でクラスターの内部通信が行われます。 + +## ステップ1. Kubernetes クラスターを開始する + +Kubernetes クラスターを準備し、いくつかのツール (`kubectl`、`helm`、`cfssl`、および `cfssljson`) をインストールする必要があります。インストール方法の詳細については、[Scalar Helm Charts をはじめよう](getting-started-scalar-helm-charts.mdx)を参照してください。 + +## ステップ2. PostgreSQL コンテナーを開始する + +ScalarDB Cluster は、バックエンドデータベースとして何らかのデータベースシステムを使用する必要があります。このチュートリアルでは、PostgreSQL を使用します。 + +次のようにして、Kubernetes クラスターに PostgreSQL をデプロイできます。 + +1. Bitnami Helm リポジトリを追加します。 + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. ScalarDB Cluster 用の PostgreSQL をデプロイします。 + + ```console + helm install postgresql-scalardb-cluster bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. PostgreSQL コンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 34s + ``` + +## ステップ3. 作業ディレクトリを作成する + +いくつかの構成ファイルと秘密鍵および証明書ファイルをローカルに作成します。したがって、それらの作業ディレクトリを作成します。 + +1. 作業ディレクトリを作成します。 + + ```console + mkdir -p ${HOME}/scalardb-cluster-test/certs/ + ``` + +## ステップ4. 秘密鍵および証明書ファイルを作成する + +秘密鍵と証明書ファイルを作成します。 + +1. 作業ディレクトリを `${HOME}/scalardb-cluster-test/certs/` ディレクトリに変更します。 + + ```console + cd ${HOME}/scalardb-cluster-test/certs/ + ``` + +1. CA の情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/certs/ca.json + { + "CN": "scalar-test-ca", + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Test CA" + } + ] + } + EOF + ``` + +1. CA の秘密鍵/証明書ファイルを作成します。 + + ```console + cfssl gencert -initca ca.json | cfssljson -bare ca + ``` + +1. CA 構成を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/certs/ca-config.json + { + "signing": { + "default": { + "expiry": "87600h" + }, + "profiles": { + "scalar-test-ca": { + "expiry": "87600h", + "usages": [ + "signing", + "key encipherment", + "server auth" + ] + } + } + } + } + EOF + ``` + +1. Envoy 情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/certs/envoy.json + { + "CN": "scalar-envoy", + "hosts": [ + "envoy.scalar.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Envoy Test" + } + ] + } + EOF + ``` + +1. ScalarDB Cluster 情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/certs/scalardb-cluster.json + { + "CN": "scalardb-cluster", + "hosts": [ + "cluster.scalardb.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "ScalarDB Cluster Test" + } + ] + } + EOF + ``` + +1. Envoy の秘密鍵および証明書ファイルを作成します。 + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca envoy.json | cfssljson -bare envoy + ``` + +1. ScalarDB Cluster の秘密鍵および証明書ファイルを作成します。 + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca scalardb-cluster.json | cfssljson -bare scalardb-cluster + ``` + +1. 秘密鍵および証明書ファイルが作成されたことを確認します。 + + ```console + ls -1 + ``` + + [コマンド実行結果] + + ```console + ca-config.json + ca-key.pem + ca.csr + ca.json + ca.pem + envoy-key.pem + envoy.csr + envoy.json + envoy.pem + scalardb-cluster-key.pem + scalardb-cluster.csr + scalardb-cluster.json + scalardb-cluster.pem + ``` + +## ステップ5. Helm Charts を使用して Kubernetes クラスターに ScalarDB Cluster をデプロイする + +1. Scalar helm リポジトリを追加します。 + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. ScalarDB Cluster のカスタム値ファイル (`scalardb-cluster-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/scalardb-cluster-custom-values.yaml + envoy: + + enabled: true + + tls: + downstream: + enabled: true + certChainSecret: "envoy-tls-cert" + privateKeySecret: "envoy-tls-key" + upstream: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" + caRootCertSecret: "scalardb-cluster-tls-ca" + + scalardbCluster: + + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium" + + scalardbClusterNodeProperties: | + ### Necessary configurations for deployment on Kuberetes + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} + + ### Storage configurations + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb-cluster.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DB_CLUSTER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DB_CLUSTER_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + + ### SQL configurations + scalar.db.sql.enabled=true + + ### Auth configurations + scalar.db.cluster.auth.enabled=true + scalar.db.cross_partition_scan.enabled=true + + ### TLS configurations + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/tls/scalardb-cluster/certs/ca.crt + scalar.db.cluster.node.tls.cert_chain_path=/tls/scalardb-cluster/certs/tls.crt + scalar.db.cluster.node.tls.private_key_path=/tls/scalardb-cluster/certs/tls.key + scalar.db.cluster.tls.override_authority=cluster.scalardb.example.com + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DB_CLUSTER_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" + caRootCertSecret: "scalardb-cluster-tls-ca" + certChainSecret: "scalardb-cluster-tls-cert" + privateKeySecret: "scalardb-cluster-tls-key" + + secretName: "scalardb-credentials-secret" + EOF + ``` + +1. ライセンスキーと証明書を環境変数に設定します。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)してください。 + + ```console + SCALAR_DB_CLUSTER_LICENSE_KEY= + SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM= + ``` + +1. 資格情報とライセンスキーを含むシークレットリソース「scalardb-credentials-secret」を作成します。 + + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DB_CLUSTER_LICENSE_KEY=${SCALAR_DB_CLUSTER_LICENSE_KEY} \ + --from-literal=SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM=${SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} \ + -n default + ``` + +1. Envoy の秘密鍵ファイルと証明書ファイルを含むシークレットリソースを作成します。 + + ```console + kubectl create secret generic envoy-tls-cert --from-file=tls.crt=${HOME}/scalardb-cluster-test/certs/envoy.pem -n default + kubectl create secret generic envoy-tls-key --from-file=tls.key=${HOME}/scalardb-cluster-test/certs/envoy-key.pem -n default + ``` + +1. ScalarDB Cluster の秘密鍵、証明書、CA 証明書ファイルを含むシークレットリソースを作成します。 + + ```console + kubectl create secret generic scalardb-cluster-tls-ca --from-file=ca.crt=${HOME}/scalardb-cluster-test/certs/ca.pem -n default + kubectl create secret generic scalardb-cluster-tls-cert --from-file=tls.crt=${HOME}/scalardb-cluster-test/certs/scalardb-cluster.pem -n default + kubectl create secret generic scalardb-cluster-tls-key --from-file=tls.key=${HOME}/scalardb-cluster-test/certs/scalardb-cluster-key.pem -n default + ``` + +1. ScalarDB Cluster のチャートのバージョンを設定します。 + + ```console + SCALAR_DB_CLUSTER_VERSION=3.12.2 + SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. ScalarDB Cluster をデプロイします。 + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f ${HOME}/scalardb-cluster-test/scalardb-cluster-custom-values.yaml --version ${SCALAR_DB_CLUSTER_CHART_VERSION} -n default + ``` + +1. ScalarDB Cluster ポッドがデプロイされているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 4m30s + scalardb-cluster-envoy-7cc948dfb-4rb8l 1/1 Running 0 18s + scalardb-cluster-envoy-7cc948dfb-hwt96 1/1 Running 0 18s + scalardb-cluster-envoy-7cc948dfb-rzbrx 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-445kj 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-4z54q 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-vcv96 1/1 Running 0 18s + ``` + ScalarDB Cluster ポッドが適切にデプロイされている場合は、ステータスが **実行中** であることがわかります。 + +1. ScalarDB Cluster サービスがデプロイされているかどうかを確認します。 + + ```console + kubectl get svc -n default + ``` + + [Command execution result] + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 7h34m + postgresql-scalardb-cluster ClusterIP 10.96.92.27 5432/TCP 4m52s + postgresql-scalardb-cluster-hl ClusterIP None 5432/TCP 4m52s + scalardb-cluster-envoy ClusterIP 10.96.250.175 60053/TCP 40s + scalardb-cluster-envoy-metrics ClusterIP 10.96.40.197 9001/TCP 40s + scalardb-cluster-headless ClusterIP None 60053/TCP 40s + scalardb-cluster-metrics ClusterIP 10.96.199.135 9080/TCP 40s + ``` + ScalarDB Cluster サービスが適切にデプロイされている場合は、CLUSTER-IP 列にプライベート IP アドレスが表示されます。 + +:::note + +`postgresql-scalardb-cluster-hl` と `scalardb-cluster-headless` の `CLUSTER-IP` 値は、IP アドレスがないため `None` になります。 + +::: + +## ステップ6. クライアントコンテナを開始する + +クライアントコンテナでCAの証明書ファイルを使用します。そこで、シークレットリソースを作成し、クライアントコンテナにマウントします。 + +1. シークレットリソース `client-ca-cert` を作成します。 + + ```console + kubectl create secret generic client-ca-cert --from-file=certificate=${HOME}/scalardb-cluster-test/certs/ca.pem -n default + ``` + +1. クライアントポッドのマニフェストファイル (`scalardb-cluster-client-pod.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml + apiVersion: v1 + kind: Pod + metadata: + name: "scalardb-cluster-client" + spec: + containers: + - name: scalardb-cluster-client + image: eclipse-temurin:8-jre-jammy + command: ['sleep'] + args: ['inf'] + env: + - name: SCALAR_DB_CLUSTER_VERSION + value: SCALAR_DB_CLUSTER_CLIENT_POD_SCALAR_DB_CLUSTER_VERSION + volumeMounts: + - name: "client-ca-cert" + mountPath: "/certs/ca/ca.pem" + subPath: certificate + readOnly: true + volumes: + - name: "client-ca-cert" + secret: + secretName: "client-ca-cert" + restartPolicy: Never + EOF + ``` + +1. マニフェストファイルで ScalarDB Cluster のバージョンを設定します。 + + ```console + sed -i s/SCALAR_DB_CLUSTER_CLIENT_POD_SCALAR_DB_CLUSTER_VERSION/${SCALAR_DB_CLUSTER_VERSION}/ ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml + ``` + +1. クライアントポッドをデプロイします。 + + ```console + kubectl apply -f ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml -n default + ``` + +1. クライアントコンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod scalardb-cluster-client -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + scalardb-cluster-client 1/1 Running 0 26s + ``` + +## ステップ7. ScalarDB Cluster SQL CLI をダウンロードしてクライアントコンテナにコピーします + +1. ScalarDB Cluster SQL CLI を [リリース](https://github.com/scalar-labs/scalardb/releases)からディレクトリ `${HOME}/scalardb-cluster-test/` の下にダウンロードします。 + +1. ScalarDB Cluster SQL CLI をクライアントコンテナにコピーします。 + + ```console + kubectl cp ${HOME}/scalardb-cluster-test/scalardb-cluster-sql-cli-${SCALAR_DB_CLUSTER_VERSION}-all.jar scalardb-cluster-client:/ + ``` + +## ステップ8. クライアントコンテナで ScalarDB Cluster SQL CLI を実行する + +1. クライアントコンテナで bash を実行します。 + + ```console + kubectl exec -it scalardb-cluster-client -n default -- bash + ``` + 次の手順移行のコマンドは、クライアントコンテナ内で実行する必要があります。 + +1. `database.properties` ファイルを作成します。 + + ```console + cat << 'EOF' > /database.properties + # ScalarDB Cluster configurations + scalar.db.sql.connection_mode=cluster + scalar.db.sql.cluster_mode.contact_points=indirect:scalardb-cluster-envoy.default.svc.cluster.local + + # Auth configurations + scalar.db.cluster.auth.enabled=true + scalar.db.sql.cluster_mode.username=admin + scalar.db.sql.cluster_mode.password=admin + + # TLS configurations + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/certs/ca/ca.pem + scalar.db.cluster.tls.override_authority=envoy.scalar.example.com + EOF + ``` + +1. ScalarDB Cluster SQL CLI を実行します。 + + ```console + java -jar /scalardb-cluster-sql-cli-${SCALAR_DB_CLUSTER_VERSION}-all.jar --config /database.properties + ``` + +1. サンプル名前空間 `ns` を作成します。 + + ```sql + CREATE NAMESPACE ns; + ``` + +1. 名前空間 `ns` の下にサンプルテーブル `tbl` を作成します。 + + ```sql + CREATE TABLE ns.tbl (a INT, b INT, c INT, PRIMARY KEY(a, b)); + ``` + +1. サンプルレコードを挿入します。 + + ```sql + INSERT INTO ns.tbl VALUES (1,2,3), (4,5,6), (7,8,9); + ``` + +1. 挿入したサンプルレコードを選択します。 + + ```sql + SELECT * FROM ns.tbl; + ``` + + [コマンド実行結果] + + ```sql + 0: scalardb> SELECT * FROM ns.tbl; + +---+---+---+ + | a | b | c | + +---+---+---+ + | 7 | 8 | 9 | + | 1 | 2 | 3 | + | 4 | 5 | 6 | + +---+---+---+ + 3 rows selected (0.059 seconds) + ``` + +## ステップ9. すべてのリソースを削除する + +Kubernetes クラスターで ScalarDB Cluster のテストが完了したら、すべてのリソースを削除します。 + +1. ScalarDB Cluster と PostgreSQL をアンインストールします。 + + ```console + helm uninstall -n default scalardb-cluster postgresql-scalardb-cluster + ``` + +1. クライアントコンテナを削除します。 + + ``` + kubectl delete pod scalardb-cluster-client --grace-period 0 -n default + ``` + +1. シークレットリソースを削除します。 + + ``` + kubectl delete secrets scalardb-credentials-secret scalardb-cluster-tls-key scalardb-cluster-tls-cert scalardb-cluster-tls-ca envoy-tls-key envoy-tls-cert client-ca-cert + ``` + +1. 作業ディレクトリとサンプルファイル (構成ファイル、秘密鍵、および証明書) を削除します。 + + ```console + cd ${HOME} + ``` + + ```console + rm -rf ${HOME}/scalardb-cluster-test/ + ``` + +## 参考文献 + +Scalar 製品の監視またはログ記録を開始する方法については、次のドキュメントで説明しています。 + +* [Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング)](getting-started-monitoring.mdx) +* [Helm Charts をはじめよう (Loki スタックを使用したロギング)](getting-started-logging.mdx) +* [Helm Charts をはじめよう (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb.mdx new file mode 100644 index 00000000..3c6ba2c4 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardb.mdx @@ -0,0 +1,387 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsJapanese +--- + +# [非推奨] Helm Charts をはじめよう (ScalarDB Server) + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +:::note + +ScalarDB Server は非推奨になりました。代わりに [ScalarDB Cluster](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart) を使用してください。 + +::: + +このドキュメントでは、Kubernetes クラスター上の Helm Chart をテスト環境として使用して、ScalarDB Server を開始する方法について説明します。ここでは、テスト用の Mac または Linux 環境がすでにあることを前提としています。このドキュメントでは **Minikube** を使用しますが、これから説明する手順はどの Kubernetes クラスターでも機能するはずです。 + +## 要件 + +※コンテナイメージ (`scalardb-server` および `scalardb-envoy`) を取得するには、[AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-rzbuhxgvqf4d2) または [Azure Marketplace](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) で ScalarDB を購読する必要があります。詳細については、以下のドキュメントを参照してください。 + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +## 私たちが作るもの + +次のように、次のコンポーネントを Kubernetes クラスターにデプロイします。 + +``` ++--------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes クラスター] | +| | +| [ポッド] [ポッド] [ポッド] [ポッド] | +| | +| +-------+ +-----------------+ | +| +---> | Envoy | ---+ +---> | ScalarDB Server | ---+ | +| | +-------+ | | +-----------------+ | | +| | | | | | +| +--------+ +---------+ | +-------+ | +-------------------+ | +-----------------+ | +------------+ | +| | クライアント | ---> | サービス | ---+---> | Envoy | ---+---> | サービス | ---+---> | ScalarDB Server | ---+---> | PostgreSQL | | +| +--------+ | (Envoy) | | +-------+ | | (ScalarDB Server) | | +-----------------+ | +------------+ | +| +---------+ | | +-------------------+ | | | +| | +-------+ | | +-----------------+ | | +| +---> | Envoy | ---+ +---> | ScalarDB Server | ---+ | +| +-------+ +-----------------+ | +| | ++--------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ステップ1. Kubernetes クラスターを開始する + +まず、Kubernetes クラスターを準備する必要があります。**minikube** 環境を使用する場合は、[Scalar Helm Charts をはじめよう](getting-started-scalar-helm-charts.mdx)を参照してください。すでに Kubernetes クラスターを開始している場合は、この手順をスキップできます。 + +## ステップ2. PostgreSQL コンテナーを開始する + +ScalarDB は、バックエンドデータベースとして何らかのデータベースシステムを使用します。このドキュメントでは PostgreSQL を使用します。 + +次のようにして、Kubernetes クラスターに PostgreSQL をデプロイできます。 + +1. Bitnami Helm リポジトリを追加します。 + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. PostgreSQLをデプロイします。 + ```console + helm install postgresql-scalardb bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. PostgreSQL コンテナが実行されているかどうかを確認します。 + ```console + kubectl get pod + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-0 1/1 Running 0 2m42s + ``` + +## ステップ3. Helm Charts を使用して Kubernetes クラスターに ScalarDB Server をデプロイする + +1. Scalar helm リポジトリを追加します。 + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. AWS/Azure Marketplace から ScalarDB コンテナーイメージをプルするためのシークレットリソースを作成します。 + * AWS Marketplace + ```console + kubectl create secret docker-registry reg-ecr-mp-secrets \ + --docker-server=709825985650.dkr.ecr.us-east-1.amazonaws.com \ + --docker-username=AWS \ + --docker-password=$(aws ecr get-login-password --region us-east-1) + ``` + * Azure Marketplace + ```console + kubectl create secret docker-registry reg-acr-secrets \ + --docker-server= \ + --docker-username= \ + --docker-password= + ``` + + 詳細については、以下のドキュメントを参照してください。 + + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +1. ScalarDB Server のカスタム値ファイル (scalardb-custom-values.yaml) を作成します。 + * AWS Marketplace + + ```console + cat << 'EOF' > scalardb-custom-values.yaml + envoy: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + + scalardb: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-server" + tag: "3.7.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + databaseProperties: | + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DB_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_POSTGRES_PASSWORD "" }} + secretName: "scalardb-credentials-secret" + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > scalardb-custom-values.yaml + envoy: + image: + repository: "/scalarinc/scalardb-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-acr-secrets" + + scalardb: + image: + repository: "/scalarinc/scalardb-server" + tag: "3.7.0" + imagePullSecrets: + - name: "reg-acr-secrets" + databaseProperties: | + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DB_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_POSTGRES_PASSWORD "" }} + secretName: "scalardb-credentials-secret" + EOF + ``` + +1. PostgreSQL のユーザー名とパスワードを含む Secret リソースを作成します。 + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DB_POSTGRES_PASSWORD=postgres + ``` + +1. ScalarDB Server をデプロイします。 + ```console + helm install scalardb scalar-labs/scalardb -f ./scalardb-custom-values.yaml + ``` + +1. ScalarDB Server ポッドがデプロイされているかどうかを確認します。 + ```console + kubectl get pod + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-0 1/1 Running 0 9m48s + scalardb-765598848b-75csp 1/1 Running 0 6s + scalardb-765598848b-w864f 1/1 Running 0 6s + scalardb-765598848b-x8rqj 1/1 Running 0 6s + scalardb-envoy-84c475f77b-kpz2p 1/1 Running 0 6s + scalardb-envoy-84c475f77b-n74tk 1/1 Running 0 6s + scalardb-envoy-84c475f77b-zbrwz 1/1 Running 0 6s + ``` + ScalarDB Server ポッドが適切にデプロイされている場合、STATUS が **Running** であることがわかります。 + +1. ScalarDB Server サービスがデプロイされているかどうかを確認します。 + ```console + kubectl get svc + ``` + 【コマンド実行結果】 + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-scalardb ClusterIP 10.109.118.122 5432/TCP 10m + postgresql-scalardb-hl ClusterIP None 5432/TCP 10m + scalardb-envoy ClusterIP 10.110.110.250 60051/TCP 41s + scalardb-envoy-metrics ClusterIP 10.107.98.227 9001/TCP 41s + scalardb-headless ClusterIP None 60051/TCP 41s + scalardb-metrics ClusterIP 10.108.188.10 8080/TCP 41s + ``` + ScalarDB Server サービスが適切にデプロイされている場合は、CLUSTER-IP 列にプライベート IP アドレスが表示されます。(注記: `scalardb-headless` には CLUSTER-IP がありません。) + +## ステップ4. クライアントコンテナを開始する + +1. Kubernetes クラスター上でクライアントコンテナーを起動します。 + ```console + kubectl run scalardb-client --image eclipse-temurin:8-jdk --command sleep inf + ``` + +1. クライアントコンテナが実行されているかどうかを確認します。 + ```console + kubectl get pod scalardb-client + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + scalardb-client 1/1 Running 0 23s + ``` + +## ステップ5. クライアントコンテナで ScalarDB サンプルアプリケーションを実行する + +以下に最低限の手順を説明します。ScalarDB についてさらに詳しく知りたい場合は、[Getting Started with ScalarDB](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb) を参照してください。 + +1. クライアントコンテナで bash を実行します。 + ```console + kubectl exec -it scalardb-client -- bash + ``` + この手順の後、クライアントコンテナで各コマンドを実行します。 + +1. git およびcurl コマンドをクライアントコンテナにインストールします。 + ```console + apt update && apt install -y git curl + ``` + +1. ScalarDB git リポジトリのクローンを作成します。 + ```console + git clone https://github.com/scalar-labs/scalardb.git + ``` + +1. ディレクトリを `scalardb/` に変更します。 + ```console + cd scalardb/ + ``` + ```console + pwd + ``` + 【コマンド実行結果】 + ```console + /scalardb + ``` + +1. ブランチを任意のバージョンに変更します。 + ```console + git checkout -b v3.7.0 refs/tags/v3.7.0 + ``` + ```console + git branch + ``` + 【コマンド実行結果】 + + ```console + master + * v3.7.0 + ``` + + 別のバージョンを使用する場合は、使用するバージョン (タグ) を指定してください。 + +1. ディレクトリを `docs/getting-started/` に変更します。 + ```console + cd docs/getting-started/ + ``` + ```console + pwd + ``` + 【コマンド実行結果】 + ```console + /scalardb/docs/getting-started + ``` + +1. [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) から Schema Loader をダウンロードします。 + ```console + curl -OL https://github.com/scalar-labs/scalardb/releases/download/v3.7.0/scalardb-schema-loader-3.7.0.jar + ``` + 同じバージョンの ScalarDB と Schema Loader を使用する必要があります。 + +1. Kubernetes クラスター上の ScalarDB Server にアクセスするための構成ファイル (scalardb.properties) を作成します。 + ```console + cat << 'EOF' > scalardb.properties + scalar.db.contact_points=scalardb-envoy.default.svc.cluster.local + scalar.db.contact_port=60051 + scalar.db.storage=grpc + scalar.db.transaction_manager=grpc + EOF + ``` + +1. サンプルアプリケーションの DB スキーマを定義する JSON ファイル (emoney-transaction.json) を作成します。 + ```console + cat << 'EOF' > emoney-transaction.json + { + "emoney.account": { + "transaction": true, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } + } + EOF + ``` + +1. Schema Loader を実行します (サンプル TABLE を作成します)。 + ```console + java -jar ./scalardb-schema-loader-3.7.0.jar --config ./scalardb.properties -f emoney-transaction.json --coordinator + ``` + +1. サンプルアプリケーションを実行します。 + * `1000` を `user1` に請求します。 + ```console + ./gradlew run --args="-action charge -amount 1000 -to user1" + ``` + * `merchant1` に `0` を請求します (`merchant1` のアカウントを作成するだけです): + ```console + ./gradlew run --args="-action charge -amount 0 -to merchant1" + ``` + * `user1` から `merchant1` に `100` を支払います。 + ```console + ./gradlew run --args="-action pay -amount 100 -from user1 -to merchant1" + ``` + * `user1` の残高を取得します。 + ```console + ./gradlew run --args="-action getBalance -id user1" + ``` + * `merchant1` の残高を取得します。 + ```console + ./gradlew run --args="-action getBalance -id merchant1" + ``` + +1. (オプション) 次のコマンドを使用して、サンプルアプリケーションを通じて挿入および変更された (INSERT/UPDATE) データを確認できます。(このコマンドは、クライアントコンテナではなくローカルホストで実行する必要があります。) + ```console + kubectl exec -it postgresql-scalardb-0 -- bash -c 'export PGPASSWORD=postgres && psql -U postgres -d postgres -c "SELECT * FROM emoney.account"' + ``` + 【コマンド実行結果】 + ```sql + id | balance | tx_id | tx_state | tx_version | tx_prepared_at | tx_committed_at | before_tx_id | before_tx_state | before_tx_version | before_tx_prepared_at | before_tx_committed_at | before_balance + -----------+---------+--------------------------------------+----------+------------+----------------+-----------------+--------------------------------------+-----------------+-------------------+-----------------------+------------------------+---------------- + merchant1 | 100 | 65a90225-0846-4e97-b729-151f76f6ca2f | 3 | 2 | 1667361909634 |1667361909679 | 3633df99-a8ed-4301-a8b9-db1344807d7b | 3 | 1 | 1667361902466 | 1667361902485 | 0 + user1 | 900 | 65a90225-0846-4e97-b729-151f76f6ca2f | 3 | 2 | 1667361909634 |1667361909679 | 5520cba4-625a-4886-b81f-6089bf846d18 | 3 | 1 | 1667361897283 | 1667361897317 | 1000 + (2 rows) + ``` + * 注記: + * 通常はScalarDB経由でデータ (レコード) にアクセスする必要があります。上記のコマンドはサンプルアプリケーションの動作を説明、確認するために使用します。 + +## ステップ6. すべてのリソースを削除する + +Kubernetes クラスター上で ScalarDB Server テストが完了したら、すべてのリソースを削除します。 + +1. ScalarDB Server と PostgreSQL をアンインストールします。 + ```console + helm uninstall scalardb postgresql-scalardb + ``` + +1. クライアントコンテナを削除します。 + ``` + kubectl delete pod scalardb-client --force --grace-period 0 + ``` + +## 参考文献 + +Scalar 製品の監視またはログ記録を開始する方法については、次のドキュメントで説明しています。 + +* [Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング)](getting-started-monitoring.mdx) +* [Helm Charts をはじめよう (Loki スタックを使用したロギング)](getting-started-logging.mdx) +* [Helm Charts をはじめよう (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls-cert-manager.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls-cert-manager.mdx new file mode 100644 index 00000000..28b5f45e --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls-cert-manager.mdx @@ -0,0 +1,951 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# Helm Charts をはじめよう (cert-manager / Auditor モードを使用した TLS 対応の ScalarDL Ledger および Auditor) + +このチュートリアルでは、Kubernetes クラスターでテスト環境として Helm Charts と cert-manager を使用して、TLS 構成で ScalarDL Ledger と ScalarDL Auditor を使い始める方法について説明します。開始する前に、テスト用の Mac または Linux 環境を用意しておく必要があります。また、このチュートリアルでは **minikube** の使用について説明していますが、説明されている手順はどの Kubernetes クラスターでも機能するはずです。 + +## 要件 + +* ScalarDL のライセンスキー (試用ライセンスまたは商用ライセンス) が必要です。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。 +* TLS をサポートする ScalarDL 3.9以降を使用する必要があります。 + +:::note + +監査によるビザンチン障害検出を適切に行うには、ScalarDL Ledger と ScalarDL Auditor を異なる管理ドメインにデプロイして管理する必要があります。ただし、このチュートリアルでは、テストを容易にするために、ScalarDL Ledger と ScalarDL Auditor を同じ Kubernetes クラスターにデプロイします。 + +::: + +## 作成するもの + +このチュートリアルでは、次の方法で Kubernetes クラスターに次のコンポーネントをデプロイします。 + +``` ++-----------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +---------+ | +| +---> | Envoy | ---+ +---> | Ledger | ---+ | +| | +-------+ | | +---------+ | | +| | | | | | +| +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Ledger | ---+---> | PostgreSQL | | +| | | (Envoy) | | +-------+ | | (Ledger) | | +---------+ | | (For Ledger) | | +| | +---------+ | | +-----------+ | | +---------------+ | +| [Pod] | | +-------+ | | +---------+ | | +| | +---> | Envoy | ---+ +---> | Ledger | ---+ | +| +--------+ | +-------+ +---------+ | +| | Client | ---+ | +| +--------+ | +-------+ +---------+ | +| | +---> | Envoy | ---+ +---> | Auditor | ---+ | +| | | +-------+ | | +---------+ | | +| | | | | | | +| | +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Auditor | ---+---> | PostgreSQL | | +| | (Envoy) | | +-------+ | | (Auditor) | | +---------+ | | (For Auditor) | | +| +---------+ | | +-----------+ | | +---------------+ | +| | +-------+ | | +---------+ | | +| +---> | Envoy | ---+ +---> | Auditor | ---+ | +| +-------+ +---------+ | +| | +| +--------------------------------------------------------------------------+ +---------------------+ | +| | cert-manager (create private key and certificate for Envoy and ScalarDL) | | Issuer (Private CA) | | +| +--------------------------------------------------------------------------+ +---------------------+ | +| | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +cert-manager は、TLS 接続用に次の秘密鍵と証明書ファイルを自動的に作成します。 + +``` + +----------------------+ + +---> | For Scalar Envoy | + | +----------------------+ + | | tls.key | + | | tls.crt | + | +----------------------+ + | ++-------------------------+ | +----------------------+ +| Issuer (Self-signed CA) | ---(Sign certificates)---+---> | For ScalarDL Ledger | ++-------------------------+ | +----------------------+ +| tls.key | | | tls.key | +| tls.crt | | | tls.crt | +| ca.crt | | +----------------------+ ++-------------------------+ | + | +----------------------+ + +---> | For ScalarDL Auditor | + +----------------------+ + | tls.key | + | tls.crt | + +----------------------+ +``` + +Scalar Helm Charts は、各接続で TLS を有効にするために、Envoy と ScalarDL の各秘密鍵と証明書ファイルを次のように自動的にマウントします。ルート CA 証明書ファイルはクライアントに手動でマウントします。 + +``` + +------------------------------------------------+ +--------------------------------------+ + +-------(Normal request)-----> | Envoy for ScalarDL Ledger | ---> | ScalarDL Ledger | + | +------------------------------------------------+ +--------------------------------------+ + | +---(Recovery request)---> | tls.key | ---> | tls.key | + | | | tls.crt | | tls.crt | + | | | ca.crt (to verify tls.crt of ScalarDL Ledger) | | ca.crt (to check health) | + | | +------------------------------------------------+ +--------------------------------------+ ++---------------------------------------+ | | +| Client | ---+ | ++---------------------------------------+ | +------------------------------------------------------------------------------------------------------------------------------+ +| ca.crt (to verify tls.crt of Envoy) | | | ++---------------------------------------+ | | + | +------------------------------------------------+ +--------------------------------------+ | + +-------(Normal request)-----> | Envoy for ScalarDL Auditor | ---> | ScalarDL Auditor | ---+ + +------------------------------------------------+ +--------------------------------------+ + | tls.key | | tls.key | + | tls.crt | | tls.crt | + | ca.crt (to verify tls.crt of ScalarDL Auditor) | | ca.crt (to check health) | + +------------------------------------------------+ | ca.crt (to verify tls.crt of Envoy) | + +--------------------------------------+ +``` + +ScalarDL 関連コンポーネント間には、次の接続が存在します: + +* **`クライアント - ScalarDL Ledger 用 Envoy`:** ScalarDL API 関数を実行すると、クライアントは ScalarDL Ledger 用 Envoy にアクセスします。 +* **`クライアント - ScalarDL Auditor 用 Envoy`:** ScalarDL API 関数を実行すると、クライアントは ScalarDL Auditor 用 Envoy にアクセスします。 +* **`ScalarDL Ledger 用 Envoy - ScalarDL Ledger`:** Envoy は ScalarDL Ledger の前で L7 (gRPC) ロードバランサーとして機能します。 +* **`ScalarDL Auditor 用 Envoy - ScalarDL Auditor`:** Envoy は ScalarDL Auditor の前で L7 (gRPC) ロードバランサーとして機能します。 +* **`ScalarDL Auditor - Envoy for ScalarDL Ledger (ScalarDL Ledger)`:** ScalarDL がデータの一貫性を保つために回復プロセスを実行する必要がある場合、ScalarDL Auditor は Envoy を介して ScalarDL Ledger に対してリクエストを実行します。 + +## ステップ1. Kubernetes クラスターを起動してツールをインストールする + +Kubernetes クラスターを準備し、いくつかのツール (`kubectl`、`helm`、`cfssl`、および `cfssljson`) をインストールする必要があります。インストール方法の詳細については、[Scalar Helm Charts の使用開始](getting-started-scalar-helm-charts.mdx)を参照してください。 + +## ステップ2. PostgreSQL コンテナを起動する + +ScalarDL Ledger と ScalarDL Auditor は、バックエンドデータベースとして何らかのデータベースシステムを使用する必要があります。このチュートリアルでは、PostgreSQL を使用します。 + +次のようにして、Kubernetes クラスターに PostgreSQL をデプロイできます。 + +1. Bitnami helm リポジトリを追加します。 + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Ledger 用に PostgreSQL をデプロイします。 + + ```console + helm install postgresql-ledger bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. Auditor 用に PostgreSQL をデプロイします。 + + ```console + helm install postgresql-auditor bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. PostgreSQL コンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 11s + postgresql-ledger-0 1/1 Running 0 16s + ``` + +## ステップ3. 作業ディレクトリを作成する + +ローカルにいくつかの構成ファイルと秘密鍵および証明書ファイルを作成します。必ずそれらのファイル用の作業ディレクトリを作成してください。 + +1. 作業ディレクトリを作成します。 + + ```console + mkdir -p ${HOME}/scalardl-test/ + ``` + +## ステップ4. cert-manager と発行者リソースをデプロイする + +このチュートリアルでは、cert-manager を使用して秘密鍵と証明書を発行および管理します。次のようにして、Kubernetes クラスターに cert-manager をデプロイできます。 + +1. Jetstack helm リポジトリを追加します。 + + ```console + helm repo add jetstack https://charts.jetstack.io + ``` + +1. cert-manager をデプロイします。 + + ```console + helm install cert-manager jetstack/cert-manager \ + --create-namespace \ + --set installCRDs=true \ + -n cert-manager + ``` + +1. cert-manager コンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod -n cert-manager + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + cert-manager-6dc66985d4-6lvtt 1/1 Running 0 26s + cert-manager-cainjector-c7d4dbdd9-xlrpn 1/1 Running 0 26s + cert-manager-webhook-847d7676c9-ckcz2 1/1 Running 0 26s + ``` + +1. 作業ディレクトリを `${HOME}/scalardl-test/` に変更します。 + + ```console + cd ${HOME}/scalardl-test/ + ``` + +1. プライベート CA のカスタム値ファイル (`private-ca-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/private-ca-custom-values.yaml + apiVersion: cert-manager.io/v1 + kind: Issuer + metadata: + name: self-signed-issuer + spec: + selfSigned: {} + --- + apiVersion: cert-manager.io/v1 + kind: Certificate + metadata: + name: self-signed-ca-cert + spec: + isCA: true + commonName: self-signed-ca + secretName: self-signed-ca-cert-secret + privateKey: + algorithm: ECDSA + size: 256 + issuerRef: + name: self-signed-issuer + kind: Issuer + group: cert-manager.io + --- + apiVersion: cert-manager.io/v1 + kind: Issuer + metadata: + name: self-signed-ca + spec: + ca: + secretName: self-signed-ca-cert-secret + EOF + ``` + +1. 自己署名 CA を展開します。 + + ```console + kubectl apply -f ./private-ca-custom-values.yaml + ``` + +1. 発行者リソースが `True` であるかどうかを確認します。 + + ```console + kubectl get issuer + ``` + + [コマンド実行結果] + + ```console + NAME READY AGE + self-signed-ca True 6s + self-signed-issuer True 6s + ``` + +## ステップ5. Helm Charts を使用して ScalarDL Ledger と ScalarDL Auditor のデータベーススキーマを作成する + +Helm Charts を使用して、Kubernetes クラスターに2つの ScalarDL Schema Loader ポッドをデプロイします。ScalarDL Schema Loader は、PostgreSQL に ScalarDL Ledger と Auditor のデータベーススキーマを作成します。 + +1. Scalar Helm Charts リポジトリを追加します。 + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. ScalarDL Schema Loader for Ledger のカスタム値ファイル (`schema-loader-ledger-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_LEDGER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_LEDGER_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + secretName: "schema-ledger-credentials-secret" + EOF + ``` + +1. ScalarDL Schema Loader for Auditor のカスタム値ファイル (`schema-loader-auditor-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/schema-loader-auditor-custom-values.yaml + schemaLoading: + schemaType: "auditor" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_AUDITOR_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_AUDITOR_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + secretName: "schema-auditor-credentials-secret" + EOF + ``` + +1. ScalarDL Ledger 用の PostgreSQL のユーザー名とパスワードを含む `schema-ledger-credentials-secret` という名前のシークレットリソースを作成します。 + + ```console + kubectl create secret generic schema-ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres \ + -n default + ``` + +1. ScalarDL Auditor 用の PostgreSQL のユーザー名とパスワードを含む `schema-auditor-credentials-secret` という名前のシークレットリソースを作成します。 + + ```console + kubectl create secret generic schema-auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres \ + -n default + ``` + +1. ScalarDL Schema Loader のチャートバージョンを設定します。 + + ```console + SCALAR_DL_VERSION=3.9.1 + SCALAR_DL_SCHEMA_LOADER_CHART_VERSION=$(helm search repo scalar-labs/schema-loading -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. ScalarDL Ledger 用の ScalarDL Schema Loader をデプロイします。 + + ```console + helm install schema-loader-ledger scalar-labs/schema-loading -f ${HOME}/scalardl-test/schema-loader-ledger-custom-values.yaml --version ${SCALAR_DL_SCHEMA_LOADER_CHART_VERSION} -n default + ``` + +1. ScalarDL Auditor 用の ScalarDL Schema Loader をデプロイします。 + + ```console + helm install schema-loader-auditor scalar-labs/schema-loading -f ${HOME}/scalardl-test/schema-loader-auditor-custom-values.yaml --version ${SCALAR_DL_SCHEMA_LOADER_CHART_VERSION} -n default + ``` + +1. ScalarDL Schema Loader ポッドが「完了」ステータスでデプロイされているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 2m56s + postgresql-ledger-0 1/1 Running 0 3m1s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 6s + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 10s + ``` + + ScalarDL Schema Loader ポッドのステータスが **ContainerCreating** または **Running** の場合、それらのポッドの `STATUS` 列に `Completed` と表示されるまで待ちます。 + +## ステップ6. Helm Charts を使用して、Kubernetes クラスターに ScalarDL Ledger と ScalarDL Auditor をデプロイします + +1. ライセンスキーと証明書を環境変数として設定します。ライセンスキーがない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。`` と `` の値の詳細については、[製品ライセンスキーを構成する方法](https://scalardl.scalar-labs.com/docs/latest/scalar-licensing/)を参照してください。 + + ```console + SCALAR_DL_LEDGER_LICENSE_KEY='' + SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM='' + SCALAR_DL_AUDITOR_LICENSE_KEY='' + SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM='' + ``` + +1. ScalarDL Ledger のカスタム値ファイル (`scalardl-ledger-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + + tls: + downstream: + enabled: true + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - envoy.scalar.example.com + upstream: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" + + ledger: + + image: + repository: "ghcr.io/scalar-labs/scalardl-ledger-byol" + + ledgerProperties: | + ### Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_LEDGER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_LEDGER_POSTGRES_PASSWORD} + + ### Ledger configurations + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.authentication.method=hmac + scalar.dl.ledger.authentication.hmac.cipher_key=${env:SCALAR_DL_LEDGER_HMAC_CIPHER_KEY} + scalar.dl.ledger.servers.authentication.hmac.secret_key=${env:SCALAR_DL_LEDGER_HMAC_SECRET_KEY} + + ### TLS configurations + scalar.dl.ledger.server.tls.enabled=true + scalar.dl.ledger.server.tls.cert_chain_path=/tls/scalardl-ledger/certs/tls.crt + scalar.dl.ledger.server.tls.private_key_path=/tls/scalardl-ledger/certs/tls.key + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DL_LEDGER_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - ledger.scalardl.example.com + + secretName: "ledger-credentials-secret" + EOF + ``` + +1. ScalarDL Auditor のカスタム値ファイル (`scalardl-auditor-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-auditor-custom-values.yaml + envoy: + + tls: + downstream: + enabled: true + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - envoy.scalar.example.com + upstream: + enabled: true + overrideAuthority: "auditor.scalardl.example.com" + + + auditor: + + image: + repository: "ghcr.io/scalar-labs/scalardl-auditor-byol" + + auditorProperties: | + ### Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_AUDITOR_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_AUDITOR_POSTGRES_PASSWORD} + + ### Auditor configurations + scalar.dl.auditor.ledger.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.auditor.authentication.method=hmac + scalar.dl.auditor.authentication.hmac.cipher_key=${env:SCALAR_DL_AUDITOR_HMAC_CIPHER_KEY} + scalar.dl.auditor.servers.authentication.hmac.secret_key=${env:SCALAR_DL_AUDITOR_HMAC_SECRET_KEY} + + ### TLS configurations + scalar.dl.auditor.server.tls.enabled=true + scalar.dl.auditor.server.tls.cert_chain_path=/tls/scalardl-auditor/certs/tls.crt + scalar.dl.auditor.server.tls.private_key_path=/tls/scalardl-auditor/certs/tls.key + scalar.dl.auditor.tls.enabled=true + scalar.dl.auditor.tls.ca_root_cert_path=/tls/scalardl-ledger/certs/ca.crt + scalar.dl.auditor.tls.override_authority=envoy.scalar.example.com + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DL_AUDITOR_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "auditor.scalardl.example.com" + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - auditor.scalardl.example.com + + secretName: "auditor-credentials-secret" + EOF + ``` + +1. 資格情報とライセンスキーを含む `ledger-credentials-secret` という名前のシークレットリソースを作成します。 + + ```console + kubectl create secret generic ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DL_LEDGER_HMAC_CIPHER_KEY=ledger-hmac-cipher-key \ + --from-literal=SCALAR_DL_LEDGER_HMAC_SECRET_KEY=scalardl-hmac-secret-key \ + --from-literal=SCALAR_DL_LEDGER_LICENSE_KEY="${SCALAR_DL_LEDGER_LICENSE_KEY}" \ + --from-file=SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. 資格情報とライセンスキーを含む `auditor-credentials-secret` という名前のシークレットリソースを作成します。 + + ```console + kubectl create secret generic auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DL_AUDITOR_HMAC_CIPHER_KEY=auditor-hmac-cipher-key \ + --from-literal=SCALAR_DL_AUDITOR_HMAC_SECRET_KEY=scalardl-hmac-secret-key \ + --from-literal=SCALAR_DL_AUDITOR_LICENSE_KEY="${SCALAR_DL_AUDITOR_LICENSE_KEY}" \ + --from-file=SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. `auditor-keys` という名前のシークレットリソースを作成して、`digital-signature` 認証方式を無効にします。このチュートリアルでは、`digital-signature` の代わりに `hmac` 認証方式を使用します。 + + ```console + kubectl create secret generic auditor-keys \ + --from-literal=tls.key=dummy-data-to-disable-digital-signature-method \ + --from-literal=certificate=dummy-data-to-disable-digital-signature-method \ + -n default + ``` + + 注意: 認証方法として `hmac` を使用する場合は、Helm Chart 側で `digital-signature` を無効にするためにダミーのシークレット `auditor-key` を作成する必要があります。 + +1. ScalarDL Ledger と ScalarDL Auditor のチャートバージョンを設定します。 + + ```console + SCALAR_DL_LEDGER_CHART_VERSION=$(helm search repo scalar-labs/scalardl -l | grep -v -e "scalar-labs/scalardl-audit" | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + SCALAR_DL_AUDITOR_CHART_VERSION=$(helm search repo scalar-labs/scalardl-audit -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. ScalarDL Ledger をデプロイします。 + + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ${HOME}/scalardl-test/scalardl-ledger-custom-values.yaml --version ${SCALAR_DL_LEDGER_CHART_VERSION} -n default + ``` + +1. ScalarDL Auditor をデプロイします。 + + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ${HOME}/scalardl-test/scalardl-auditor-custom-values.yaml --version ${SCALAR_DL_AUDITOR_CHART_VERSION} -n default + ``` + +1. ScalarDL Ledger および ScalarDL Auditor ポッドがデプロイされているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 14m + postgresql-ledger-0 1/1 Running 0 14m + scalardl-auditor-auditor-5b885ff4c8-fwkpf 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-g69cb 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-nsmnq 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-5mn6v 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-fpq8j 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-lsz2t 1/1 Running 0 18s + scalardl-ledger-envoy-547bbf7546-n7p5x 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-p8nwp 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-pskpb 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-5zsbj 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-vnmrw 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-wpjvs 1/1 Running 0 26s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 11m + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 11m + ``` + + ScalarDL Ledger ポッドと ScalarDL Auditor ポッドが適切にデプロイされている場合、それらのポッドの `STATUS` 列には `Running` と表示されます。 + +1. ScalarDL Ledger および ScalarDL Auditor サービスがデプロイされているかどうかを確認します。 + + ```console + kubectl get svc -n default + ``` + + [コマンド実行結果] + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-auditor ClusterIP 10.107.9.78 5432/TCP 15m + postgresql-auditor-hl ClusterIP None 5432/TCP 15m + postgresql-ledger ClusterIP 10.108.241.181 5432/TCP 15m + postgresql-ledger-hl ClusterIP None 5432/TCP 15m + scalardl-auditor-envoy ClusterIP 10.100.61.202 40051/TCP,40052/TCP 55s + scalardl-auditor-envoy-metrics ClusterIP 10.99.6.227 9001/TCP 55s + scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 55s + scalardl-auditor-metrics ClusterIP 10.108.1.147 8080/TCP 55s + scalardl-ledger-envoy ClusterIP 10.101.191.116 50051/TCP,50052/TCP 61s + scalardl-ledger-envoy-metrics ClusterIP 10.106.52.103 9001/TCP 61s + scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 61s + scalardl-ledger-metrics ClusterIP 10.99.122.106 8080/TCP 61s + ``` + + ScalarDL Ledger および ScalarDL Auditor サービスが適切にデプロイされている場合は、`CLUSTER-IP` 列にプライベート IP アドレスが表示されます。 + +:::note + +`scalardl-ledger-headless`、`scalardl-auditor-headless`、`postgresql-ledger-hl`、および `postgresql-auditor-hl` の `CLUSTER-IP` 値は、IP アドレスがないため `None` になります。 + +::: + +## ステップ7. クライアントコンテナを起動する + +クライアントコンテナで CA 証明書ファイルを使用します。そのため、シークレットリソースを作成し、クライアントコンテナにマウントする必要があります。 + +1. `client-ca-cert` という名前のシークレットリソースを作成します。 + + ```console + kubectl create secret generic client-ca-cert --from-file=ca.crt=<(kubectl get secret self-signed-ca-cert-secret -o "jsonpath={.data['ca\.crt']}" | base64 -d) -n default + ``` + +1. クライアントポッドのマニフェストファイル (`scalardl-client-pod.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-client-pod.yaml + apiVersion: v1 + kind: Pod + metadata: + name: "scalardl-client" + spec: + containers: + - name: scalardl-client + image: eclipse-temurin:8-jdk + command: ['sleep'] + args: ['inf'] + env: + - name: SCALAR_DL_VERSION + value: SCALAR_DL_CLIENT_POD_SCALAR_DL_VERSION + volumeMounts: + - name: "client-ca-cert" + mountPath: "/certs/" + readOnly: true + volumes: + - name: "client-ca-cert" + secret: + secretName: "client-ca-cert" + restartPolicy: Never + EOF + ``` + +1. マニフェストファイルで ScalarDL バージョンを設定します。 + + ```console + sed -i s/SCALAR_DL_CLIENT_POD_SCALAR_DL_VERSION/${SCALAR_DL_VERSION}/ ${HOME}/scalardl-test/scalardl-client-pod.yaml + ``` + +1. クライアントポッドをデプロイします。 + + ```console + kubectl apply -f ${HOME}/scalardl-test/scalardl-client-pod.yaml -n default + ``` + +1. クライアントコンテナーが実行されているかどうかを確認します。 + + ```console + kubectl get pod scalardl-client -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + scalardl-client 1/1 Running 0 4s + ``` + +## ステップ8. クライアントコンテナで ScalarDL サンプルコントラクトを実行する + +以下では、サンプルコントラクトを実行するために必要な最小限の手順について説明します。ScalarDL Ledger と ScalarDL Auditor の詳細については、以下を参照してください。 + +* [ScalarDL の使用開始](https://scalardl.scalar-labs.com/docs/latest/getting-started/) +* [ScalarDL Auditor の使用開始](https://scalardl.scalar-labs.com/docs/latest/getting-started-auditor/) + +1. クライアントコンテナーで bash を実行します。 + + ```console + kubectl exec -it scalardl-client -n default -- bash + ``` + + 次の手順のコマンドは、クライアントコンテナーで実行する必要があります。 + +1. クライアントコンテナーに git、curl、unzip コマンドをインストールします。 + + ```console + apt update && apt install -y git curl unzip + ``` + +1. ScalarDL Java Client SDK git リポジトリをクローンします。 + + ```console + git clone https://github.com/scalar-labs/scalardl-java-client-sdk.git + ``` + +1. 作業ディレクトリを `scalardl-java-client-sdk/` に変更します。 + + ```console + cd scalardl-java-client-sdk/ + ``` + + ```console + pwd + ``` + + [コマンド実行結果] + + ```console + /scalardl-java-client-sdk + ``` + +1. 使用しているバージョンにブランチを変更します。 + + ```console + git checkout -b v${SCALAR_DL_VERSION} refs/tags/v${SCALAR_DL_VERSION} + ``` + +1. サンプルコントラクトを作成します。 + + ```console + ./gradlew assemble + ``` + +1. [ScalarDL Java Client SDK リリース](https://github.com/scalar-labs/scalardl-java-client-sdk/releases)から ScalarDL の CLI ツールをダウンロードします。 + + ```console + curl -OL https://github.com/scalar-labs/scalardl-java-client-sdk/releases/download/v${SCALAR_DL_VERSION}/scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip + ``` + +1. `scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip` ファイルを解凍します。 + + ```console + unzip ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip + ``` + +1. Kubernetes クラスター上の ScalarDL Ledger および ScalarDL Auditor にアクセスするための `client.properties` という名前の構成ファイルを作成します。 + + ```console + cat << 'EOF' > client.properties + # Ledger configuration + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.client.tls.enabled=true + scalar.dl.client.tls.ca_root_cert_path=/certs/ca.crt + scalar.dl.client.tls.override_authority=envoy.scalar.example.com + + # Auditor configuration + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + scalar.dl.client.auditor.tls.enabled=true + scalar.dl.client.auditor.tls.ca_root_cert_path=/certs/ca.crt + scalar.dl.client.auditor.tls.override_authority=envoy.scalar.example.com + + # Client configuration + scalar.dl.client.authentication_method=hmac + scalar.dl.client.entity.id=client + scalar.dl.client.entity.identity.hmac.secret_key=scalardl-hmac-client-secert-key + EOF + ``` + +1. クライアントシークレットを登録します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-secret --config ./client.properties + ``` + +1. サンプルコントラクト `StateUpdater` を登録します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id StateUpdater --contract-binary-name com.org1.contract.StateUpdater --contract-class-file ./build/classes/java/main/com/org1/contract/StateUpdater.class + ``` + +1. サンプルコントラクト `StateReader` を登録します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id StateReader --contract-binary-name com.org1.contract.StateReader --contract-class-file ./build/classes/java/main/com/org1/contract/StateReader.class + ``` + +1. 検証リクエストを実行するには、コントラクト `ValidateLedger` を登録します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id validate-ledger --contract-binary-name com.scalar.dl.client.contract.ValidateLedger --contract-class-file ./build/classes/java/main/com/scalar/dl/client/contract/ValidateLedger.class + ``` + +1. コントラクト `StateUpdater` を実行します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl execute-contract --config ./client.properties --contract-id StateUpdater --contract-argument '{"asset_id": "test_asset", "state": 3}' + ``` + + このサンプルコントラクトは、`test_asset` という名前のアセットの `state` (値) を `3` に更新します。 + +1. コントラクト `StateReader` を実行します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl execute-contract --config ./client.properties --contract-id StateReader --contract-argument '{"asset_id": "test_asset"}' + ``` + + [コマンド実行結果] + + ```console + Contract result: + { + "id" : "test_asset", + "age" : 0, + "output" : { + "state" : 3 + } + } + ``` + + ### 参照 + + * 資産データが改ざんされていない場合、コントラクト実行を要求する `execute-contract` コマンドを実行すると、結果として `OK` が返されます。 + * アセットデータが改ざんされている場合 (たとえば、データベースの `state` 値が改ざんされている場合) 、コントラクト実行を要求する `execute-contract` コマンドを実行すると、結果として `OK` 以外の値 (たとえば、`INCONSISTENT_STATES`) が返されます。ScalarDL がデータ改ざんを検出する方法の例については、以下を参照してください。 + + [コマンド実行結果 (資産データが改ざんされた場合) ] + + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + +1. 資産の検証リクエストを実行します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl validate-ledger --config ./client.properties --asset-id "test_asset" + ``` + + [コマンド実行結果] + + ```console + { + "status_code" : "OK", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEYCIQDiiXqzw6K+Ml4uvn8rK43o5wHWESU3hoXnZPi6/OeKVwIhAM+tFBcapl6zg47Uq0Uc8nVNGWNHZLBDBGve3F0xkzTR" + }, + "Auditor" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEUCIQDLsfUR2PmxSvfpL3YvHJUkz00RDpjCdctkroZKXE8d5QIgH73FQH2e11jfnynD00Pp9DrIG1vYizxDsvxUsMPo9IU=" + } + } + ``` + + ### 参照 + + * 資産データが改ざんされていない場合、検証を要求する `validate-ledger` コマンドを実行すると、結果として `OK` が返されます。 + * 資産データが改ざんされている場合 (たとえば、データベースの `state` 値が改ざんされている場合)、検証を要求する `validate-ledger` コマンドを実行すると、結果として `OK` 以外の値 (たとえば、`INVALID_OUTPUT`) が返されます。ScalarDL がデータ改ざんを検出する方法の例については、以下を参照してください。 + + [コマンド実行結果 (資産データが改ざんされた場合) ] + + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + +1. クライアントコンテナーを終了します。 + + ```console + exit + ``` + +## ステップ9. すべてのリソースを削除する + +Kubernetes クラスターで ScalarDL Ledger および ScalarDL Auditor テストを完了したら、すべてのリソースを削除します。 + +1. ScalarDL Ledger、ScalarDL Auditor、ScalarDL Schema Loader、および PostgreSQL をアンインストールします。 + + ```console + helm uninstall -n default scalardl-ledger schema-loader-ledger postgresql-ledger scalardl-auditor schema-loader-auditor postgresql-auditor + ``` + +1. 自己署名 CA を削除します。 + + ``` + kubectl delete -f ./private-ca-custom-values.yaml + ``` + +1. cert-manager をアンインストールします。 + + ```console + helm uninstall -n cert-manager cert-manager + ``` + +1. クライアントコンテナーを削除します。 + + ``` + kubectl delete pod scalardl-client --grace-period 0 -n default + ``` + +1. シークレットリソースを削除します。 + + ``` + kubectl delete secrets self-signed-ca-cert-secret schema-ledger-credentials-secret schema-auditor-credentials-secret scalardl-ledger-tls-cert scalardl-ledger-envoy-tls-cert scalardl-auditor-tls-cert scalardl-auditor-envoy-tls-cert ledger-credentials-secret auditor-credentials-secret client-ca-cert auditor-keys + ``` + +1. ネームスペース `cert-manager` を削除します。 + + ``` + kubectl delete ns cert-manager + ``` + +1. 作業ディレクトリとサンプルファイル (構成ファイル) を削除します。 + + ```console + cd ${HOME} + ``` + + ```console + rm -rf ${HOME}/scalardl-test/ + ``` + +## 参考文献 + +Scalar 製品の監視またはログ記録を開始する方法については、次のチュートリアルを参照してください。 + +* [Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング)](getting-started-monitoring.mdx) +* [Helm Charts をはじめよう (Loki Stack を使用したログ記録)](getting-started-logging.mdx) +* [Helm Charts をはじめよう (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls.mdx new file mode 100644 index 00000000..c0924e75 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls.mdx @@ -0,0 +1,1023 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# Helm Chart をはじめよう (TLS を使用した ScalarDL Ledger および Auditor / Auditor モード) + +このドキュメントでは、Kubernetes クラスター上の Helm Chart をテスト環境として使用して、TLS 構成で ScalarDL Ledger および ScalarDL Auditor を開始する方法について説明します。ここでは、テスト用の Mac または Linux 環境がすでにあることを前提としています。このドキュメントでは **minikube** を使用しますが、これから説明する手順はどの Kubernetes クラスターでも機能するはずです。 + +## 要件 + +* ScalarDLのライセンスキー (試用ライセンスまたは商用ライセンス) を取得する必要があります。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)してください。 +* TLSに対応したScalarDL v3.9以降を使用する必要があります。 + +:::note + +監査によるビザンチン障害検出を適切に機能させるには、ScalarDL Ledger と ScalarDL Auditor を別の管理ドメインに展開して管理する必要があります。ただし、このチュートリアルでは、テストを容易にするために、ScalarDL Ledger と ScalarDL Auditor を同じ Kubernetes クラスターにデプロイします。 + +::: + +## 作成するもの + +次のように、次のコンポーネントを Kubernetes クラスターにデプロイします。 + +``` ++-----------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +---------+ | +| +---> | Envoy | ---+ +---> | Ledger | ---+ | +| | +-------+ | | +---------+ | | +| | | | | | +| +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Ledger | ---+---> | PostgreSQL | | +| | | (Envoy) | | +-------+ | | (Ledger) | | +---------+ | | (For Ledger) | | +| | +---------+ | | +-----------+ | | +---------------+ | +| [Pod] | | +-------+ | | +---------+ | | +| | +---> | Envoy | ---+ +---> | Ledger | ---+ | +| +--------+ | +-------+ +---------+ | +| | Client | ---+ | +| +--------+ | +-------+ +---------+ | +| | +---> | Envoy | ---+ +---> | Auditor | ---+ | +| | | +-------+ | | +---------+ | | +| | | | | | | +| | +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Auditor | ---+---> | PostgreSQL | | +| | (Envoy) | | +-------+ | | (Auditor) | | +---------+ | | (For Auditor) | | +| +---------+ | | +-----------+ | | +---------------+ | +| | +-------+ | | +---------+ | | +| +---> | Envoy | ---+ +---> | Auditor | ---+ | +| +-------+ +---------+ | +| | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +TLS 接続用に次の秘密鍵ファイルと証明書ファイルを作成します。 + +``` + +----------------------+ + +---> | For Scalar Envoy | + | +----------------------+ + | | envoy-key.pem | + | | envoy.pem | + | +----------------------+ + | ++----------------------+ | +----------------------+ +| Self-signed CA | ---(Sign certificates)---+---> | For ScalarDL Ledger | ++----------------------+ | +----------------------+ +| ca-key.pem | | | ledger-key.pem | +| ca.pem | | | ledger.pem | ++----------------------+ | +----------------------+ + | + | +----------------------+ + +---> | For ScalarDL Auditor | + +----------------------+ + | auditor-key.pem | + | auditor.pem | + +----------------------+ +``` + +各接続で TLS を有効にするために、各秘密鍵と証明書ファイルを次のように設定します。 + +``` + +--------------------------------+ +--------------------------------+ + +-------(Normal request)-----> | Envoy for ScalarDL Ledger | ---> | ScalarDL Ledger | + | +--------------------------------+ +--------------------------------+ + | +---(Recovery request)---> | envoy-key.pem | ---> | ledger-key.pem | + | | | envoy.pem | | ledger.pem | + | | | ca.pem (to verify ledger.pem) | | ca.pem (used for health check) | + | | +--------------------------------+ +--------------------------------+ ++--------------------------------+ | | +| Client | ---+ | ++--------------------------------+ | +--------------------------------------------------------------------------------------------------------+ +| ca.pem (to verify envoy.pem) | | | ++--------------------------------+ | | + | +--------------------------------+ +--------------------------------+ | + +-------(Normal request)-----> | Envoy for ScalarDL Auditor | ---> | ScalarDL Auditor | ---+ + +--------------------------------+ +--------------------------------+ + | envoy-key.pem | | auditor-key.pem | + | envoy.pem | | auditor.pem | + | ca.pem (to verify auditor.pem) | | ca.pem (used for health check) | + +--------------------------------+ | ca.pem (to verify ledger.pem) | + +--------------------------------+ +``` + +ScalarDL 関連コンポーネント間には、次の接続があります。 + +* **`クライアント - ScalarDL Ledger の Envoy`:** 一部のScalarDL APIを実行すると、クライアントはEnvoy for ScalarDL Ledgerにアクセスします。 +* **`クライアント - ScalarDL Auditor の Envoy`:** 一部のScalarDL APIを実行すると、クライアントはEnvoy for ScalarDL Auditorにアクセスします。 +* **`ScalarDL Ledgerの Envoy - ScalarDL Ledger`:** Envoy は、ScalarDL Ledger の前で L7 (gRPC) ロードバランサーとして機能します。 +* **`ScalarDL Auditor の Envoy - ScalarDL Auditor`:** Envoy は、ScalarDL Auditor の前で L7 (gRPC) ロードバランサーとして機能します。 +* **`ScalarDL Auditor - ScalarDL Ledger (ScalarDL Ledger) の Envoy`:** ScalarDL がデータの一貫性を保つために回復プロセスを実行する必要がある場合、ScalarDL Auditor は Envoy を介して ScalarDL Lever に対してリクエストを実行します。 + +## ステップ1. Kubernetes クラスターを開始する + +Kubernetes クラスターを準備し、いくつかのツール (`kubectl`、`helm`、`cfssl`、および `cfssljson`) をインストールする必要があります。インストール方法の詳細については、[Scalar Helm Charts をはじめよう](getting-started-scalar-helm-charts.mdx)を参照してください。 + +## ステップ2. PostgreSQL コンテナーを開始する + +ScalarDL Ledger および ScalarDL Auditor は、バックエンドデータベースとして何らかのデータベースシステムを使用する必要があります。このチュートリアルでは、PostgreSQL を使用します。 + +次のようにして、Kubernetes クラスターに PostgreSQL をデプロイできます。 + +1. Bitnami Helm リポジトリを追加します。 + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Ledger 用に PostgreSQL をデプロイします。 + + ```console + helm install postgresql-ledger bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. Auditor 用に PostgreSQL をデプロイします。 + + ```console + helm install postgresql-auditor bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. PostgreSQL コンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 11s + postgresql-ledger-0 1/1 Running 0 16s + ``` + +## ステップ3. 作業ディレクトリを作成する + +いくつかの構成ファイルと秘密鍵および証明書ファイルをローカルに作成します。したがって、それらの作業ディレクトリを作成します。 + +1. 作業ディレクトリを作成します。 + + ```console + mkdir -p ${HOME}/scalardl-test/certs/ + ``` + +## ステップ4. 秘密鍵および証明書ファイルを作成する + +秘密鍵と証明書ファイルを作成します。 + +1. 作業ディレクトリを `${HOME}/scalardl-test/certs/` ディレクトリに変更します。 + + ```console + cd ${HOME}/scalardl-test/certs/ + ``` + +1. CA の情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/ca.json + { + "CN": "scalar-test-ca", + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Test CA" + } + ] + } + EOF + ``` + +1. CA の秘密鍵/証明書ファイルを作成します。 + + ```console + cfssl gencert -initca ca.json | cfssljson -bare ca + ``` + +1. CA 構成を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/ca-config.json + { + "signing": { + "default": { + "expiry": "87600h" + }, + "profiles": { + "scalar-test-ca": { + "expiry": "87600h", + "usages": [ + "signing", + "key encipherment", + "server auth" + ] + } + } + } + } + EOF + ``` + +1. Envoy 情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/envoy.json + { + "CN": "scalar-envoy", + "hosts": [ + "envoy.scalar.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Envoy Test" + } + ] + } + EOF + ``` + +1. ScalarDL Ledger 情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/ledger.json + { + "CN": "scalardl-ledger", + "hosts": [ + "ledger.scalardl.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "ScalarDL Ledger Test" + } + ] + } + EOF + ``` + +1. ScalarDL Auditor 情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/auditor.json + { + "CN": "scalardl-auditor", + "hosts": [ + "auditor.scalardl.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "ScalarDL Auditor Test" + } + ] + } + EOF + ``` + +1. Envoy の秘密鍵および証明書ファイルを作成します。 + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca envoy.json | cfssljson -bare envoy + ``` + +1. ScalarDL Ledger の秘密鍵および証明書ファイルを作成します。 + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca ledger.json | cfssljson -bare ledger + ``` + +1. ScalarDL Auditor の秘密鍵および証明書ファイルを作成します。 + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca auditor.json | cfssljson -bare auditor + ``` + +1. 秘密鍵および証明書ファイルが作成されたことを確認します。 + + ```console + ls -1 + ``` + + [コマンド実行結果] + + ```console + auditor-key.pem + auditor.csr + auditor.json + auditor.pem + ca-config.json + ca-key.pem + ca.csr + ca.json + ca.pem + envoy-key.pem + envoy.csr + envoy.json + envoy.pem + ledger-key.pem + ledger.csr + ledger.json + ledger.pem + ``` + +## ステップ5. Helm Charts を使用して ScalarDL Ledger と ScalarDL Auditor の DB スキーマを作成する + +Helm Chart を使用して、Kubernetes クラスターに2つの ScalarDL Schema Loader ポッドをデプロイします。ScalarDL Schema Loader は、PostgreSQL で ScalarDL Ledger と Auditor の DB スキーマを作成します。 + +1. 作業ディレクトリを `${HOME}/scalardl-test/` に変更します。 + + ```console + cd ${HOME}/scalardl-test/ + ``` + +1. Scalar helm リポジトリを追加します。 + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. ScalarDL Schema Loader for Ledger のカスタム値ファイル (`schema-loader-ledger-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_LEDGER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_LEDGER_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + secretName: "schema-ledger-credentials-secret" + EOF + ``` + +1. ScalarDL Schema Loader for Auditor のカスタム値ファイル (`schema-loader-auditor-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/schema-loader-auditor-custom-values.yaml + schemaLoading: + schemaType: "auditor" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_AUDITOR_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_AUDITOR_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + secretName: "schema-auditor-credentials-secret" + EOF + ``` + +1. PostgreSQL for Ledger のユーザー名とパスワードを含むシークレットリソースを作成します。 + + ```console + kubectl create secret generic schema-ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres \ + -n default + ``` + +1. PostgreSQL for Auditor のユーザー名とパスワードを含むシークレットリソースを作成します。 + + ```console + kubectl create secret generic schema-auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres \ + -n default + ``` + +1. ScalarDL Schema Loaderのチャートバージョンを設定します。 + + ```console + SCALAR_DL_VERSION=3.9.1 + SCALAR_DL_SCHEMA_LOADER_CHART_VERSION=$(helm search repo scalar-labs/schema-loading -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. Ledger 用の ScalarDL Schema Loader をデプロイします。 + + ```console + helm install schema-loader-ledger scalar-labs/schema-loading -f ${HOME}/scalardl-test/schema-loader-ledger-custom-values.yaml --version ${SCALAR_DL_SCHEMA_LOADER_CHART_VERSION} -n default + ``` + +1. Auditor 用の ScalarDL Schema Loader をデプロイします。 + + ```console + helm install schema-loader-auditor scalar-labs/schema-loading -f ${HOME}/scalardl-test/schema-loader-auditor-custom-values.yaml --version ${SCALAR_DL_SCHEMA_LOADER_CHART_VERSION} -n default + ``` + +1. ScalarDL Schema Loader ポッドがデプロイされ、完了しているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 2m56s + postgresql-ledger-0 1/1 Running 0 3m1s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 6s + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 10s + ``` + ScalarDL Schema Loader ポッドが **ContainerCreating** または **Running** の場合は、プロセスが完了するまで待ちます (ステータスは **Completed** になります)。 + +## ステップ6. Helm Chart を使用して Kubernetes クラスターに ScalarDL Ledger と ScalarDL Auditor をデプロイする + +1. ScalarDL Ledger のカスタム値ファイル (`scalardl-ledger-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + + tls: + downstream: + enabled: true + certChainSecret: "envoy-tls-cert" + privateKeySecret: "envoy-tls-key" + upstream: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" + caRootCertSecret: "scalardl-ledger-tls-ca" + + ledger: + + image: + repository: "ghcr.io/scalar-labs/scalardl-ledger-byol" + + ledgerProperties: | + ### Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_LEDGER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_LEDGER_POSTGRES_PASSWORD} + + ### Ledger configurations + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.authentication.method=hmac + scalar.dl.ledger.authentication.hmac.cipher_key=${env:SCALAR_DL_LEDGER_HMAC_CIPHER_KEY} + scalar.dl.ledger.servers.authentication.hmac.secret_key=${env:SCALAR_DL_LEDGER_HMAC_SECRET_KEY} + + ### TLS configurations + scalar.dl.ledger.server.tls.enabled=true + scalar.dl.ledger.server.tls.cert_chain_path=/tls/scalardl-auditor/certs/tls.crt + scalar.dl.ledger.server.tls.private_key_path=/tls/scalardl-auditor/certs/tls.key + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DL_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DL_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" + caRootCertSecret: "scalardl-ledger-tls-ca" + certChainSecret: "scalardl-ledger-tls-cert" + privateKeySecret: "scalardl-ledger-tls-key" + + secretName: "ledger-credentials-secret" + EOF + ``` + +1. ScalarDL Auditor のカスタム値ファイル (`scalardl-auditor-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-auditor-custom-values.yaml + envoy: + + tls: + downstream: + enabled: true + certChainSecret: "envoy-tls-cert" + privateKeySecret: "envoy-tls-key" + upstream: + enabled: true + overrideAuthority: "auditor.scalardl.example.com" + caRootCertSecret: "scalardl-auditor-tls-ca" + + auditor: + + image: + repository: "ghcr.io/scalar-labs/scalardl-auditor-byol" + + auditorProperties: | + ### Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_AUDITOR_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_AUDITOR_POSTGRES_PASSWORD} + + ### Auditor configurations + scalar.dl.auditor.ledger.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.auditor.authentication.method=hmac + scalar.dl.auditor.authentication.hmac.cipher_key=${env:SCALAR_DL_AUDITOR_HMAC_CIPHER_KEY} + scalar.dl.auditor.servers.authentication.hmac.secret_key=${env:SCALAR_DL_AUDITOR_HMAC_SECRET_KEY} + + ### TLS configurations + scalar.dl.auditor.server.tls.enabled=true + scalar.dl.auditor.server.tls.cert_chain_path=/tls/scalardl-auditor/certs/tls.crt + scalar.dl.auditor.server.tls.private_key_path=/tls/scalardl-auditor/certs/tls.key + scalar.dl.auditor.tls.enabled=true + scalar.dl.auditor.tls.ca_root_cert_path=/tls/scalardl-ledger/certs/ca.crt + scalar.dl.auditor.tls.override_authority=envoy.scalar.example.com + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DL_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DL_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "auditor.scalardl.example.com" + caRootCertSecret: "scalardl-auditor-tls-ca" + certChainSecret: "scalardl-auditor-tls-cert" + privateKeySecret: "scalardl-auditor-tls-key" + caRootCertForLedgerSecret: "scalardl-auditor-tls-ca-for-ledger" + + secretName: "auditor-credentials-secret" + EOF + ``` + +1. ライセンスキーと証明書を環境変数に設定します。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)してください。 + + ```console + SCALAR_DL_LICENSE_KEY= + SCALAR_DL_LICENSE_CHECK_CERT_PEM= + ``` + +1. 資格情報とライセンスキーを含むシークレットリソース `ledger-credentials-secret` を作成します。 + + ```console + kubectl create secret generic ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DL_LEDGER_HMAC_CIPHER_KEY=ledger-hmac-cipher-key \ + --from-literal=SCALAR_DL_LEDGER_HMAC_SECRET_KEY=scalardl-hmac-secret-key \ + --from-literal=SCALAR_DL_LICENSE_KEY=${SCALAR_DL_LICENSE_KEY} \ + --from-literal=SCALAR_DL_LICENSE_CHECK_CERT_PEM=${SCALAR_DL_LICENSE_CHECK_CERT_PEM} \ + -n default + ``` + +1. 資格情報とライセンスキーを含むシークレットリソース `auditor-credentials-secret` を作成します。 + + ```console + kubectl create secret generic auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DL_AUDITOR_HMAC_CIPHER_KEY=auditor-hmac-cipher-key \ + --from-literal=SCALAR_DL_AUDITOR_HMAC_SECRET_KEY=scalardl-hmac-secret-key \ + --from-literal=SCALAR_DL_LICENSE_KEY=${SCALAR_DL_LICENSE_KEY} \ + --from-literal=SCALAR_DL_LICENSE_CHECK_CERT_PEM=${SCALAR_DL_LICENSE_CHECK_CERT_PEM} \ + -n default + ``` + +1. Envoy の秘密鍵ファイルと証明書ファイルを含むシークレットリソースを作成します。 + + ```console + kubectl create secret generic envoy-tls-cert --from-file=tls.crt=${HOME}/scalardl-test/certs/envoy.pem -n default + kubectl create secret generic envoy-tls-key --from-file=tls.key=${HOME}/scalardl-test/certs/envoy-key.pem -n default + ``` + +1. ScalarDL Ledger の秘密鍵、証明書、CA 証明書ファイルを含むシークレットリソースを作成します。 + + ```console + kubectl create secret generic scalardl-ledger-tls-ca --from-file=ca.crt=${HOME}/scalardl-test/certs/ca.pem -n default + kubectl create secret generic scalardl-ledger-tls-cert --from-file=tls.crt=${HOME}/scalardl-test/certs/ledger.pem -n default + kubectl create secret generic scalardl-ledger-tls-key --from-file=tls.key=${HOME}/scalardl-test/certs/ledger-key.pem -n default + ``` + +1. ScalarDL Auditor の秘密鍵、証明書、CA 証明書ファイルを含むシークレットリソースを作成します。 + + ```console + kubectl create secret generic scalardl-auditor-tls-ca --from-file=ca.crt=${HOME}/scalardl-test/certs/ca.pem -n default + kubectl create secret generic scalardl-auditor-tls-cert --from-file=tls.crt=${HOME}/scalardl-test/certs/auditor.pem -n default + kubectl create secret generic scalardl-auditor-tls-key --from-file=tls.key=${HOME}/scalardl-test/certs/auditor-key.pem -n default + kubectl create secret generic scalardl-auditor-tls-ca-for-ledger --from-file=ca.crt=${HOME}/scalardl-test/certs/ca.pem -n default + ``` + +1. シークレットリソース `auditor-keys` を作成して、`デジタル署名` 認証方法を無効にします。このドキュメントでは、 `デジタル署名` の代わりに `hmac` 認証方法を使用します。 + + ```console + kubectl create secret generic auditor-keys \ + --from-literal=tls.key=dummy-data-to-disable-digital-signature-method \ + --from-literal=certificate=dummy-data-to-disable-digital-signature-method \ + -n default + ``` + 注: 認証方法として `hmac` を使用する場合は、ダミーのシークレット `auditor-key` を作成して、Helm Chart 側の `デジタル署名` を無効にする必要があります。 + +1. ScalarDL のチャートのバージョンを設定します。 + + ```console + SCALAR_DL_LEDGER_CHART_VERSION=$(helm search repo scalar-labs/scalardl -l | grep -v -e "scalar-labs/scalardl-audit" | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + SCALAR_DL_AUDITOR_CHART_VERSION=$(helm search repo scalar-labs/scalardl-audit -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. ScalarDL Ledger をデプロイします。 + + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ${HOME}/scalardl-test/scalardl-ledger-custom-values.yaml --version ${SCALAR_DL_LEDGER_CHART_VERSION} -n default + ``` + +1. ScalarDL Auditor をデプロイします。 + + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ${HOME}/scalardl-test/scalardl-auditor-custom-values.yaml --version ${SCALAR_DL_AUDITOR_CHART_VERSION} -n default + ``` + +1. ScalarDL Ledger および ScalarDL Auditor ポッドがデプロイされているかどうかを確認します。 + + ```console + kubectl get pod -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 14m + postgresql-ledger-0 1/1 Running 0 14m + scalardl-auditor-auditor-5b885ff4c8-fwkpf 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-g69cb 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-nsmnq 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-5mn6v 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-fpq8j 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-lsz2t 1/1 Running 0 18s + scalardl-ledger-envoy-547bbf7546-n7p5x 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-p8nwp 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-pskpb 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-5zsbj 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-vnmrw 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-wpjvs 1/1 Running 0 26s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 11m + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 11m + ``` + + ScalarDL Ledger および ScalarDL Auditor ポッドが適切にデプロイされている場合、ステータスが **Running** であることがわかります。 + +1. ScalarDL Ledger サービスと ScalarDL Auditor サービスがデプロイされているかどうかを確認します。 + + ```console + kubectl get svc -n default + ``` + + [コマンド実行結果] + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-auditor ClusterIP 10.107.9.78 5432/TCP 15m + postgresql-auditor-hl ClusterIP None 5432/TCP 15m + postgresql-ledger ClusterIP 10.108.241.181 5432/TCP 15m + postgresql-ledger-hl ClusterIP None 5432/TCP 15m + scalardl-auditor-envoy ClusterIP 10.100.61.202 40051/TCP,40052/TCP 55s + scalardl-auditor-envoy-metrics ClusterIP 10.99.6.227 9001/TCP 55s + scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 55s + scalardl-auditor-metrics ClusterIP 10.108.1.147 8080/TCP 55s + scalardl-ledger-envoy ClusterIP 10.101.191.116 50051/TCP,50052/TCP 61s + scalardl-ledger-envoy-metrics ClusterIP 10.106.52.103 9001/TCP 61s + scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 61s + scalardl-ledger-metrics ClusterIP 10.99.122.106 8080/TCP 61s + ``` + ScalarDL Ledger サービスと ScalarDL Auditor サービスが適切にデプロイされている場合は、CLUSTER-IP 列にプライベート IP アドレスが表示されます。 + +:::note + +`scalardl-ledger-headless`、`scalardl-auditor-headless`、`postgresql-ledger-hl`、`postgresql-auditor-hl` の `CLUSTER-IP` の値は、IP アドレスがないため `None` になります。。 + +::: + +## ステップ7. クライアントコンテナを開始する + +クライアントコンテナでCAの証明書ファイルを使用します。そこで、シークレットリソースを作成し、クライアントコンテナにマウントします。 + +1. シークレットリソース `client-ca-cert` を作成します。 + + ```console + kubectl create secret generic client-ca-cert --from-file=certificate=${HOME}/scalardl-test/certs/ca.pem -n default + ``` + +1. クライアントポッドのマニフェストファイル (`scalardl-client-pod.yaml`) を作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-client-pod.yaml + apiVersion: v1 + kind: Pod + metadata: + name: "scalardl-client" + spec: + containers: + - name: scalardl-client + image: eclipse-temurin:8-jdk + command: ['sleep'] + args: ['inf'] + env: + - name: SCALAR_DL_VERSION + value: SCALAR_DL_CLIENT_POD_SCALAR_DL_VERSION + volumeMounts: + - name: "client-ca-cert" + mountPath: "/certs/ca/ca.pem" + subPath: certificate + readOnly: true + volumes: + - name: "client-ca-cert" + secret: + secretName: "client-ca-cert" + restartPolicy: Never + EOF + ``` + +1. マニフェストファイルに ScalarDL のバージョンを設定します。 + + ```console + sed -i s/SCALAR_DL_CLIENT_POD_SCALAR_DL_VERSION/${SCALAR_DL_VERSION}/ ${HOME}/scalardl-test/scalardl-client-pod.yaml + ``` + +1. クライアントポッドをデプロイします。 + + ```console + kubectl apply -f ${HOME}/scalardl-test/scalardl-client-pod.yaml -n default + ``` + +1. クライアントコンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod scalardl-client -n default + ``` + + [コマンド実行結果] + + ```console + NAME READY STATUS RESTARTS AGE + scalardl-client 1/1 Running 0 4s + ``` + +## ステップ8. クライアントコンテナで ScalarDL サンプルコントラクトを実行する + +以下に最低限の手順を説明します。ScalarDL LedgerとScalarDL Auditorについて詳しく知りたい場合は、以下のドキュメントを参照してください。 + +* [ScalarDL 入門](https://scalardl.scalar-labs.com/docs/latest/getting-started/) +* [ScalarDL Auditor 入門](https://scalardl.scalar-labs.com/docs/latest/getting-started-auditor/) + +1. クライアントコンテナで bash を実行します。 + + ```console + kubectl exec -it scalardl-client -n default -- bash + ``` + 次の手順移行のコマンドは、クライアントコンテナ無いで実行する必要があります。 + +1. git、curl、および unzip コマンドをクライアントコンテナにインストールします。 + + ```console + apt update && apt install -y git curl unzip + ``` + +1. ScalarDL Java クライアント SDK git リポジトリのクローンを作成します。 + + ```console + git clone https://github.com/scalar-labs/scalardl-java-client-sdk.git + ``` + +1. ディレクトリを `scalardl-java-client-sdk/` に変更します。 + + ```console + cd scalardl-java-client-sdk/ + ``` + + ```console + pwd + ``` + + [コマンド実行結果] + + ```console + /scalardl-java-client-sdk + ``` + +1. ブランチを使用するバージョンに変更します。 + + ```console + git checkout -b v${SCALAR_DL_VERSION} refs/tags/v${SCALAR_DL_VERSION} + ``` + +1. サンプルコントラクトを作成します。 + + ```console + ./gradlew assemble + ``` + +1. ScalarDL の CLI ツールを [ScalarDL Java Client SDK Releases](https://github.com/scalar-labs/scalardl-java-client-sdk/releases) からダウンロードします。 + + ```console + curl -OL https://github.com/scalar-labs/scalardl-java-client-sdk/releases/download/v${SCALAR_DL_VERSION}/scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip + ``` + 同じバージョンの CLI ツールと ScalarDL Ledger を使用する必要があります。 + +1. `scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip` ファイルを解凍します。 + + ```console + unzip ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip + ``` + +1. Kubernetes クラスター上の ScalarDL Ledger および ScalarDL Auditor にアクセスするための構成ファイル (`client.properties`) を作成します。 + + ```console + cat << 'EOF' > client.properties + # Ledger configuration + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.client.tls.enabled=true + scalar.dl.client.tls.ca_root_cert_path=/certs/ca/ca.pem + scalar.dl.client.tls.override_authority=envoy.scalar.example.com + + # Auditor configuration + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + scalar.dl.client.auditor.tls.enabled=true + scalar.dl.client.auditor.tls.ca_root_cert_path=/certs/ca/ca.pem + scalar.dl.client.auditor.tls.override_authority=envoy.scalar.example.com + + # Client configuration + scalar.dl.client.authentication_method=hmac + scalar.dl.client.entity.id=client + scalar.dl.client.entity.identity.hmac.secret_key=scalardl-hmac-client-secert-key + EOF + ``` + +1. クライアントのシークレットを登録します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-secret --config ./client.properties + ``` + +1. サンプルコントラクト `StateUpdater` を登録します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id StateUpdater --contract-binary-name com.org1.contract.StateUpdater --contract-class-file ./build/classes/java/main/com/org1/contract/StateUpdater.class + ``` + +1. サンプルコントラクト `StateReader` を登録します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id StateReader --contract-binary-name com.org1.contract.StateReader --contract-class-file ./build/classes/java/main/com/org1/contract/StateReader.class + ``` + +1. 検証リクエストを実行するためのコントラクト `ValidateLedger` を登録します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id validate-ledger --contract-binary-name com.scalar.dl.client.contract.ValidateLedger --contract-class-file ./build/classes/java/main/com/scalar/dl/client/contract/ValidateLedger.class + ``` + +1. コントラクト `StateUpdater` を実行します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl execute-contract --config ./client.properties --contract-id StateUpdater --contract-argument '{"asset_id": "test_asset", "state": 3}' + ``` + このサンプルコントラクトは、`test_asset` という名前のアセットの `state` (値) を `3` に更新します。 + +1. コントラクト `StateReader` を実行します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl execute-contract --config ./client.properties --contract-id StateReader --contract-argument '{"asset_id": "test_asset"}' + ``` + + [コマンド実行結果] + + ```console + Contract result: + { + "id" : "test_asset", + "age" : 0, + "output" : { + "state" : 3 + } + } + ``` + + ### 参考情報 + + * 資産データが改ざんされていない場合、`execute-contract` コマンドを実行してコントラクトの実行を要求すると、結果として `OK` が返されます。 + * 資産データが改ざんされている場合 (たとえば、データベース内の `state` 値が改ざんされている場合)、コントラクトの実行を要求する `execute-contract` コマンドを実行すると、実行結果として `OK` 以外の値が返されます (たとえば、 `INCONSISTENT_STATES`)。ScalarDL がデータ改ざんを検出する方法の例として、以下を参照してください。 + + [コマンド実行結果 (資産データが改ざんされている場合) ] + + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + +1. アセットの検証リクエストを実行します。 + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl validate-ledger --config ./client.properties --asset-id "test_asset" + ``` + + [コマンド実行結果] + + ```console + { + "status_code" : "OK", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEYCIQDiiXqzw6K+Ml4uvn8rK43o5wHWESU3hoXnZPi6/OeKVwIhAM+tFBcapl6zg47Uq0Uc8nVNGWNHZLBDBGve3F0xkzTR" + }, + "Auditor" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEUCIQDLsfUR2PmxSvfpL3YvHJUkz00RDpjCdctkroZKXE8d5QIgH73FQH2e11jfnynD00Pp9DrIG1vYizxDsvxUsMPo9IU=" + } + } + ``` + + ### 参考情報 + + * 資産データが改ざんされていない場合、`validate-ledger` コマンドを実行して検証を要求すると、結果として `OK` が返されます。 + * 資産データが改ざんされている場合 (たとえば、データベース内の `state` 値が改ざんされている場合)、`validate-ledger` コマンドを実行して検証を要求すると、実行結果として `OK` 以外の値が返されます (たとえば、`INVALID_OUTPUT`)。ScalarDL がデータ改ざんを検出する方法の例として、以下を参照してください。 + + [コマンド実行結果 (資産データが改ざんされている場合) ] + + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + +## ステップ9. すべてのリソースを削除する + +Kubernetes クラスターで ScalarDL Ledger テストと ScalarDL Auditor テストを完了したら、すべてのリソースを削除します。 + +1. ScalarDL Ledger、ScalarDL Auditor、ScalarDL Schema Loader、および PostgreSQL をアンインストールします。 + + ```console + helm uninstall -n default scalardl-ledger schema-loader-ledger postgresql-ledger scalardl-auditor schema-loader-auditor postgresql-auditor + ``` + +1. クライアントコンテナを削除します。 + + ``` + kubectl delete pod scalardl-client --grace-period 0 -n default + ``` + +1. シークレットリソースを削除します。 + + ``` + kubectl delete secrets envoy-tls-key envoy-tls-cert schema-ledger-credentials-secret schema-auditor-credentials-secret ledger-credentials-secret scalardl-ledger-tls-ca scalardl-ledger-tls-cert scalardl-ledger-tls-key auditor-credentials-secret auditor-keys scalardl-auditor-tls-ca scalardl-auditor-tls-cert scalardl-auditor-tls-key scalardl-auditor-tls-ca-for-ledger client-ca-cert + ``` + +1. 作業ディレクトリとサンプルファイル (構成ファイル、秘密鍵、および証明書) を削除します。 + + ```console + cd ${HOME} + ``` + + ```console + rm -rf ${HOME}/scalardl-test/ + ``` + +## 参考文献 + +Scalar 製品の監視またはログ記録を開始する方法については、次のドキュメントで説明しています。 + +* [Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング)](getting-started-monitoring.mdx) +* [Helm Charts をはじめよう (Loki スタックを使用したロギング)](getting-started-logging.mdx) +* [Helm Charts をはじめよう (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor.mdx new file mode 100644 index 00000000..c0d3e9a1 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-auditor.mdx @@ -0,0 +1,913 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# Helm Charts をはじめよう (ScalarDL Ledger と Auditor / Auditor モード) + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Kubernetes クラスター上の Helm Chart をテスト環境として使用して、ScalarDL Ledger および Auditor を開始する方法について説明します。ここでは、テスト用の Mac または Linux 環境がすでにあることを前提としています。このドキュメントでは **Minikube** を使用しますが、これから説明する手順はどの Kubernetes クラスターでも機能するはずです。 + +## 要件 + +以下のコンテナイメージを取得するには、[AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-rzbuhxgvqf4d2) または [Azure Marketplace](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) でScalarDL Ledger および ScalarDL Auditor をサブスクライブする必要があります。 + * AWS Marketplace + * scalar-ledger + * scalar-ledger-envoy + * scalardl-schema-loader-ledger + * scalar-auditor + * scalar-auditor-envoy + * scalardl-schema-loader-auditor + * Azure Marketplace + * scalar-ledger + * scalar-auditor + * scalardl-envoy + * scalardl-schema-loader + +詳細については、以下のドキュメントを参照してください。 + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +## 注記 +監査によるビザンチン障害検出を適切に機能させるには、Ledger と Auditor を異なる管理ドメインに展開して管理する必要があります。ただし、このガイドでは、テストを容易にするために、Ledger と Auditor を同じ Kubernetes クラスターにデプロイします。 + +## 私たちが作るもの + +次のように、次のコンポーネントを Kubernetes クラスターにデプロイします。 + +``` ++-----------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes クラスター] | +| [ポッド] [ポッド] [ポッド] | +| | +| +-------+ +---------+ | +| +---> | Envoy | ---+ +---> | Ledger | ---+ | +| | +-------+ | | +---------+ | | +| | | | | | +| +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | サービス | ---+---> | Envoy | ---+---> | サービス | ---+---> | Ledger | ---+---> | PostgreSQL | | +| | | (Envoy) | | +-------+ | | (Ledger) | | +---------+ | | (Ledger 用) | | +| | +---------+ | | +-----------+ | | +---------------+ | +| | | +-------+ | | +---------+ | | +| | +---> | Envoy | ---+ +---> | Ledger | ---+ | +| +--------+ | +-------+ +---------+ | +| | クライアント | ---+ | +| +--------+ | +-------+ +---------+ | +| | +---> | Envoy | ---+ +---> | Auditor | ---+ | +| | | +-------+ | | +---------+ | | +| | | | | | | +| | +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | サービス | ---+---> | Envoy | ---+---> | サービス | ---+---> | Auditor | ---+---> | PostgreSQL | | +| | (Envoy) | | +-------+ | | (Auditor) | | +---------+ | | (Auditor 用) | | +| +---------+ | | +-----------+ | | +---------------+ | +| | +-------+ | | +---------+ | | +| +---> | Envoy | ---+ +---> | Auditor | ---+ | +| +-------+ +---------+ | +| | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +## ステップ1. Kubernetes クラスターを開始する + +まず、Kubernetes クラスターを準備する必要があります。**minikube** 環境を使用する場合は、[Scalar Helm Charts をはじめよう](./getting-started-scalar-helm-charts.mdx)を参照してください。すでに Kubernetes クラスターを開始している場合は、この手順をスキップできます。 + +## ステップ2. PostgreSQL コンテナーを開始する + +ScalarDL Ledger と Auditor は、バックエンドデータベースとして何らかのデータベースシステムを使用します。このドキュメントでは PostgreSQL を使用します。 + +次のようにして、Kubernetes クラスターに PostgreSQL をデプロイできます。 + +1. Bitnami Helm リポジトリを追加します。 + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Ledger 用に PostgreSQL をデプロイします。 + ```console + helm install postgresql-ledger bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. Auditor 用に PostgreSQL をデプロイします。 + ```console + helm install postgresql-auditor bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. PostgreSQL コンテナが実行されているかどうかを確認します。 + ```console + kubectl get pod + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 11s + postgresql-ledger-0 1/1 Running 0 16s + ``` + +## ステップ3. 作業ディレクトリを作成する + +いくつかの構成ファイルとキー/証明書ファイルをローカルに作成します。したがって、それらの作業ディレクトリを作成します。 + +1. 作業ディレクトリを作成します。 + ```console + mkdir -p ~/scalardl-test/certs/ + ``` + +## ステップ4. 秘密鍵/証明書ファイルを作成する + +注記:このガイドでは、テストに自己署名証明書を使用します。ただし、これらの証明書を運用環境では使用しないことを強くお勧めします。 + +1. 作業ディレクトリを `~/scalardl-test/certs/` ディレクトリに変更します。 + ```console + cd ~/scalardl-test/certs/ + ``` + +1. Ledger 情報を含む JSON ファイルを作成します。 + ```console + cat << 'EOF' > ~/scalardl-test/certs/ledger.json + { + "CN": "ledger", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "ledger", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. Auditor 情報を含む JSON ファイルを作成します。 + ```console + cat << 'EOF' > ~/scalardl-test/certs/auditor.json + { + "CN": "auditor", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "auditor", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. クライアント情報を含む JSON ファイルを作成します。 + ```console + cat << 'EOF' > ~/scalardl-test/certs/client.json + { + "CN": "client", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "client", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. Ledger のキー/証明書ファイルを作成します。 + ```console + cfssl selfsign "" ./ledger.json | cfssljson -bare ledger + ``` + +1. Auditor のキー/証明書ファイルを作成します。 + ```console + cfssl selfsign "" ./auditor.json | cfssljson -bare auditor + ``` + +1. クライアントのキー/証明書ファイルを作成します。 + ```console + cfssl selfsign "" ./client.json | cfssljson -bare client + ``` + +1. キー/証明書ファイルが作成されたことを確認します。 + ```console + ls -1 + ``` + 【コマンド実行結果】 + ```console + auditor-key.pem + auditor.csr + auditor.json + auditor.pem + client-key.pem + client.csr + client.json + client.pem + ledger-key.pem + ledger.csr + ledger.json + ledger.pem + ``` + +## ステップ5. Helm Charts を使用して ScalarDL Ledger と ScalarDL Auditor の DB スキーマを作成する + +Helm Chart を使用して、Kubernetes クラスターに2つの ScalarDL Schema Loader ポッドをデプロイします。 +ScalarDL Schema Loader は、PostgreSQL で ScalarDL Ledger と Auditor の DB スキーマを作成します。 + +1. 作業ディレクトリを `~/scalardl-test/` に変更します。 + ```console + cd ~/scalardl-test/ + ``` + +1. Scalar helm リポジトリを追加します。 + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. AWS/Azure Marketplace から ScalarDL コンテナーイメージをプルするためのシークレットリソースを作成します。 + * AWS Marketplace + ```console + kubectl create secret docker-registry reg-ecr-mp-secrets \ + --docker-server=709825985650.dkr.ecr.us-east-1.amazonaws.com \ + --docker-username=AWS \ + --docker-password=$(aws ecr get-login-password --region us-east-1) + ``` + * Azure Marketplace + ```console + kubectl create secret docker-registry reg-acr-secrets \ + --docker-server= \ + --docker-username= \ + --docker-password= + ``` + + 詳細については、以下のドキュメントを参照してください。 + + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +1. ScalarDL Schema Loader for Ledger のカスタム値ファイル (schema-loader-ledger-custom-values.yaml) を作成します。 + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-schema-loader-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "ledger-credentials-secret" + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + image: + repository: "/scalarinc/scalardl-schema-loader" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "ledger-credentials-secret" + EOF + ``` + +1. Auditor 用の ScalarDL Schema Loader のカスタム値ファイル (schema-loader-auditor-custom-values.yaml) を作成します。 + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-auditor-custom-values.yaml + schemaLoading: + schemaType: "auditor" + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-schema-loader-auditor" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "auditor-credentials-secret" + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-auditor-custom-values.yaml + schemaLoading: + schemaType: "auditor" + image: + repository: "/scalarinc/scalardl-schema-loader" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "auditor-credentials-secret" + EOF + ``` + +1. PostgreSQL for Ledger のユーザー名とパスワードを含むシークレットリソースを作成します。 + ```console + kubectl create secret generic ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres + ``` + +1. PostgreSQL for Auditor のユーザー名とパスワードを含むシークレットリソースを作成します。 + ```console + kubectl create secret generic auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres + ``` + +1. Ledger 用の ScalarDL Schema Loader をデプロイします。 + ```console + helm install schema-loader-ledger scalar-labs/schema-loading -f ./schema-loader-ledger-custom-values.yaml + ``` + +1. Auditor 用の ScalarDL Schema Loader をデプロイします。 + ```console + helm install schema-loader-auditor scalar-labs/schema-loading -f ./schema-loader-auditor-custom-values.yaml + ``` + +1. ScalarDL Schema Loader ポッドがデプロイされ、完了しているかどうかを確認します。 + ```console + kubectl get pod + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 2m56s + postgresql-ledger-0 1/1 Running 0 3m1s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 6s + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 10s + ``` + ScalarDL Schema Loader ポッドが **ContainerCreating** または **Running** の場合は、プロセスが完了するまで待ちます (STATUS は **Completed** になります)。 + +## ステップ6. Helm Chart を使用して Kubernetes クラスターに ScalarDL Ledger と Auditor をデプロイする + +1. ScalarDL Ledger のカスタム値ファイル (scalardl-ledger-custom-values.yaml) を作成します。 + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ledgerProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + secretName: "ledger-credentials-secret" + extraVolumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + extraVolumeMounts: + - name: "ledger-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + image: + repository: "/scalarinc/scalardl-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-acr-secrets" + + ledger: + image: + repository: "/scalarinc/scalar-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + ledgerProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + secretName: "ledger-credentials-secret" + extraVolumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + extraVolumeMounts: + - name: "ledger-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + +1. ScalarDL Auditor のカスタム値ファイル (scalardl-auditor-custom-values.yaml) を作成します。 + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-auditor-custom-values.yaml + envoy: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-auditor-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + + auditor: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-auditor" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + auditorProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.auditor.ledger.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.auditor.cert_path=/keys/certificate + scalar.dl.auditor.private_key_path=/keys/private-key + secretName: "auditor-credentials-secret" + extraVolumes: + - name: "auditor-keys" + secret: + secretName: "auditor-keys" + extraVolumeMounts: + - name: "auditor-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-auditor-custom-values.yaml + envoy: + image: + repository: "/scalarinc/scalardl-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-acr-secrets" + + auditor: + image: + repository: "/scalarinc/scalar-auditor" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + auditorProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.auditor.ledger.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.auditor.cert_path=/keys/certificate + scalar.dl.auditor.private_key_path=/keys/private-key + secretName: "auditor-credentials-secret" + extraVolumes: + - name: "auditor-keys" + secret: + secretName: "auditor-keys" + extraVolumeMounts: + - name: "auditor-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + +1. シークレットリソース `ledger-keys` を作成します。 + ```console + kubectl create secret generic ledger-keys --from-file=certificate=./certs/ledger.pem --from-file=private-key=./certs/ledger-key.pem + ``` + +1. シークレットリソース `auditor-keys` を作成します。 + ```console + kubectl create secret generic auditor-keys --from-file=certificate=./certs/auditor.pem --from-file=private-key=./certs/auditor-key.pem + ``` + +1. ScalarDL Ledger をデプロイします。 + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + +1. ScalarDL Auditor をデプロイします。 + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + +1. ScalarDL Ledger および Auditor ポッドがデプロイされているかどうかを確認します。 + ```console + kubectl get pod + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 14m + postgresql-ledger-0 1/1 Running 0 14m + scalardl-auditor-auditor-5b885ff4c8-fwkpf 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-g69cb 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-nsmnq 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-5mn6v 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-fpq8j 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-lsz2t 1/1 Running 0 18s + scalardl-ledger-envoy-547bbf7546-n7p5x 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-p8nwp 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-pskpb 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-5zsbj 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-vnmrw 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-wpjvs 1/1 Running 0 26s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 11m + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 11m + ``` + ScalarDL Ledger および Auditor ポッドが適切にデプロイされている場合、STATUS が **Running** であることがわかります。 + +1. ScalarDL Ledger サービスと Auditor サービスがデプロイされているかどうかを確認します。 + ```console + kubectl get svc + ``` + 【コマンド実行結果】 + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-auditor ClusterIP 10.107.9.78 5432/TCP 15m + postgresql-auditor-hl ClusterIP None 5432/TCP 15m + postgresql-ledger ClusterIP 10.108.241.181 5432/TCP 15m + postgresql-ledger-hl ClusterIP None 5432/TCP 15m + scalardl-auditor-envoy ClusterIP 10.100.61.202 40051/TCP,40052/TCP 55s + scalardl-auditor-envoy-metrics ClusterIP 10.99.6.227 9001/TCP 55s + scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 55s + scalardl-auditor-metrics ClusterIP 10.108.1.147 8080/TCP 55s + scalardl-ledger-envoy ClusterIP 10.101.191.116 50051/TCP,50052/TCP 61s + scalardl-ledger-envoy-metrics ClusterIP 10.106.52.103 9001/TCP 61s + scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 61s + scalardl-ledger-metrics ClusterIP 10.99.122.106 8080/TCP 61s + ``` + ScalarDL Ledger サービスと Auditor サービスが適切にデプロイされている場合は、CLUSTER-IP 列にプライベート IP アドレスが表示されます。(注記: `scalardl-ledger-headless` と `scalardl-auditor-headless` には CLUSTER-IP がありません。) + +## ステップ7. クライアントコンテナを開始する + +クライアントコンテナで証明書ファイルを使用します。そこで、シークレットリソースを作成し、クライアントコンテナにマウントします。 + +1. シークレットリソース `client-keys` を作成します。 + ``` + kubectl create secret generic client-keys --from-file=certificate=./certs/client.pem --from-file=private-key=./certs/client-key.pem + ``` + +1. Kubernetes クラスター上でクライアントコンテナーを起動します。 + ```console + cat << 'EOF' | kubectl apply -f - + apiVersion: v1 + kind: Pod + metadata: + name: "scalardl-client" + spec: + containers: + - name: scalardl-client + image: eclipse-temurin:8-jdk + command: ['sleep'] + args: ['inf'] + volumeMounts: + - name: "ledger-keys" + mountPath: "/keys/ledger" + readOnly: true + - name: "auditor-keys" + mountPath: "/keys/auditor" + readOnly: true + - name: "client-keys" + mountPath: "/keys/client" + readOnly: true + volumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + - name: "auditor-keys" + secret: + secretName: "auditor-keys" + - name: "client-keys" + secret: + secretName: "client-keys" + restartPolicy: Never + EOF + ``` + +1. クライアントコンテナが実行されているかどうかを確認します。 + ```console + kubectl get pod scalardl-client + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + scalardl-client 1/1 Running 0 4s + ``` + +## ステップ8. クライアントコンテナで ScalarDL サンプルコントラクトを実行する + +以下に最低限の手順を説明します。ScalarDL Ledger と Auditor について詳しく知りたい場合は、以下のドキュメントを参照してください。 + * [Getting Started with ScalarDL](https://scalardl.scalar-labs.com/ja-jp/docs/latest/getting-started) + * [Getting Started with ScalarDL Auditor](https://scalardl.scalar-labs.com/ja-jp/docs/latest/getting-started-auditor) + +Auditor を使用する場合、クライアントアプリケーションを起動する前に Ledger と Auditor の証明書を登録する必要があります。Ledger はその証明書を Auditor に登録する必要があり、Auditor はその証明書を Ledger に登録する必要があります。 + +1. クライアントコンテナで bash を実行します。 + ```console + kubectl exec -it scalardl-client -- bash + ``` + この手順の後、クライアントコンテナで各コマンドを実行します。 + +1. git、curl、および unzip コマンドをクライアントコンテナにインストールします。 + ```console + apt update && apt install -y git curl unzip + ``` + +1. ScalarDL Java Client SDK git リポジトリのクローンを作成します。 + ```console + git clone https://github.com/scalar-labs/scalardl-java-client-sdk.git + ``` + +1. ディレクトリを `scalardl-java-client-sdk/` に変更します。 + ```console + cd scalardl-java-client-sdk/ + ``` + ```console + pwd + ``` + 【コマンド実行結果】 + ```console + + /scalardl-java-client-sdk + ``` + +1. ブランチを任意のバージョンに変更します。 + ```console + git checkout -b v3.6.0 refs/tags/v3.6.0 + ``` + ```console + git branch + ``` + 【コマンド実行結果】 + ```console + master + * v3.6.0 + ``` + 別のバージョンを使用する場合は、使用するバージョン (タグ) を指定してください。同じバージョンの ScalarDL Ledger と ScalarDL Java Client SDK を使用する必要があります。 + +1. サンプルコントラクトを作成します。 + ```console + ./gradlew assemble + ``` + +1. ScalarDL の CLI ツールは [ScalarDL Java Client SDK Releases](https://github.com/scalar-labs/scalardl-java-client-sdk/releases) からダウンロードしてください。 + ```console + curl -OL https://github.com/scalar-labs/scalardl-java-client-sdk/releases/download/v3.6.0/scalardl-java-client-sdk-3.6.0.zip + ``` + 同じバージョンの CLI ツールと ScalarDL Ledger を使用する必要があります。 + +1. `scalardl-java-client-sdk-3.6.0.zip` ファイルを解凍します。 + ```console + unzip ./scalardl-java-client-sdk-3.6.0.zip + ``` + +1. Ledger の証明書を Auditor に登録するための設定ファイル(ledger.as.client.properties)を作成します。 + ```console + cat << 'EOF' > ledger.as.client.properties + # Ledger + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + + # Certificate + scalar.dl.client.cert_holder_id=ledger + scalar.dl.client.cert_path=/keys/ledger/certificate + scalar.dl.client.private_key_path=/keys/ledger/private-key + EOF + ``` + +1. Auditor の証明書を Ledger に登録するための設定ファイル(auditor.as.client.properties)を作成します。 + ```console + cat << 'EOF' > auditor.as.client.properties + # Ledger + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + + # Certificate + scalar.dl.client.cert_holder_id=auditor + scalar.dl.client.cert_path=/keys/auditor/certificate + scalar.dl.client.private_key_path=/keys/auditor/private-key + EOF + ``` + +1. Kubernetes クラスター上の ScalarDL Ledger にアクセスするための構成ファイル (client.properties) を作成します。 + ```console + cat << 'EOF' > client.properties + # Ledger + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + + # Certificate + scalar.dl.client.cert_holder_id=client + scalar.dl.client.cert_path=/keys/client/certificate + scalar.dl.client.private_key_path=/keys/client/private-key + EOF + ``` + +1. Ledger の証明書ファイルを登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-cert --properties ./ledger.as.client.properties + ``` + +1. Auditor の証明書ファイルを登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-cert --properties ./auditor.as.client.properties + ``` + +1. クライアントの証明書ファイルを登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-cert --properties ./client.properties + ``` + +1. サンプルコントラクト `StateUpdater` を登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id StateUpdater --contract-binary-name com.org1.contract.StateUpdater --contract-class-file ./build/classes/java/main/com/org1/contract/StateUpdater.class + ``` + +1. サンプルコントラクト `StateReader` を登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id StateReader --contract-binary-name com.org1.contract.StateReader --contract-class-file ./build/classes/java/main/com/org1/contract/StateReader.class + ``` + +1. 検証リクエストを実行するためのコントラクト `ValdateLedger` を登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id validate-ledger --contract-binary-name com.scalar.dl.client.contract.ValidateLedger --contract-class-file ./build/classes/java/main/com/scalar/dl/client/contract/ValidateLedger.class + ``` + +1. コントラクト `StateUpdater` を実行します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/execute-contract --properties ./client.properties --contract-id StateUpdater --contract-argument '{"asset_id": "test_asset", "state": 3}' + ``` + このサンプルコントラクトは、`test_asset` という名前のアセットの `state` (値) を `3` に更新します。 + +1. コントラクト `StateReader` を実行します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/execute-contract --properties ./client.properties --contract-id StateReader --contract-argument '{"asset_id": "test_asset"}' + ``` + 【コマンド実行結果】 + ```console + Contract result: + { + "id" : "test_asset", + "age" : 0, + "output" : { + "state" : 3 + } + } + ``` + * 参考情報 + * 資産データが改ざんされていない場合、コントラクト実行要求 (execute-contract コマンド) は結果として `OK` を返します。 + * 資産データが改ざんされている場合 (例: DB の `state` 値が改ざんされている場合) 、コントラクト実行要求 (execute-contract コマンド) は結果として `OK` 以外の値 (例:`INCONSISTENT_STATES`) を返す , 以下のような感じです。 + 【コマンド実行結果 (資産データが改ざんされた場合) 】 + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + * このようにして、ScalarDL はデータの改ざんを検出できます。 + +1. アセットの検証リクエストを実行します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/validate-ledger --properties ./client.properties --asset-id "test_asset" + ``` + 【コマンド実行結果】 + ```console + { + "status_code" : "OK", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEYCIQDiiXqzw6K+Ml4uvn8rK43o5wHWESU3hoXnZPi6/OeKVwIhAM+tFBcapl6zg47Uq0Uc8nVNGWNHZLBDBGve3F0xkzTR" + }, + "Auditor" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEUCIQDLsfUR2PmxSvfpL3YvHJUkz00RDpjCdctkroZKXE8d5QIgH73FQH2e11jfnynD00Pp9DrIG1vYizxDsvxUsMPo9IU=" + } + } + ``` + * 参考情報 + * 資産データが改ざんされていない場合、検証リクエスト (validate-ledger コマンド) は結果として `OK` を返します。 + * 資産データが改ざんされている場合 (例: DB の `state` 値が改ざんされている場合) 、検証リクエスト (validate-ledger コマンド) は結果として `OK` 以外の値 (例: `INVALID_OUTPUT`) を返します。以下のような。 + 【コマンド実行結果 (資産データが改ざんされた場合) 】 + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + * このようにして、ScalarDL Ledger はデータの改ざんを検出できます。 + +## ステップ9. すべてのリソースを削除する + +Kubernetes クラスターで ScalarDL Ledger テストを完了したら、すべてのリソースを削除します。 + +1. ScalarDL Ledger、ScalarDL Schema Loader、PostgreSQL をアンインストールします。 + ```console + helm uninstall scalardl-ledger schema-loader-ledger postgresql-ledger scalardl-auditor schema-loader-auditor postgresql-auditor + ``` + +1. クライアントコンテナを削除します。 + ``` + kubectl delete pod scalardl-client --force --grace-period 0 + ``` + +1. 作業ディレクトリとサンプルファイル (構成ファイル、秘密鍵、証明書) を削除します。 + ```console + cd ~ + ``` + ```console + rm -rf ~/scalardl-test/ + ``` + +## 参考文献 + +Scalar 製品の監視またはログ記録を開始する方法については、次のドキュメントで説明しています。 + +* [Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング)](getting-started-monitoring.mdx) +* [Helm Charts をはじめよう (Loki スタックを使用したロギング)](getting-started-logging.mdx) +* [Helm Charts をはじめよう (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-ledger.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-ledger.mdx new file mode 100644 index 00000000..c4641a39 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/getting-started-scalardl-ledger.mdx @@ -0,0 +1,618 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# Helm Charts をはじめよう (ScalarDL Ledger / Ledger のみ) + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Kubernetes クラスター上の Helm Chart をテスト環境として使用して、ScalarDL Ledger を開始する方法について説明します。ここでは、テスト用の Mac または Linux 環境がすでにあることを前提としています。このドキュメントでは **Minikube** を使用しますが、これから説明する手順はどの Kubernetes クラスターでも機能するはずです。 + +## 要件 + +以下のコンテナイメージを入手するには、[AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-rzbuhxgvqf4d2) または [Azure Marketplace](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) でScalarDL Ledgerを購読する必要があります。 + * AWS Marketplace + * scalar-ledger + * scalar-ledger-envoy + * scalardl-schema-loader-ledger + * Azure Marketplace + * scalar-ledger + * scalardl-envoy + * scalardl-schema-loader + +詳細については、以下のドキュメントを参照してください。 + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +## 私たちが作るもの + +次のように、次のコンポーネントを Kubernetes クラスターにデプロイします。 + +``` ++--------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes クラスター] | +| | +| [ポッド] [ポッド] [ポッド] [ポッド] | +| | +| +-------+ +-----------------+ | +| +---> | Envoy | ---+ +---> | ScalarDL Ledger | ---+ | +| | +-------+ | | +-----------------+ | | +| | | | | | +| +--------+ +---------+ | +-------+ | +-------------------+ | +-----------------+ | +------------+ | +| | クライアント | ---> | サービス | ---+---> | Envoy | ---+---> | サービス | ---+---> | ScalarDL Ledger | ---+---> | PostgreSQL | | +| +--------+ | (Envoy) | | +-------+ | | (ScalarDL Ledger) | | +-----------------+ | +------------+ | +| +---------+ | | +-------------------+ | | | +| | +-------+ | | +-----------------+ | | +| +---> | Envoy | ---+ +---> | ScalarDL Ledger | ---+ | +| +-------+ +-----------------+ | +| | ++--------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ステップ1. Kubernetes クラスターを開始する + +まず、Kubernetes クラスターを準備する必要があります。**minikube** 環境を使用する場合は、[Scalar Helm Charts をはじめよう](./getting-started-scalar-helm-charts.mdx)を参照してください。すでに Kubernetes クラスターを開始している場合は、この手順をスキップできます。 + +## ステップ2. PostgreSQL コンテナーを開始する + +ScalarDL Ledger は、バックエンドデータベースとして何らかのデータベースシステムを使用します。このドキュメントでは PostgreSQL を使用します。 + +次のようにして、Kubernetes クラスターに PostgreSQL をデプロイできます。 + +1. Bitnami Helm リポジトリを追加します。 + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. PostgreSQLをデプロイします。 + ```console + helm install postgresql-ledger bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. PostgreSQL コンテナが実行されているかどうかを確認します。 + ```console + kubectl get pod + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + postgresql-ledger-0 1/1 Running 0 11s + ``` + +## ステップ3. 作業ディレクトリを作成する + +いくつかの構成ファイルとキー/証明書ファイルをローカルに作成します。したがって、それらの作業ディレクトリを作成します。 + +1. 作業ディレクトリを作成します。 + ```console + mkdir -p ~/scalardl-test/certs/ + ``` + +## ステップ4. キー/証明書ファイルを作成する + +注記:このガイドでは、テストに自己署名証明書を使用します。ただし、これらの証明書を運用環境では使用しないことを強くお勧めします。 + +1. 作業ディレクトリを `~/scalardl-test/certs/` ディレクトリに変更します。 + ```console + cd ~/scalardl-test/certs/ + ``` + +1. Ledger 情報を含む JSON ファイルを作成します。 + ```console + cat << 'EOF' > ~/scalardl-test/certs/ledger.json + { + "CN": "ledger", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "ledger", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. クライアント情報を含む JSON ファイルを作成します。 + ```console + cat << 'EOF' > ~/scalardl-test/certs/client.json + { + "CN": "client", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "client", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. Ledger のキー/証明書ファイルを作成します。 + ```console + cfssl selfsign "" ./ledger.json | cfssljson -bare ledger + ``` + +1. クライアントのキー/証明書ファイルを作成します。 + ```console + cfssl selfsign "" ./client.json | cfssljson -bare client + ``` + +1. キー/証明書ファイルが作成されたことを確認します。 + ```console + ls -1 + ``` + 【コマンド実行結果】 + ```console + client-key.pem + client.csr + client.json + client.pem + ledger-key.pem + ledger.csr + ledger.json + ledger.pem + ``` + +## ステップ5. Helm Charts を使用して ScalarDL Ledger の DB スキーマを作成する + +Helm Charts を使用して、ScalarDL Schema Loader を Kubernetes クラスターにデプロイします。 +ScalarDL Schema Loader は、PostgreSQL で ScalarDL Ledger の DB スキーマを作成します。 + +1. 作業ディレクトリを `~/scalardl-test/` に変更します。 + ```console + cd ~/scalardl-test/ + ``` + +1. Scalar helm リポジトリを追加します。 + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. AWS/Azure Marketplace から ScalarDL コンテナーイメージをプルするためのシークレットリソースを作成します。 + * AWS Marketplace + ```console + kubectl create secret docker-registry reg-ecr-mp-secrets \ + --docker-server=709825985650.dkr.ecr.us-east-1.amazonaws.com \ + --docker-username=AWS \ + --docker-password=$(aws ecr get-login-password --region us-east-1) + ``` + * Azure Marketplace + ```console + kubectl create secret docker-registry reg-acr-secrets \ + --docker-server= \ + --docker-username= \ + --docker-password= + ``` + + 詳細については、以下のドキュメントを参照してください。 + + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +1. ScalarDL Schema Loader のカスタム値ファイル (schema-loader-ledger-custom-values.yaml) を作成します。 + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-schema-loader-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "ledger-credentials-secret" + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + image: + repository: "/scalarinc/scalardl-schema-loader" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "ledger-credentials-secret" + EOF + ``` + +1. PostgreSQL のユーザー名とパスワードを含むシークレットリソースを作成します。 + ```console + kubectl create secret generic ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres + ``` + +1. ScalarDL Schema Loader をデプロイします。 + ```console + helm install schema-loader-ledger scalar-labs/schema-loading -f ./schema-loader-ledger-custom-values.yaml + ``` + +1. ScalarDL Schema Loader ポッドがデプロイされ、完了しているかどうかを確認します。 + ```console + kubectl get pod + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + postgresql-ledger-0 1/1 Running 0 11m + schema-loader-ledger-schema-loading-46rcr 0/1 Completed 0 3s + ``` + ScalarDL Schema Loader ポッドが **ContainerCreating** または **Running** の場合は、プロセスが完了するまで待ちます (STATUS は **Completed** になります)。 + +## ステップ6. Helm Charts を使用して Kubernetes クラスターに ScalarDL Ledger をデプロイする + +1. ScalarDL Ledger のカスタム値ファイル (scalardl-ledger-custom-values.yaml) を作成します。 + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ledgerProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + secretName: "ledger-credentials-secret" + extraVolumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + extraVolumeMounts: + - name: "ledger-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + image: + repository: "/scalarinc/scalardl-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-acr-secrets" + + ledger: + image: + repository: "/scalarinc/scalar-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + ledgerProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + secretName: "ledger-credentials-secret" + extraVolumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + extraVolumeMounts: + - name: "ledger-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + +1. シークレットリソース `ledger-keys` を作成します。 + ```console + kubectl create secret generic ledger-keys --from-file=private-key=./certs/ledger-key.pem + ``` + +1. ScalarDL Ledger をデプロイします。 + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + +1. ScalarDL Ledger ポッドがデプロイされているかどうかを確認します。 + ```console + kubectl get pod + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + postgresql-ledger-0 1/1 Running 0 14m + scalardl-ledger-envoy-547bbf7546-6cn88 1/1 Running 0 52s + scalardl-ledger-envoy-547bbf7546-rpg5p 1/1 Running 0 52s + scalardl-ledger-envoy-547bbf7546-x2vlg 1/1 Running 0 52s + scalardl-ledger-ledger-9bdf7f8bd-29bzm 1/1 Running 0 52s + scalardl-ledger-ledger-9bdf7f8bd-9fklw 1/1 Running 0 52s + scalardl-ledger-ledger-9bdf7f8bd-9tw5x 1/1 Running 0 52s + schema-loader-ledger-schema-loading-46rcr 0/1 Completed 0 3m38s + ``` + ScalarDL Ledger ポッドが適切にデプロイされている場合、STATUS が **Running** であることがわかります。 + +1. ScalarDL Ledger サービスがデプロイされているかどうかを確認します。 + ```console + kubectl get svc + ``` + 【コマンド実行結果】 + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-ledger ClusterIP 10.109.253.150 5432/TCP 15m + postgresql-ledger-hl ClusterIP None 5432/TCP 15m + scalardl-ledger-envoy ClusterIP 10.106.141.153 50051/TCP,50052/TCP 83s + scalardl-ledger-envoy-metrics ClusterIP 10.108.36.136 9001/TCP 83s + scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 83s + scalardl-ledger-metrics ClusterIP 10.98.4.217 8080/TCP 83s + ``` + ScalarDL Ledger サービスが適切にデプロイされている場合は、CLUSTER-IP 列にプライベート IP アドレスが表示されます。(注記: `scalardl-ledger-headless` には CLUSTER-IP がありません。) + +## ステップ7. クライアントコンテナを開始する + +クライアントコンテナで証明書ファイルを使用します。そこで、シークレットリソースを作成し、クライアントコンテナにマウントします。 + +1. シークレットリソース `client-keys` を作成します。 + ``` + kubectl create secret generic client-keys --from-file=certificate=./certs/client.pem --from-file=private-key=./certs/client-key.pem + ``` + +1. Kubernetes クラスター上でクライアントコンテナーを起動します。 + ```console + cat << 'EOF' | kubectl apply -f - + apiVersion: v1 + kind: Pod + metadata: + name: "scalardl-client" + spec: + containers: + - name: scalardl-client + image: eclipse-temurin:8-jdk + command: ['sleep'] + args: ['inf'] + volumeMounts: + - name: "client-keys" + mountPath: "/keys" + readOnly: true + volumes: + - name: "client-keys" + secret: + secretName: "client-keys" + restartPolicy: Never + EOF + ``` + +1. クライアントコンテナが実行されているかどうかを確認します。 + ```console + kubectl get pod scalardl-client + ``` + 【コマンド実行結果】 + ```console + NAME READY STATUS RESTARTS AGE + scalardl-client 1/1 Running 0 11s + ``` + +## ステップ8. クライアントコンテナで ScalarDL サンプルコントラクトを実行する + +以下に最低限の手順を説明します。ScalarDL の詳細やコントラクトについて知りたい場合は、[Getting Started with ScalarDL](https://scalardl.scalar-labs.com/ja-jp/docs/latest/getting-started) をご覧ください。 + +1. クライアントコンテナで bash を実行します。 + ```console + kubectl exec -it scalardl-client -- bash + ``` + この手順の後、クライアントコンテナで各コマンドを実行します。 + +1. git、curl、および unzip コマンドをクライアントコンテナにインストールします。 + ```console + apt update && apt install -y git curl unzip + ``` + +1. ScalarDL Java Client SDK git リポジトリのクローンを作成します。 + ```console + git clone https://github.com/scalar-labs/scalardl-java-client-sdk.git + ``` + +1. ディレクトリを `scalardl-java-client-sdk/` に変更します。 + ```console + cd scalardl-java-client-sdk/ + ``` + ```console + pwd + ``` + 【コマンド実行結果】 + ```console + + /scalardl-java-client-sdk + ``` + +1. ブランチを任意のバージョンに変更します。 + ```console + git checkout -b v3.6.0 refs/tags/v3.6.0 + ``` + ```console + git branch + ``` + 【コマンド実行結果】 + ```console + master + * v3.6.0 + ``` + 別のバージョンを使用する場合は、使用するバージョン (タグ) を指定してください。同じバージョンの ScalarDL Ledger と ScalarDL Java Client SDK を使用する必要があります。 + +1. サンプルコントラクトを作成します。 + ```console + ./gradlew assemble + ``` + +1. ScalarDL の CLI ツールは [ScalarDL Java Client SDK Releases](https://github.com/scalar-labs/scalardl-java-client-sdk/releases) からダウンロードしてください。 + ```console + curl -OL https://github.com/scalar-labs/scalardl-java-client-sdk/releases/download/v3.6.0/scalardl-java-client-sdk-3.6.0.zip + ``` + 同じバージョンの CLI ツールと ScalarDL Ledger を使用する必要があります。 + +1. `scalardl-java-client-sdk-3.6.0.zip` ファイルを解凍します。 + ```console + unzip ./scalardl-java-client-sdk-3.6.0.zip + ``` + +1. Kubernetes クラスター上の ScalarDL Ledger にアクセスするための構成ファイル (client.properties) を作成します。 + ```console + cat << 'EOF' > client.properties + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.client.cert_holder_id=client + scalar.dl.client.cert_path=/keys/certificate + scalar.dl.client.private_key_path=/keys/private-key + EOF + ``` + +1. クライアントの証明書ファイルを登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-cert --properties ./client.properties + ``` + +1. サンプルコントラクト`StateUpdater`を登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id StateUpdater --contract-binary-name com.org1.contract.StateUpdater --contract-class-file ./build/classes/java/main/com/org1/contract/StateUpdater.class + ``` + +1. サンプルコントラクト`StateReader`を登録します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id StateReader --contract-binary-name com.org1.contract.StateReader --contract-class-file ./build/classes/java/main/com/org1/contract/StateReader.class + ``` + +1. コントラクト`StateUpdater`を実行します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/execute-contract --properties ./client.properties --contract-id StateUpdater --contract-argument '{"asset_id": "test_asset", "state": 3}' + ``` + このサンプルコントラクトは、`test_asset` という名前のアセットの `state` (値) を `3` に更新します。 + +1. コントラクト `StateReader` を実行します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/execute-contract --properties ./client.properties --contract-id StateReader --contract-argument '{"asset_id": "test_asset"}' + ``` + 【コマンド実行結果】 + ```console + Contract result: + { + "id" : "test_asset", + "age" : 0, + "output" : { + "state" : 3 + } + } + ``` + +1. アセットの検証リクエストを実行します。 + ```console + ./scalardl-java-client-sdk-3.6.0/bin/validate-ledger --properties ./client.properties --asset-id "test_asset" + ``` + 【コマンド実行結果】 + ```console + { + "status_code" : "OK", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "f31599c6-e6b9-4b77-adc3-61cb5f119bd3", + "hash" : "9ExfFl5Lg9IQwdXdW9b87Bi+PWccn3OSNRbhmI/dboo=", + "signature" : "MEQCIG6Xa4WOWGMIIbA3PnCje4aAapYfCMerF54xRW0gaUuzAiBCA1nCAPoFWgxArB34/u9b+KeoxQBMALI/pOzMNoLExg==" + }, + "Auditor" : null + } + ``` + * 参考情報 + * 資産データが改ざんされていない場合、検証リクエスト (validate-ledger コマンド) は結果として `OK` を返します。 + * 資産データが改ざんされている場合 (例: DB の `state` 値が改ざんされている場合)、検証リクエスト (validate-ledger コマンド) は結果として `OK` 以外の値 (例:`INVALID_OUTPUT`) を返します。以下のような。 + 【コマンド実行結果 (資産データが改ざんされた場合) 】 + ```console + { + "status_code" : "INVALID_OUTPUT", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "f31599c6-e6b9-4b77-adc3-61cb5f119bd3", + "hash" : "9ExfFl5Lg9IQwdXdW9b87Bi+PWccn3OSNRbhmI/dboo=", + "signature" : "MEQCIGtJerW7N93c/bvIBy/7NXxoQwGFznHMmV6RzsgHQg0dAiBu+eBxkfmMQKJY2d9fLNvCH+4b+9rl7gZ3OXJ2NYeVsA==" + }, + "Auditor" : null + } + ``` + * このようにして、ScalarDL Ledger はデータの改ざんを検出できます。 + +## ステップ9. すべてのリソースを削除する + +Kubernetes クラスターで ScalarDL Ledger テストを完了したら、すべてのリソースを削除します。 + +1. ScalarDL Ledger、ScalarDL Schema Loader、PostgreSQL をアンインストールします。 + ```console + helm uninstall scalardl-ledger schema-loader-ledger postgresql-ledger + ``` + +1. クライアントコンテナを削除します。 + ``` + kubectl delete pod scalardl-client --force --grace-period 0 + ``` + +1. 作業ディレクトリとサンプルファイル (構成ファイル、秘密鍵、証明書) を削除します。 + ```console + cd ~ + ``` + ```console + rm -rf ~/scalardl-test/ + ``` + +## 参考文献 + +Scalar 製品の監視またはログ記録を開始する方法については、次のドキュメントで説明しています。 + +* [Helm Charts をはじめよう (Prometheus Operator を使用したモニタリング)](getting-started-monitoring.mdx) +* [Helm Charts をはじめよう (Loki スタックを使用したロギング)](getting-started-logging.mdx) +* [Helm Charts をはじめよう (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalar-admin-for-kubernetes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalar-admin-for-kubernetes.mdx new file mode 100644 index 00000000..447e0ad3 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalar-admin-for-kubernetes.mdx @@ -0,0 +1,38 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes 用に Scalar Admin をデプロイする方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Scalar Helm Chart を使用して Kubernetes に Scalar Admin をデプロイする方法について説明します。Scalar Admin for Kubernetes のカスタム値ファイルの詳細については、[Scalar Admin for Kubernetes のカスタム値ファイルの構成](configure-custom-values-scalar-admin-for-kubernetes.mdx)を参照してください。 + +## Kubernetes 用の Scalar Admin をデプロイする + +Scalar Admin for Kubernetes をデプロイするには、次のコマンドを実行します。山かっこ内の内容を説明どおりに置き換えます。 + +```console +helm install scalar-labs/scalar-admin-for-kubernetes -n -f / --version +``` + +## Scalar Admin for Kubernetes ジョブをアップグレードする + +Scalar Admin for Kubernetes ジョブをアップグレードするには、次のコマンドを実行して、山かっこ内の内容を説明どおりに置き換えます。 + +```console +helm upgrade scalar-labs/scalar-admin-for-kubernetes -n -f / --version +``` + +## Scalar Admin for Kubernetes ジョブを削除する + +Scalar Admin for Kubernetes ジョブを削除するには、次のコマンドを実行して、山括弧内の内容を説明どおりに置き換えます。 + +```console +helm uninstall -n +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalar-products.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalar-products.mdx new file mode 100644 index 00000000..a3f1a9d3 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalar-products.mdx @@ -0,0 +1,71 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar Helm Chart を使用して Scalar 製品をデプロイする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Scalar Helm Chart を使用して Scalar 製品をデプロイする方法について説明します。minikube クラスターを使用してローカル環境で Scalar 製品をテストする場合は、次のスタートガイドを参照してください。 + +* [Scalar Helm Charts をはじめよう](getting-started-scalar-helm-charts.mdx) + +## 前提条件 + +### Helm コマンドをインストールする + +Scalar Helm Charts を使用するには、helm コマンドをインストールする必要があります。[Helm ドキュメント](https://helm.sh/docs/intro/install/)に従って helm コマンドをインストールしてください。 + +### Scalar Helm Charts リポジトリを追加する + +```console +helm repo add scalar-labs https://scalar-labs.github.io/helm-charts +``` +```console +helm repo update scalar-labs +``` + +### Kubernetes クラスターを準備する + +Scalar 製品を展開するには、Kubernetes クラスターを準備する必要があります。運用環境で EKS (Amazon Elastic Kubernetes Service) または AKS (Azure Kubernetes Service) を使用している場合。詳細については、次のドキュメントを参照してください。 + +- [Scalar 製品用の Amazon EKS クラスターを作成するためのガイドライン](../scalar-kubernetes/CreateEKSClusterForScalarProducts.mdx) +- [Scalar 製品用の AKS クラスターを作成するためのガイドライン](../scalar-kubernetes/CreateAKSClusterForScalarProducts.mdx) + +サポートされているバージョンの Kubernetes を準備する必要があります。Scalar Helm Charts がサポートするバージョンについては、[Kubernetes](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes) を参照してください。 + +### データベースの準備 (ScalarDB、ScalarDL Ledger、ScalarDL Auditor) + +ScalarDB/ScalarDLのバックエンドストレージとしてデータベースを用意する必要があります。ScalarDB/ScalarDL がサポートするデータベースは次のドキュメントで確認できます。 + +* [ScalarDB がサポートするデータベース](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) + +### カスタム値ファイルを準備する + +環境に基づいてカスタム値ファイルを準備する必要があります。カスタム値ファイルの作成方法の詳細については、次のドキュメントを参照してください。 + +* [Scalar Helm Charts のカスタム値ファイルを構成する](configure-custom-values-file.mdx) + +### コンテナイメージを取得する + +特に商用ライセンス製品を使用する場合は、Scalar 製品のコンテナイメージを取得する必要があります。Scalar 製品のコンテナリポジトリの詳細については、[Scalar 製品のコンテナイメージを取得する方法](../scalar-kubernetes/HowToGetContainerImages.mdx)を参照してください。 + +ScalarDB Analytics with PostgreSQL などの OSS 製品を使用する場合は、パブリックコンテナリポジトリからコンテナイメージを取得できます。 + +## Scalar 製品をデプロイする + +各製品の導入方法の詳細については、次のドキュメントを参照してください。 + +* [ScalarDB Cluster](how-to-deploy-scalardb-cluster.mdx) +* [ScalarDB Analytics with PostgreSQL](how-to-deploy-scalardb-analytics-postgresql.mdx) +* [ScalarDL Ledger](how-to-deploy-scalardl-ledger.mdx) +* [ScalarDL Auditor](how-to-deploy-scalardl-auditor.mdx) +* [Scalar Admin for Kubernetes](how-to-deploy-scalar-admin-for-kubernetes.mdx) +* [Scalar Manager](getting-started-scalar-manager.mdx) +* [[非推奨] ScalarDB Server](how-to-deploy-scalardb.mdx) +* [[非推奨] ScalarDB GraphQL](how-to-deploy-scalardb-graphql.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-analytics-postgresql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-analytics-postgresql.mdx new file mode 100644 index 00000000..ca4cd7ad --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-analytics-postgresql.mdx @@ -0,0 +1,45 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics with PostgreSQL の導入方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Scalar Helm Chart を使用して ScalarDB Analytics with PostgreSQL をデプロイする方法について説明します。ScalarDB Analytics with PostgreSQL のカスタム値ファイルの詳細については、[ScalarDB Analytics with PostgreSQL のカスタム値ファイルの構成](configure-custom-values-scalardb-analytics-postgresql.mdx)を参照してください。 + +## シークレットリソースを準備する + +`ScalarDB Analytics with PostgreSQL` をデプロイする前に、キー `superuser-password` を使用して、PostgreSQL のスーパーユーザーパスワードを含むシークレットリソース `scalardb-analytics-postgresql-superuser-password` を作成する必要があります。Scalar Helm Chart は、このシークレットリソースをマウントし、`POSTGRES_PASSWORD` 環境変数を `superuser-password` キーの値に設定します。 + +```console +kubectl create secret generic scalardb-analytics-postgresql-superuser-password --from-literal=superuser-password= -n +``` + +## ScalarDB Analytics with PostgreSQLをデプロイする + +ScalarDB Analytics with PostgreSQL をデプロイするには、次のコマンドを実行します。山かっこ内の内容を説明どおりに置き換えます。 + +```console +helm install scalar-labs/scalardb-analytics-postgresql -n -f / --version +``` + +## ScalarDB Analytics with PostgreSQL 展開をアップグレードする + +ScalarDB Analytics with PostgreSQL デプロイメントをアップグレードするには、次のコマンドを実行します。山括弧内の内容は説明どおりに置き換えてください。 + +```console +helm upgrade scalar-labs/scalardb-analytics-postgresql -n -f / --version +``` + +## ScalarDB Analytics with PostgreSQL デプロイメントを削除する + +ScalarDB Analytics with PostgreSQL デプロイメントを削除するには、次のコマンドを実行して、山括弧内の内容を説明どおりに置き換えます。 + +```console +helm uninstall -n +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-cluster.mdx new file mode 100644 index 00000000..6a40c39c --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-cluster.mdx @@ -0,0 +1,78 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster のデプロイする方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Scalar Helm Chart を使用して ScalarDB Cluster をデプロイする方法について説明します。ScalarDB Cluster のカスタム値ファイルの詳細については、[ScalarDB Cluster のカスタム値ファイルの構成](configure-custom-values-scalardb-cluster.mdx)を参照してください。 + +## ScalarDB Cluster をデプロイする + +```console +helm install scalar-labs/scalardb-cluster -n -f / --version +``` + +## ScalarDB Cluster のデプロイメントをアップグレードする + +```console +helm upgrade scalar-labs/scalardb-cluster -n -f / --version +``` + +## ScalarDB Cluster のデプロイメントを削除する + +```console +helm uninstall -n +``` + +## `direct-kubernetes` モードを使用してクライアントアプリケーションを Kubernetes にデプロイします + +ScalarDB Cluster を `direct-kubernetes` モードで使用する場合は、次のことを行う必要があります。 + +1. アプリケーションポッドを ScalarDB Cluster と同じ Kubernetes クラスターにデプロイします。 +2. 3つの Kubernetes リソース (`Role`、`RoleBinding`、`ServiceAccount`) を作成します。 +3. アプリケーションポッドに `ServiceAccount` をマウントします。 + +このメソッドが必要なのは、`direct-kubernetes` モードの ScalarDB Cluster クライアントライブラリがアプリケーションポッド内から Kubernetes API を実行して、ScalarDB Cluster ポッドに関する情報を取得するためです。 + +* Role + ```yaml + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: scalardb-cluster-client-role + namespace: + rules: + - apiGroups: [""] + resources: ["endpoints"] + verbs: ["get", "watch", "list"] + ``` +* RoleBinding + ```yaml + apiVersion: rbac.authorization.k8s.io/v1 + kind: RoleBinding + metadata: + name: scalardb-cluster-client-rolebinding + namespace: + subjects: + - kind: ServiceAccount + name: scalardb-cluster-client-sa + roleRef: + kind: Role + name: scalardb-cluster-role + apiGroup: rbac.authorization.k8s.io + ``` +* ServiceAccount + ```yaml + apiVersion: v1 + kind: ServiceAccount + metadata: + name: scalardb-cluster-client-sa + namespace: + ``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-graphql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-graphql.mdx new file mode 100644 index 00000000..0443480e --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb-graphql.mdx @@ -0,0 +1,50 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# [非推奨] ScalarDB GraphQL をデプロイする方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +:::note + +ScalarDB GraphQL サーバーは非推奨になりました。代わりに [ScalarDB Cluster](how-to-deploy-scalardb-cluster.mdx) を使用してください。 + +::: + +このドキュメントでは、Scalar Helm Chart を使用して ScalarDB GraphQL をデプロイする方法について説明します。カスタム値ファイルを準備する必要があります。ScalarDB GraphQL のカスタム値ファイルの詳細については、次のドキュメントを参照してください。 + +* [[非推奨] ScalarDB GraphQL のカスタム値ファイルを構成する](configure-custom-values-scalardb-graphql.mdx) + +## ScalarDB Server のデプロイ (推奨オプション) + +ScalarDB GraphQL をデプロイする場合は、次のように ScalarDB GraphQL とバックエンドデータベースの間に ScalarDB Server をデプロイすることをお勧めします。 + +``` +[クライアント] ---> [ScalarDB GraphQL] ---> [ScalarDB Server] ---> [バックエンドデータベース] +``` + +ScalarDB GraphQLをデプロイする前に、ドキュメント [ScalarDB Server をデプロイする方法](how-to-deploy-scalardb.mdx)に従ってScalarDB Serverをデプロイしてください。 + +## ScalarDB GraphQL をデプロイする + +```console +helm install scalar-labs/scalardb-graphql -n -f / --version +``` + +## ScalarDB GraphQL のデプロイメントをアップグレードする + +```console +helm upgrade scalar-labs/scalardb-graphql -n -f / --version +``` + +## ScalarDB GraphQL のデプロイメントを削除する + +```console +helm uninstall -n +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb.mdx new file mode 100644 index 00000000..79371b5d --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardb.mdx @@ -0,0 +1,41 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsJapanese +--- + +# [非推奨] ScalarDB Server をデプロイする方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +:::note + +ScalarDB Server は非推奨になりました。代わりに [ScalarDB Cluster](how-to-deploy-scalardb-cluster.mdx) を使用してください。 + +::: + +このドキュメントでは、Scalar Helm Chart を使用して ScalarDB Server をデプロイする方法について説明します。カスタム値ファイルを準備する必要があります。ScalarDB Server のカスタム値ファイルの詳細については、次のドキュメントを参照してください。 + +* [[非推奨] ScalarDB Server のカスタム値ファイルを構成する](configure-custom-values-scalardb.mdx) + +## ScalarDB Server をデプロイする + +```console +helm install scalar-labs/scalardb -n -f / --version +``` + +## ScalarDB Server のデプロイメントをアップグレードする + +```console +helm upgrade scalar-labs/scalardb -n -f / --version +``` + +## ScalarDB Server のデプロイメントを削除します + +```console +helm uninstall -n +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardl-auditor.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardl-auditor.mdx new file mode 100644 index 00000000..c47596c9 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardl-auditor.mdx @@ -0,0 +1,48 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Auditor のデプロイする方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Scalar Helm Chart を使用して ScalarDL Auditor をデプロイする方法について説明します。カスタム値ファイルを準備する必要があります。ScalarDL Auditor および ScalarDL Schema Loader のカスタム値ファイルの詳細については、次のドキュメントを参照してください。 + +* [ScalarDL Auditor のカスタム値ファイルを構成する](configure-custom-values-scalardl-auditor.mdx) +* [ScalarDL Schema Loaderのカスタム値ファイルを構成する](configure-custom-values-scalardl-schema-loader.mdx) + +## 秘密鍵ファイルと証明書ファイルを準備する + +ScalarDL Auditor をデプロイするときは、秘密鍵ファイルと証明書ファイルを ScalarDL Auditor ポッドにマウントするための Secrete リソースを作成する必要があります。 + +ScalarDL ポッドに秘密鍵ファイルと証明書ファイルをマウントする方法の詳細については、[ScalarDL Helm Charts のポッドに秘密鍵ファイルと証明書ファイルをマウントする](mount-files-or-volumes-on-scalar-pods.mdx#scalardl-helm-charts-のポッドにキーファイルと証明書ファイルをマウントする)を参照してください。 + +## ScalarDL Auditor のスキーマの作成 (ScalarDL Schema Loader のデプロイ) + +ScalarDL Auditor をデプロイする前に、バックエンドデータベースに ScalarDL Auditor のスキーマを作成する必要があります。 + +```console +helm install scalar-labs/schema-loading -n -f / --version +``` + +## ScalarDL Auditor のデプロイ + +```console +helm install scalar-labs/scalardl-audit -n -f / --version +``` + +## ScalarDL Auditor の展開をアップグレードする + +```console +helm upgrade scalar-labs/scalardl-audit -n -f / --version +``` + +## ScalarDL Auditor および ScalarDL Schema Loader のデプロイメントを削除する + +```console +helm uninstall -n +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardl-ledger.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardl-ledger.mdx new file mode 100644 index 00000000..05691946 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/how-to-deploy-scalardl-ledger.mdx @@ -0,0 +1,50 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger のデプロイ方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Scalar Helm Chart を使用して ScalarDL Ledger をデプロイする方法について説明します。カスタム値ファイルを準備する必要があります。ScalarDL Ledger および ScalarDL Schema Loader のカスタム値ファイルの詳細については、次のドキュメントを参照してください。 + +* [ScalarDL Ledger のカスタム値ファイルを構成する](configure-custom-values-scalardl-ledger.mdx) +* [ScalarDL Schema Loaderのカスタム値ファイルを構成する](configure-custom-values-scalardl-schema-loader.mdx) + +## 秘密鍵ファイルを準備します (オプション / ScalarDL Auditor を使用する場合は必要です) + +ScalarDL Ledger の [asset proofs](https://scalardl.scalar-labs.com/ja-jp/docs/latest/how-to-write-applications#アセットプルーフとは) を使用する場合は、秘密鍵ファイルを ScalarDL Ledger ポッドにマウントするための Secrete リソースを作成する必要があります。ScalarDL Auditor を使用する場合はアセットプルーフが必要です。 + +ScalarDL ポッドにキー/証明書ファイルをマウントする方法の詳細については、次のドキュメントを参照してください。 + +* [ScalarDL Helm Charts のポッドに秘密鍵ファイルと証明書ファイルをマウントする](mount-files-or-volumes-on-scalar-pods.mdx#scalardl-helm-charts-のポッドに秘密鍵ファイルと証明書ファイルをマウントする) + +## ScalarDL Ledger のスキーマの作成 (ScalarDL Schema Loader のデプロイ) + +ScalarDL Ledger をデプロイする前に、バックエンドデータベースに ScalarDL Ledger のスキーマを作成する必要があります。 + +```console +helm install scalar-labs/schema-loading -n -f / --version +``` + +## ScalarDL Ledger のデプロイ + +```console +helm install scalar-labs/scalardl -n -f / --version +``` + +## ScalarDL Ledger の展開をアップグレードする + +```console +helm upgrade scalar-labs/scalardl -n -f / --version +``` + +## ScalarDL Ledger および ScalarDL Schema Loader のデプロイメントを削除する + +```console +helm uninstall -n +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/mount-files-or-volumes-on-scalar-pods.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/mount-files-or-volumes-on-scalar-pods.mdx new file mode 100644 index 00000000..fd11df55 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/mount-files-or-volumes-on-scalar-pods.mdx @@ -0,0 +1,142 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar 製品ポッドにファイルまたはボリュームをマウントします + +ScalarDB Server、ScalarDB Cluster、ScalarDB Analytics with PostgreSQL、または ScalarDL Helm Charts (ScalarDL Ledger および ScalarDL Auditor) を使用する場合、Scalar 製品ポッドに任意のファイルまたはボリュームをマウントできます。 + +## ScalarDL Helm Charts のポッドに秘密鍵ファイルと証明書ファイルをマウントする + +ScalarDL Auditor を実行するには、秘密鍵ファイルと証明書ファイルをマウントする必要があります。 + +* 構成例 + * ScalarDL Ledger + ```yaml + ledger: + ledgerProperties: | + ... + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + ``` + * ScalarDL Auditor + ```yaml + auditor: + auditorProperties: | + ... + scalar.dl.auditor.private_key_path=/keys/private-key + scalar.dl.auditor.cert_path=/keys/certificate + ``` + +この例では、**秘密鍵** ファイルと **証明書** ファイルをコンテナ内の `/keys` ディレクトリにマウントする必要があります。そして、`private-key` と `certificate` という名前のファイルをマウントする必要があります。これらのファイルをマウントするには、`extraVolumes` および `extraVolumeMounts` を使用できます。 + +1. Kubernetes マニフェストと同じ構文を使用して、カスタム値ファイルに `extraVolumes` と `extraVolumeMounts` を設定します。`mountPath` キーにディレクトリ名を指定する必要があります。 + * 例 + * ScalarDL Ledger + ```yaml + ledger: + extraVolumes: + - name: ledger-keys + secret: + secretName: ledger-keys + extraVolumeMounts: + - name: ledger-keys + mountPath: /keys + readOnly: true + ``` + * ScalarDL Auditor + ```yaml + auditor: + extraVolumes: + - name: auditor-keys + secret: + secretName: auditor-keys + extraVolumeMounts: + - name: auditor-keys + mountPath: /keys + readOnly: true + ``` + +1. キーと証明書ファイルを含む `Secret` リソースを作成します。 + + Secret のキーにはファイル名を指定する必要があります。 + + * 例 + * ScalarDL Ledger + ```console + kubectl create secret generic ledger-keys \ + --from-file=tls.key=./ledger-key.pem + ``` + * ScalarDL Auditor + ```console + kubectl create secret generic auditor-keys \ + --from-file=tls.key=./auditor-key.pem \ + --from-file=certificate=./auditor-cert.pem + ``` + +1. 上記のカスタム値ファイルを使用して Scalar 製品をデプロイします。 + + Scalar 製品を展開した後、次のように秘密鍵ファイルと証明書ファイルが `/keys` ディレクトリにマウントされます。 + + * 例 + * ScalarDL Ledger + ```console + ls -l /keys/ + ``` + + 次のような結果が表示されます: + + ```console + total 0 + lrwxrwxrwx 1 root root 18 Jun 27 03:12 private-key -> ..data/private-key + ``` + * ScalarDL Auditor + ```console + ls -l /keys/ + ``` + + 次のような結果が表示されます: + + ```console + total 0 + lrwxrwxrwx 1 root root 18 Jun 27 03:16 certificate -> ..data/certificate + lrwxrwxrwx 1 root root 18 Jun 27 03:16 private-key -> ..data/private-key + ``` + +## emptyDir をマウントしてヒープダンプファイルを取得します + +カスタム値ファイルで次のキーを使用して、emptyDir を Scalar 製品ポッドにマウントできます。たとえば、このボリュームを使用して、Scalar 製品のヒープダンプを取得できます。 + +* キー + * `scalardb.extraVolumes` / `scalardb.extraVolumeMounts` (ScalarDB Server) + * `scalardbCluster.extraVolumes` / `scalardbCluster.extraVolumeMounts` (ScalarDB Cluster) + * `scalardbAnalyticsPostgreSQL.extraVolumes` / `scalardbAnalyticsPostgreSQL.extraVolumeMounts` (ScalarDB Analytics with PostgreSQL) + * `ledger.extraVolumes` / `ledger.extraVolumeMounts` (ScalarDL Ledger) + * `auditor.extraVolumes` / `auditor.extraVolumeMounts` (ScalarDL Auditor) + +* 例 (ScalarDB Server) + ```yaml + scalardb: + extraVolumes: + - name: heap-dump + emptyDir: {} + extraVolumeMounts: + - name: heap-dump + mountPath: /dump + ``` + +この例では、次のように ScalarDB Server ポッドにマウントされたボリュームを確認できます。 + +```console +ls -ld /dump +``` + +次のような結果が表示されます: + +```console +drwxrwxrwx 2 root root 4096 Feb 6 07:43 /dump +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/use-secret-for-credentials.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/use-secret-for-credentials.mdx new file mode 100644 index 00000000..2f62352c --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/helm-charts/use-secret-for-credentials.mdx @@ -0,0 +1,246 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Secret リソースを使用して資格情報を環境変数としてプロパティファイルに渡す方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Kubernetes の `Secret` リソースを介して、**username** や **password** などの資格情報を環境変数として渡すことができます。Scalar 製品の以前のバージョンの Docker イメージは、プロパティファイルのテンプレート化に `dockerize` コマンドを使用します。Scalar 製品の最新バージョンの Docker イメージは、環境変数から直接値を取得します。 + +注記:次の環境変数名は、Scalar Helm Chart の内部で使用されるため、カスタム値ファイルで使用できません。 +```console +HELM_SCALAR_DB_CONTACT_POINTS +HELM_SCALAR_DB_CONTACT_PORT +HELM_SCALAR_DB_USERNAME +HELM_SCALAR_DB_PASSWORD +HELM_SCALAR_DB_STORAGE +HELM_SCALAR_DL_LEDGER_PROOF_ENABLED +HELM_SCALAR_DL_LEDGER_AUDITOR_ENABLED +HELM_SCALAR_DL_LEDGER_PROOF_PRIVATE_KEY_PATH +HELM_SCALAR_DL_AUDITOR_SERVER_PORT +HELM_SCALAR_DL_AUDITOR_SERVER_PRIVILEGED_PORT +HELM_SCALAR_DL_AUDITOR_SERVER_ADMIN_PORT +HELM_SCALAR_DL_AUDITOR_LEDGER_HOST +HELM_SCALAR_DL_AUDITOR_CERT_HOLDER_ID +HELM_SCALAR_DL_AUDITOR_CERT_VERSION +HELM_SCALAR_DL_AUDITOR_CERT_PATH +HELM_SCALAR_DL_AUDITOR_PRIVATE_KEY_PATH +SCALAR_DB_LOG_LEVEL +SCALAR_DL_LEDGER_LOG_LEVEL +SCALAR_DL_AUDITOR_LOG_LEVEL +SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME +SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME +``` + +1. 環境変数名をカスタム値ファイルのプロパティ構成に設定します。使用している製品に応じて、次の例を参照してください。 + + + + ```yaml + scalardbCluster: + scalardbClusterNodeProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + + + ```yaml + scalardbAnalyticsPostgreSQL: + databaseProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + + +

ScalarDB Server 3.8以降 (Apache Commons Text 構文)

+ + ```yaml + scalardb: + databaseProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + +

ScalarDB Server 3.7以前 (Go テンプレート構文)

+ + ```yaml + scalardb: + databaseProperties: | + ... + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + ... + ``` +
+ +

ScalarDL Ledger 3.8以降 (Apache Commons Text 構文)

+ + ```yaml + ledger: + ledgerProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + +

ScalarDL Ledger 3.7以前 (Go テンプレート構文)

+ + ```yaml + ledger: + ledgerProperties: | + ... + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + ... + ``` +
+ +

ScalarDL Auditor 3.8以降 (Apache Commons Text 構文)

+ + ```yaml + auditor: + auditorProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + +

ScalarDL Auditor 3.7以前 (Go テンプレート構文)

+ + ```yaml + auditor: + auditorProperties: | + ... + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + ... + ``` +
+ +

ScalarDL Schema Loader 3.8以降 (Apache Commons Text 構文)

+ + ```yaml + schemaLoading: + databaseProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + +

ScalarDL Schema Loader 3.7以前 (Go テンプレート構文)

+ + ```yaml + schemaLoading: + databaseProperties: | + ... + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + ... + ``` +
+
+ +1. 資格情報を含む `Secret` リソースを作成します。 + `Secret` のキーとして環境変数名を指定する必要があります。 + * 例 + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_USERNAME=postgres \ + --from-literal=SCALAR_DB_PASSWORD=postgres + ``` + +1. カスタム値ファイル内の次のキーに `Secret` 名を設定します。使用している製品に応じて、次の例を参照してください。 + + + + **キー:** `scalardbCluster.secretName` + + ```yaml + scalardbCluster: + secretName: "scalardb-cluster-credentials-secret" + ``` + + + **キー:** `scalardbAnalyticsPostgreSQL.secretName` + + ```yaml + scalardbAnalyticsPostgreSQL: + secretName: "scalardb-analytics-postgresql-credentials-secret" + ``` + + + **キー:** `scalardb.secretName` + + ```yaml + scalardb: + secretName: "scalardb-credentials-secret" + ``` + + + **キー:** `ledger.secretName` + + ```yaml + ledger: + secretName: "ledger-credentials-secret" + ``` + + + **キー:** `auditor.secretName` + + ```yaml + auditor: + secretName: "auditor-credentials-secret" + ``` + + + **キー:** `schemaLoading.secretName` + + ```yaml + schemaLoading: + secretName: "schema-loader-ledger-credentials-secret" + ``` + + + +1. 上記のカスタム値ファイルを使用して Scalar 製品をデプロイします。 + + Scalar 製品をデプロイした後、Go テンプレート文字列 (環境変数) は `Secret` の値に置き換えられます。 + + * 例 + * カスタム値ファイル + + ```yaml + scalardb: + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + scalar.db.storage=jdbc + ``` + + * コンテナ内のプロパティファイル + ```properties + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.username=postgres + scalar.db.password=postgres + scalar.db.storage=jdbc + ``` + + Apache Commons Text 構文を使用する場合、Scalar 製品は環境変数から直接値を取得します。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/data_model.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/data_model.png new file mode 100644 index 00000000..15a0e4d4 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/data_model.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/getting-started-ERD.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/getting-started-ERD.png new file mode 100644 index 00000000..1a6d13c5 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/getting-started-ERD.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb-architecture.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb-architecture.png new file mode 100644 index 00000000..6f22111c Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb-architecture.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb-metadata.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb-metadata.png new file mode 100644 index 00000000..49880267 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb-metadata.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb.png new file mode 100644 index 00000000..658486cb Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb_data_model.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb_data_model.png new file mode 100644 index 00000000..7a02fa23 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/scalardb_data_model.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/software_stack.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/software_stack.png new file mode 100644 index 00000000..75fba6e6 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/software_stack.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/two_phase_commit_load_balancing.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/two_phase_commit_load_balancing.png new file mode 100644 index 00000000..5cdc26f0 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/two_phase_commit_load_balancing.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/two_phase_commit_sequence_diagram.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/two_phase_commit_sequence_diagram.png new file mode 100644 index 00000000..116ef635 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/images/two_phase_commit_sequence_diagram.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/index.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/index.mdx new file mode 100644 index 00000000..31a0f4cf --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/index.mdx @@ -0,0 +1,14 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +image: img/scalardb-social-card-preview.png +hide_table_of_contents: true +title: "" +--- + +import CategoryGrid from '/src/components/Cards/ja-jp/3.15'; + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-backup-and-restore.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-backup-and-restore.mdx new file mode 100644 index 00000000..c0588d9b --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-backup-and-restore.mdx @@ -0,0 +1,27 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# データベースのバックアップと復元 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB で使用されるデータベースのバックアップと復元の方法について説明します。 + +## データベースのバックアップと復元の基本ガイドライン + +バックアップを実行する前に、[ScalarDB で使用されるデータベースのバックアップと復元方法](backup-restore.mdx)を必ずお読みください。 + +## Kubernetes 環境で ScalarDB を使用する場合のデータベースのバックアップ + +Kubernetes 環境でデータベースをバックアップする方法の詳細については、[Kubernetes 環境で NoSQL データベースをバックアップする](scalar-kubernetes/BackupNoSQL.mdx)を参照してください。 + +## Kubernetes 環境で ScalarDB を使用する場合のデータベースの復元 + +Kubernetes 環境でデータベースを復元する方法の詳細については、[Kubernetes 環境でデータベースを復元する](scalar-kubernetes/RestoreDatabase.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-monitor-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-monitor-overview.mdx new file mode 100644 index 00000000..8ac01978 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-monitor-overview.mdx @@ -0,0 +1,25 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# 監視の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Scalar Manager は、Kubernetes クラスター環境内の ScalarDB の集中管理および監視ソリューションであり、次のことが可能になります。 + +- ScalarDB の可用性を確認します。 +- ScalarDB が使用するデータベースでトランザクションの一貫性のある期間を作成する一時停止ジョブをスケジュールまたは実行します。 +- Grafana ダッシュボードを介して ScalarDB の時系列メトリックとログを確認します。 + +Scalar Manager の詳細については、[Scalar Manager 概要](scalar-manager/overview.mdx)を参照してください。 + +## Scalar Manager をデプロイする + +Helm Chart を使用して Scalar Manager をデプロイできます。 + +Scalar Manager をデプロイする方法の詳細については、[Scalar Manager のデプロイ](helm-charts/getting-started-scalar-manager.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-overview.mdx new file mode 100644 index 00000000..bddf73f4 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/manage-overview.mdx @@ -0,0 +1,30 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 運用の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このカテゴリでは、ScalarDB の運用に役立つガイドを参照できます。 + +- ScalarDB をスケールする方法の詳細については、[スケール](scalar-kubernetes/HowToScaleScalarDB.mdx)を参照してください。 +- ScalarDB をアップグレードする方法の詳細については、[アップグレード](scalar-kubernetes/HowToUpgradeScalarDB.mdx)を参照してください。 + +## 監視 + +このサブカテゴリでは、ScalarDB のデプロイメントを監視する方法を学習できます。 + +このサブカテゴリの概要については、[監視の概要](manage-monitor-overview.mdx)を参照してください。 + +## バックアップと復元 + +このサブカテゴリでは、ScalarDB のデプロイメントに接続されているデータベースをバックアップおよび復元する方法を学習できます。 + +このサブカテゴリの概要については、[データベースのバックアップと復元](manage-backup-and-restore.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/migrate-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/migrate-overview.mdx new file mode 100644 index 00000000..dfaf61aa --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/migrate-overview.mdx @@ -0,0 +1,18 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 移行の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +テーブルのインポート、またはアプリケーションとデータベースを ScalarDB ベースの環境に移行する方法の詳細については、次のガイドを参照してください: + +- [ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](schema-loader-import.mdx) +- [アプリケーションとデータベースを ScalarDB ベースの環境に移行する方法](scalardb-sql/migration-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/multi-storage-transactions.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/multi-storage-transactions.mdx new file mode 100644 index 00000000..58ae7bcb --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/multi-storage-transactions.mdx @@ -0,0 +1,72 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# マルチストレージトランザクション + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB トランザクションは、*マルチストレージトランザクション* と呼ばれる機能を使用することで、ACID 準拠を維持しながら複数のストレージまたはデータベースにまたがることができます。 + +このページでは、マルチストレージトランザクションの仕組みと、ScalarDB でこの機能を設定する方法について説明します。 + +## ScalarDB でのマルチストレージトランザクションの仕組み + +ScalarDB では、`マルチストレージ` 実装は複数のストレージインスタンスを保持し、名前空間名から適切なストレージインスタンスへのマッピングを持っています。操作が実行されると、マルチストレージトランザクション機能は、名前空間ストレージマッピングを使用して指定された名前空間から適切なストレージインスタンスを選択し、そのストレージインスタンスを使用します。 + +## マルチストレージトランザクションをサポートするように ScalarDB を設定する方法 + +マルチストレージトランザクションを有効にするには、`scalar.db.transaction_manager` の値として `consensus-commit` を指定し、`scalar.db.storage` の値として `multi-storage` を指定し、ScalarDB プロパティファイルでデータベースを設定する必要があります。 + +以下は、マルチストレージトランザクションの設定例です。 + +```properties +# Consensus Commit is required to support multi-storage transactions. +scalar.db.transaction_manager=consensus-commit + +# Multi-storage implementation is used for Consensus Commit. +scalar.db.storage=multi-storage + +# Define storage names by using a comma-separated format. +# In this case, "cassandra" and "mysql" are used. +scalar.db.multi_storage.storages=cassandra,mysql + +# Define the "cassandra" storage. +# When setting storage properties, such as `storage`, `contact_points`, `username`, and `password`, for multi-storage transactions, the format is `scalar.db.multi_storage.storages..`. +# For example, to configure the `scalar.db.contact_points` property for Cassandra, specify `scalar.db.multi_storage.storages.cassandra.contact_point`. +scalar.db.multi_storage.storages.cassandra.storage=cassandra +scalar.db.multi_storage.storages.cassandra.contact_points=localhost +scalar.db.multi_storage.storages.cassandra.username=cassandra +scalar.db.multi_storage.storages.cassandra.password=cassandra + +# Define the "mysql" storage. +# When defining JDBC-specific configurations for multi-storage transactions, you can follow a similar format of `scalar.db.multi_storage.storages..`. +# For example, to configure the `scalar.db.jdbc.connection_pool.min_idle` property for MySQL, specify `scalar.db.multi_storage.storages.mysql.jdbc.connection_pool.min_idle`. +scalar.db.multi_storage.storages.mysql.storage=jdbc +scalar.db.multi_storage.storages.mysql.contact_points=jdbc:mysql://localhost:3306/ +scalar.db.multi_storage.storages.mysql.username=root +scalar.db.multi_storage.storages.mysql.password=mysql +# Define the JDBC-specific configurations for the "mysql" storage. +scalar.db.multi_storage.storages.mysql.jdbc.connection_pool.min_idle=5 +scalar.db.multi_storage.storages.mysql.jdbc.connection_pool.max_idle=10 +scalar.db.multi_storage.storages.mysql.jdbc.connection_pool.max_total=25 + +# Define namespace mapping from a namespace name to a storage. +# The format is ":,...". +scalar.db.multi_storage.namespace_mapping=user:cassandra,coordinator:mysql + +# Define the default storage that's used if a specified table doesn't have any mapping. +scalar.db.multi_storage.default_storage=cassandra +``` + +追加の設定については、[ScalarDB 設定](configurations.mdx)を参照してください。 + +## 実践的なチュートリアル + +実践的なチュートリアルについては、[マルチストレージトランザクションをサポートするサンプルアプリケーションを作成する](scalardb-samples/multi-storage-transaction-sample/README.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/overview.mdx new file mode 100644 index 00000000..c7e60f17 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/overview.mdx @@ -0,0 +1,82 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB の概要と主な使用例について説明します。 + +## ScalarDB とは + +ScalarDB は、さまざまなデータベース向けのユニバーサルなハイブリッドトランザクション/分析処理 (HTAP) エンジンです。データベース上でミドルウェアとして実行され、ACID トランザクションとリアルタイム分析を実現することでさまざまなデータベースを仮想的に統合し、複数のデータベースまたは単一のデータベースの複数のインスタンスの管理の複雑さを簡素化します。 + +![ScalarDB が複雑なデータ管理アーキテクチャを簡素化する方法。](images/scalardb.png) + +多用途のソリューションである ScalarDB は、次のようなさまざまなデータベースをサポートしています。 + +- MariaDB、Microsoft SQL Server、MySQL、Oracle Database、PostgreSQL、SQLite などの JDBC をサポートするリレーショナルデータベース、および Amazon Aurora、YugabyteDB などの互換性のあるデータベース。 +- Amazon DynamoDB、Apache Cassandra、Azure Cosmos DB などの NoSQL データベース。 + +ScalarDB がサポートするデータベースの詳細については、[データベース](requirements.mdx#データベース) を参照してください。 + +## ScalarDB を選ぶ理由 + +グローバルトランザクションマネージャー、データフェデレーションエンジン、HTAP システムなどのいくつかのソリューションは、同様の目標を持っていますが、次の観点で制限があります。 + +- グローバルトランザクションマネージャー (Oracle MicroTx や Atomikos など) は、限られた異種データベースセット (XA 準拠のデータベースのみなど) でトランザクションを実行するように設計されています。 +- データフェデレーションエンジン (Denodo や Starburst など) は、異種データベースで分析クエリを実行するように設計されています。 +- HTAP システム (TiDB や SingleStore など) は、同種データベースでのみトランザクションと分析クエリの両方を実行します。 + +言い換えれば、これらはデータベースを仮想的に統合しますが、制限があります。たとえば、データフェデレーションエンジンを使用すると、ユーザーは複数のデータベースにまたがる仮想ビューで読み取り専用の分析クエリを実行できます。ただし、多くの場合、データベースごとに更新クエリを個別に実行する必要があります。 + +他のソリューションとは異なり、ScalarDB は、異種データベースでトランザクションクエリと分析クエリの両方を実行できる機能を備えているため、データベース管理を大幅に簡素化できます。 + +次の表は、ScalarDB が他のソリューションとどのように異なるかをまとめたものです。 + +| | 異種データベース間のトランザクション | 異種データベース間の分析 | +| :--------------------------------------------------------------: | :----------------------------------------------------------------------------: | :--------------------------------: | +| グローバルトランザクションマネージャー (Oracle MicroTx や Atomikos など) | はい(ただし、既存のソリューションでは限られたデータベースのセットしかサポートされていません) | いいえ | +| データフェデレーションエンジン (Denodo や Starburst など) | いいえ | はい | +| HTAP システム (TiDB や SingleStore など) | いいえ (同種のデータベースのみサポート) | いいえ (同種のデータベースのみサポート) | +| **ScalarDB** | **はい (各種データベースに対応)** | **はい** | + +## ScalarDB の使用例 + +ScalarDB はさまざまな用途で使用できます。ScalarDB の主な使用例を3つ紹介します。 + +### サイロ化されたデータベースを簡単に管理 + +多くの企業は、アジャイルなビジネスオペレーションをサポートするために複数の組織、部門、ビジネスユニットで構成されており、その結果、サイロ化された情報システムになることがよくあります。特に、異なる組織では、異なるデータベースを使用して異なるアプリケーションを管理する可能性があります。このようなサイロ化されたデータベースの管理は、アプリケーションが各データベースと個別に通信し、データベース間の違いを適切に処理する必要があるため、困難です。 + +ScalarDB は、統一されたインターフェイスを使用してサイロ化されたデータベースの管理を簡素化し、ユーザーがデータベースを1つのデータベースのように扱えるようにします。たとえば、ユーザーは複数のデータベースに対して (分析的な) 結合クエリを、それぞれのデータベースとやり取りすることなく実行できます。 + +### 複数のデータベース間の一貫性の管理 + +マイクロサービスアーキテクチャなどの最新のアーキテクチャでは、システムでサービスとそのデータベースを小さなサブセットに分割して、システムのモジュール性と開発効率を高めることが推奨されています。しかし、多様なデータベース、特に異なる種類のデータベースを管理するのは困難です。なぜなら、Saga や TCC などのトランザクション管理パターンを使用しても、アプリケーションはそれらのデータベースの正しい状態 (言い換えれば一貫性) を保証する必要があるからです。 + +ScalarDB は、正確性の保証 (言い換えれば、厳密なシリアル化可能性を備えた ACID) によって、このような多様なデータベースの管理を簡素化します。これにより、データベース間の一貫性の保証を気にすることなく、アプリケーション開発に集中できます。 + +### データメッシュでのデータ管理の簡素化 + +企業は、データ利用を合理化および拡張するために、[データメッシュ](https://martinfowler.com/articles/data-mesh-principles.html)の構築に時間を費やしてきました。ただし、データメッシュの構築は必ずしも簡単ではありません。たとえば、分散データの管理方法には多くの技術的な問題があります。 + +ScalarDB は、データメッシュ内のすべてのデータベースに統一された API を提供することで、データメッシュ内の分散データベースの管理を簡素化し「データをプロダクトとして扱う(Data as a Product)」という原則に簡単に適合させます。 + +### データベース移行のハードルを下げる + +アプリケーションは、データベースが提供する特定の機能のために、特定のデータベースを使用するようにロックされる傾向があります。このようなデータベースロックインにより、データベースのアップグレードや変更が妨げられます。アップグレードや変更を行うには、多くの場合、アプリケーションの書き直しが必要になるからです。 + +ScalarDB は、多様なデータベースに統一されたインターフェイスを提供します。したがって、ScalarDB インターフェイスを使用してアプリケーションを作成すると、そのアプリケーションは移植可能になり、アプリケーションを書き直すことなくシームレスなデータベース移行を実現できます。 + +## さらに読む + +- [ScalarDB Technical Overview](https://speakerdeck.com/scalar/scalar-db-universal-transaction-manager) +- [ScalarDB Research Paper [VLDB'23]](https://dl.acm.org/doi/10.14778/3611540.3611563) \ No newline at end of file diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-overview.mdx new file mode 100644 index 00000000..1e9d5741 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-overview.mdx @@ -0,0 +1,45 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# クイックスタート + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このカテゴリでは、ScalarDB を介してトランザクションとクエリの実行を開始する方法についてのクイックスタートチュートリアルに従うことができます。 + +このサブカテゴリの概要については、[ScalarDB Core クイックスタートの概要](quickstart-scalardb-core-overview.mdx)を参照してください。 + +## ScalarDB Core ライブラリを介してトランザクションを実行してみる + +このサブカテゴリでは、Apache 2 ライセンスの下で公開されている ScalarDB Core ライブラリを介して ACID トランザクションを実行する方法に関するチュートリアルに従うことができます。 + +## ScalarDB Cluster を介してトランザクションを実行してみる + +このサブカテゴリでは、ScalarDB Core ライブラリをラップする [gRPC](https://grpc.io/) サーバーである ScalarDB Cluster を介して ACID トランザクションを実行する方法に関するチュートリアルを参照できます。 + +このサブカテゴリの概要については、[ScalarDB Cluster クイックスタートの概要](quickstart-scalardb-cluster-overview.mdx)を参照してください。 + +:::note + +ScalarDB Cluster は Enterprise エディションでのみ利用できます。 + +::: + +## ScalarDB Analytics で分析クエリを実行してみる + +このサブカテゴリでは、ScalarDB Analytics というコンポーネントを使用して、ScalarDB を通じて書き込んだデータベースに対して分析クエリを実行する方法に関するチュートリアルを参照できます。ScalarDB Analytics は現在、ScalarDB トランザクションを通じて更新される ScalarDB 管理データベースのみを対象としていますが、将来的には ScalarDB 管理以外のデータベースも対象とする予定です。 + +このサブカテゴリの概要については、[ScalarDB Analytics クイックスタートの概要](quickstart-scalardb-analytics-overview.mdx)を参照してください。 + +:::note + +- ScalarDB Analytics with PostgreSQL は Apache 2 ライセンスでのみ利用可能で、商用ライセンスは必要ありません。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-analytics-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-analytics-overview.mdx new file mode 100644 index 00000000..082d9be0 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-analytics-overview.mdx @@ -0,0 +1,17 @@ +--- +tags: + - Community + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics クイックスタートの概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このサブカテゴリでは、ScalarDB Analytics というコンポーネントを使用して、ScalarDB で作成したデータベースに対して分析クエリを実行する方法に関するチュートリアルを確認できます。 + +- PostgreSQL を介して分析クエリを実行するには、[ScalarDB Analytics with PostgreSQL をはじめよう](scalardb-analytics-postgresql/getting-started.mdx)を参照してください。 +- Spark を介して分析クエリを実行するには、[ScalarDB Analytics をはじめよう](scalardb-samples/scalardb-analytics-spark-sample/README.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-cluster-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-cluster-overview.mdx new file mode 100644 index 00000000..8e0e658f --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-cluster-overview.mdx @@ -0,0 +1,19 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster クイックスタートの概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このサブカテゴリでは、ScalarDB Core ライブラリをラップする [gRPC](https://grpc.io/) サーバーである ScalarDB Cluster を介して ACID トランザクションを実行する方法に関するチュートリアルを確認できます。 + +- トランザクションの実行を試すには、[ScalarDB Cluster をはじめよう](scalardb-cluster/getting-started-with-scalardb-cluster.mdx)を参照してください。 +- JDBC 経由の SQL インターフェースを介してトランザクションの実行を試すには、[JDBC 経由の ScalarDB Cluster SQL をはじめよう](scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx)を参照してください。 +- Spring Data JDBC 経由で SQL インターフェースを介してトランザクションを実行するには、[Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx)を参照してください。 +- GraphQL インターフェースを介してトランザクションを実行するには、[ScalarDB Cluster GraphQL をはじめよう](scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-core-overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-core-overview.mdx new file mode 100644 index 00000000..b1218739 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/quickstart-scalardb-core-overview.mdx @@ -0,0 +1,18 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Core クイックスタートの概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このサブカテゴリでは、Apache 2 ライセンスで公開されている ScalarDB Core ライブラリを使用して ACID トランザクションを実行する方法に関するチュートリアルに従うことができます。 + +- トランザクションの実行を試すには、[ScalarDB をはじめよう](getting-started-with-scalardb.mdx)を参照してください。 +- Kotlin を使用してトランザクションの実行を試すには、[Kotlin を使って ScalarDB をはじめよう](getting-started-with-scalardb-by-using-kotlin.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/releases/release-notes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/releases/release-notes.mdx new file mode 100644 index 00000000..7e376041 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/releases/release-notes.mdx @@ -0,0 +1,161 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB 3.15 リリースノート + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページには、ScalarDB 3.15 のリリースノートのリストが含まれています。 + +## v3.15.4 + +**発売日:** 2025年06月21日 + +### まとめ + +このリリースには脆弱性とバグの修正が含まれています。 + +### Community edition + +#### バグの修正 + +- カラム値変換におけるDateTimeParseExceptionの例外処理を追加しました。([#2662](https://github.com/scalar-labs/scalardb/pull/2662)) +- セキュリティ問題を修正するためにPostgreSQLドライバーをアップグレードしました。[CVE-2025-49146](https://github.com/advisories/GHSA-hq9p-pm7w-8p54 "CVE-2025-49146") ([#2772](https://github.com/scalar-labs/scalardb/pull/2772)) +- `jdbc`ストレージを使用し、対象テーブルが存在しないためにスキャン操作が失敗した場合の潜在的な接続リークを修正しました。([#2766](https://github.com/scalar-labs/scalardb/pull/2766)) + +### Enterprise edition + +#### バグの修正 + +##### ScalarDB Cluster + +- コーディネーターのグループコミット機能が有効になっている場合のメモリリーク問題を修正しました。 +- セキュリティ問題を修正するためにOpenSearch Javaクライアントをアップグレードしました。[CVE-2025-27820](https://github.com/advisories/GHSA-73m2-qfq3-56cx "CVE-2025-27820") + +## v3.15.3 + +**発売日:** 2025年05月15日 + +### まとめ + +このリリースには、脆弱性とバグの修正が含まれており、Omnistrate サービス上で ScalarDB Cluster を実行するためのサポートが追加されています。 + +### Community edition + +#### バグの修正 + +- 名前空間プレフィックス設定 `scalar.db.dynamo.namespace.prefix` を使用して DynamoDB ストレージを使用する場合の `DistributedStorageAdmin.getNamespaceNames()` API の問題を修正しました。このメソッドによって返される名前空間名に誤ってプレフィックスが含まれていました。([#2641](https://github.com/scalar-labs/scalardb/pull/2641)) + +### Enterprise edition + +#### 改善点 + +##### ScalarDB Cluster + +- Omnistrate サービスのサポートを追加しました。これにより、Omnistrate サービス上で ScalarDB Cluster を実行できるようになりました。 + +#### バグの修正 + +##### ScalarDB Cluster + +- セキュリティの問題を修正するために `grpc_health_probe` をアップグレードしました。[CVE-2025-22869](https://github.com/advisories/GHSA-hcg3-q754-cr77) + +## v3.15.2 + +**発売日:** 2025年03月24日 + +### まとめ + +このリリースには、いくつかの改善とバグ修正が含まれています。 + +### Community edition + +#### 改善点 + +- ScalarDB BIGINT データ型が Oracle の NUMBER(16) にマッピングされるようになりました。([#2566](https://github.com/scalar-labs/scalardb/pull/2566)) + +#### バグの修正 + +- セキュリティ問題を修正するために Netty ライブラリをアップグレードしました。 [CVE-2025-24970](https://github.com/advisories/GHSA-4g8c-wm8x-jfhw "CVE-2025-24970") ([#2552](https://github.com/scalar-labs/scalardb/pull/2552)) + +### Enterprise edition + +#### 機能強化 + +##### ScalarDB Cluster + +- ScalarDB Cluster のトランザクション機能を有効または無効にする設定オプション (`scalar.db.transaction.enabled`) を追加しました。デフォルト値は `true` です。 + +#### バグ修正 + +##### ScalarDB Cluster + +- SQL インターフェースで認証を使用する場合のメタデータキャッシュの動作に関連するバグを修正しました。 +- 埋め込み機能の設定を修正しました。 +- スーパーユーザーが存在しないユーザーに対して ABAC 管理操作を実行できるバグを修正しました。 +- 空の ABAC システムテーブルを削除するときにテーブルが見つからないというエラーが発生するバグを修正しました。 + +## v3.15.1 + +**発売日:** 2025年02月20日 + +### まとめ + +このリリースには、多数の機能強化、改善、バグ修正が含まれています。[3.15.0 リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.0)は破棄され、これが 3.15 の最初の公式リリースとなります。 + +### Community edition + +#### 機能強化 + +- 操作属性が導入され、操作に追加のキー値情報を含める機能が提供されました。([#2333](https://github.com/scalar-labs/scalardb/pull/2333)) +- 新しい時間関連のデータ型 DATE、TIME、TIMESTAMP、および TIMESTAMPTZ が追加されました。 ([#2468](https://github.com/scalar-labs/scalardb/pull/2468) [#2491](https://github.com/scalar-labs/scalardb/pull/2491)) + +#### 改善点 + +- ScalarDB は、MySQL 8.4、8.0、PostgreSQL 17、16、15、14、13、Amazon Aurora PostgreSQL 16、15、14、13 をサポートするようになりました。 Amazon Aurora MySQL 3、および 2。([#2302](https://github.com/scalar-labs/scalardb/pull/2302)) +- `jdbc:mariadb` で始まる接続 URL には MariaDB Connector/J JDBC ドライバーを使用します。([#2391](https://github.com/scalar-labs/scalardb/pull/2391)) +- Cassandra および Cosmos DB のステートメントハンドラーで不要なログ記録を削除しました。([#2469](https://github.com/scalar-labs/scalardb/pull/2469)) + +#### バグの修正 + +- Cosmos DB アダプターの主キー列の検証を追加しました。検証により、主キー列のテキスト値に不正な文字 (`:`、`/`、`\`、`#`、および `?`) が含まれていないことが保証されます。 ([#2292](https://github.com/scalar-labs/scalardb/pull/2292)) +- Consensus Commit のトランザクションで同じレコードに対して複数のミューテーションが発生する動作を修正しました。([#2340](https://github.com/scalar-labs/scalardb/pull/2340)) +- Cosmos アダプターで存在しないレコードを削除するときの動作を修正しました。([#2341](https://github.com/scalar-labs/scalardb/pull/2341)) +- GetBuilder と ScanBuilder のバグを修正しました。([#2352](https://github.com/scalar-labs/scalardb/pull/2352)) + +### Enterprise edition + +#### 機能強化 + +##### ScalarDB Cluster + +- [#2333](https://github.com/scalar-labs/scalardb/pull/2333) で導入された操作属性のサポートを ScalarDB Cluster に追加しました。 +- 属性ベースのアクセス制御機能を追加しました。 +- [#2468](https://github.com/scalar-labs/scalardb/pull/2468) で導入された時間関連の型のサポートを ScalarDB Cluster に追加しました。 +- [scalar-labs/scalardb-sql#708](https://github.com/scalar-labs/scalardb-sql/pull/708) で導入された ABAC のメタデータ API のサポートを追加しました。 +- LangChain4j を統合することで、ScalarDB Cluster にベクトル検索機能を追加しました。 + +##### ScalarDB SQL + +- DML に操作属性のサポートを追加しました。また、ABAC の読み取りタグと書き込みタグを DMS にサポートしました。 +- 時間関連の型である DATE、TIME、TIMESTAMP、および TIMESTAMPTZ をサポートします。 +- ABAC のメタデータ API を追加しました。 +- ABAC の SQL ステートメントを追加しました。 + +#### バグの修正 + +##### ScalarDB Cluster + +- セキュリティ問題を修正するために `grpc_health_probe` をアップグレードしました。 [CVE-2024-45337](https://github.com/advisories/GHSA-v778-237x-gjrc "CVE-2024-45337") [CVE-2024-45338](https://github.com/advisories/GHSA-w32m-9786-jp63 "CVE-2024-45338") + +##### ScalarDB SQL + +- [Spring Data JDBC For ScalarDB] `existsById()` API が動作しないバグを修正しました +- SQL ステートメントパーサーが INT 型および BIGINT 型の列の負の数値リテラルを拒否する問題を修正しました。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/releases/release-support-policy.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/releases/release-support-policy.mdx new file mode 100644 index 00000000..e92a601a --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/releases/release-support-policy.mdx @@ -0,0 +1,122 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# リリースサポートポリシー + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDL のメジャーバージョンリリースとマイナーバージョンリリースに対する Scalar のサポートポリシーについて説明します。 + +## 用語と定義 + +- **メンテナンスサポート:** Scalar は、商用ライセンスを持つ顧客に、コード修正やドキュメントを含む製品アップデートと、[サポートポータル](https://support.scalar-labs.com/)を通じて技術サポートを提供します。 指定された日付まで。 +- **アシスタンスサポート:** Scalar は、[サポートポータル](https://support.scalar-labs.com/)を通じて、FAQ および問い合わせの形式でコード以外の質問に対して限定的な技術サポートを顧客に提供します。 指定された日付までは商用ライセンスが付与されます。 +- **延長サポート:** 延長サポートは、メンテナンスサポートまたはアシスタンスサポートが終了したバージョンのサポートを希望する商用ライセンスを持つ顧客向けのアドオンとして利用できます。 + +## リリースサポートタイムライン + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
バージョン発売日メンテナンスサポート終了日サポートサポート終了日延長サポート
3.152025-02-202026-06-202026-12-17お問い合わせ
3.142024-11-222026-02-202026-08-18お問い合わせ
3.132024-07-082025-11-222026-05-21お問い合わせ
3.122024-02-172025-07-082026-01-04お問い合わせ
3.112023-12-272025-02-162025-08-15お問い合わせ
3.102023-07-202024-12-262025-06-24お問い合わせ
3.9*2023-04-272024-07-192025-01-15お問い合わせ
3.8*2023-01-172024-04-262024-10-23お問い合わせ
3.7*2022-09-032024-01-172024-07-15お問い合わせ
3.6*2022-07-082023-09-032024-03-01お問い合わせ
3.5*2022-02-162023-07-082024-01-04お問い合わせ
3.4*2021-12-022023-02-162023-08-15お問い合わせ
+ +\* この製品バージョンは、メンテナンスサポートまたはアシスタンスサポートではサポートされなくなりました。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/requirements.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/requirements.mdx new file mode 100644 index 00000000..a2bc5c3d --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/requirements.mdx @@ -0,0 +1,259 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB の要件 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB を正しく使用するために必要なツールとそのバージョンについて説明します。 + +## クライアント SDK + +ScalarDB は Java で記述されているため、ScalarDB を操作する最も簡単な方法は、Java Client SDK を使用することです。 + +- [ScalarDB Core 用 SDK](add-scalardb-to-your-build.mdx) +- [ScalarDB Cluster 用 SDK](scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx) + +### Java + +次の Java Software Development (JDK) が検証され、サポートされています。 + +- **[Oracle JDK](https://www.oracle.com/java/):** 8、11、17、または21 (LTS バージョン) +- **[OpenJDK](https://openjdk.org/) ([Eclipse Temurin](https://adoptium.net/temurin/)、[Amazon Corretto](https://aws.amazon.com/corretto/)、または [Microsoft Build of OpenJDK](https://learn.microsoft.com/en-us/java/openjdk/)):** 8、11、17、または21 (LTS バージョン) + +### .NET + +ScalarDB は、ScalarDB Cluster と呼ばれる gRPC サーバーとして提供され、proto ファイルから生成された .NET クライアントをラップする [.NET Client SDK](scalardb-cluster-dotnet-client-sdk/index.mdx) も備えています。 + +次の .NET バージョンが検証され、サポートされています。 + +- [.NET 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) +- [.NET 6.0](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) + +### その他の言語 + +ScalarDB Cluster は gRPC バージョン1.65.0を使用するため、好みの言語で生成されたクライアントを使用して独自のクライアントを作成できます。 + +## データベース + +ScalarDB は、次のデータベースとそのバージョン上で実行されるミドルウェアです。 + +### リレーショナルデータベース + + + + +| バージョン | Oracle Database 23ai | Oracle Database 21c | Oracle Database 19c | +|:------------------|:---------------------|:--------------------|:--------------------| +| **ScalarDB 3.15** | ✅ | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | ✅ | + + + + +| バージョン | MySQL 8.4 | MySQL 8.0 | +|:------------------|:----------|:----------| +| **ScalarDB 3.15** | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | + + + + +| バージョン | PostgreSQL 17 | PostgreSQL 16 | PostgreSQL 15 | PostgreSQL 14 | PostgreSQL 13 | +|:------------------|:--------------|:--------------|:--------------|:--------------|---------------| +| **ScalarDB 3.15** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | ✅ | ✅ | ✅ | + + + + +| バージョン | Aurora MySQL 3 | Aurora MySQL 2 | +|:------------------|:---------------|:---------------| +| **ScalarDB 3.15** | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | + + + + +| バージョン | Aurora PostgreSQL 16 | Aurora PostgreSQL 15 | Aurora PostgreSQL 14 | Aurora PostgreSQL 13 | +|:------------------|:---------------------|:---------------------|:---------------------|:---------------------| +| **ScalarDB 3.15** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | ✅ | ✅ | + + + + +| バージョン | MariaDB 11.4 | MariaDB 10.11 | +|:------------------|:-------------|:--------------| +| **ScalarDB 3.15** | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | + + + + +| バージョン | SQL Server 2022 | SQL Server 2019 | SQL Server 2017 | +|:------------------|:----------------|:----------------|:----------------| +| **ScalarDB 3.15** | ✅ | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | ✅ | + + + + +| バージョン | SQLite 3 | +|:------------------|:---------| +| **ScalarDB 3.15** | ✅ | +| **ScalarDB 3.14** | ✅ | +| **ScalarDB 3.13** | ✅ | +| **ScalarDB 3.12** | ✅ | +| **ScalarDB 3.11** | ✅ | +| **ScalarDB 3.10** | ✅ | +| **ScalarDB 3.9** | ✅ | +| **ScalarDB 3.8** | ❌ | +| **ScalarDB 3.7** | ❌ | + + + + +| バージョン | YugabyteDB 2 | +|:------------------|:-------------| +| **ScalarDB 3.15** | ✅ | +| **ScalarDB 3.14** | ✅ | +| **ScalarDB 3.13** | ✅ | +| **ScalarDB 3.12** | ❌ | +| **ScalarDB 3.11** | ❌ | +| **ScalarDB 3.10** | ❌ | +| **ScalarDB 3.9** | ❌ | +| **ScalarDB 3.8** | ❌ | +| **ScalarDB 3.7** | ❌ | + + + + +### NoSQL データベース + + + + +| バージョン | DynamoDB | +|:------------------|:---------| +| **ScalarDB 3.15** | ✅ | +| **ScalarDB 3.14** | ✅ | +| **ScalarDB 3.13** | ✅ | +| **ScalarDB 3.12** | ✅ | +| **ScalarDB 3.11** | ✅ | +| **ScalarDB 3.10** | ✅ | +| **ScalarDB 3.9** | ✅ | +| **ScalarDB 3.8** | ✅ | +| **ScalarDB 3.7** | ✅ | + + + + +| バージョン | Cassandra 4.1 | Cassandra 4.0 | Cassandra 3.11 | Cassandra 3.0 | +|:------------------|:--------------|:--------------|:---------------|:--------------| +| **ScalarDB 3.15** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.14** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.13** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.12** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.11** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.10** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.9** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.8** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.7** | ❌ | ❌ | ✅ | ✅ | + + + + +| バージョン | Cosmos DB for NoSQL | +|:------------------|:--------------------| +| **ScalarDB 3.15** | ✅ | +| **ScalarDB 3.14** | ✅ | +| **ScalarDB 3.13** | ✅ | +| **ScalarDB 3.12** | ✅ | +| **ScalarDB 3.11** | ✅ | +| **ScalarDB 3.10** | ✅ | +| **ScalarDB 3.9** | ✅ | +| **ScalarDB 3.8** | ✅ | +| **ScalarDB 3.7** | ✅ | + + + + +:::note + +各データベースの設定方法の詳細については、[ScalarDB の基盤となるデータベースの設定](./database-configurations.mdx) を参照してください。 + +::: + +## Kubernetes + +ScalarDB は、本番環境では Kubernetes プラットフォーム上の Pod として提供されます。ScalarDB は次のプラットフォームとツールをサポートしています。 + +### プラットフォーム + +- **[Kubernetes](https://kubernetes.io/):** 1.28 - 1.32 + - **[Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/jp/eks/)** + - **[Azure Kubernetes Service (AKS)](https://azure.microsoft.com/ja-jp/products/kubernetes-service)** +- **[Red Hat OpenShift](https://www.redhat.com/en/technologies/cloud-computing/openshift):** TBD + +### パッケージマネージャー + +- **[Helm](https://helm.sh/):** 3.5+ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/roadmap.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/roadmap.mdx new file mode 100644 index 00000000..2bb80719 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/roadmap.mdx @@ -0,0 +1,137 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB ロードマップ + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このロードマップは、ScalarDB の今後の計画の概要を示しています。このロードマップの目的は、今後どのような変更が行われる可能性があるかを把握できるようにし、進捗状況をより詳しく追跡し、主要なマイルストーンを把握し、開発中にフィードバックを提供することです。このロードマップは、ScalarDB の新しいバージョンがリリースされるたびに更新されます。 + +:::warning + +開発の過程で、このロードマップはユーザーのニーズやフィードバックに基づいて変更される可能性があります。**このロードマップの内容に従ってリリース計画をスケジュールしないでください。** + +機能リクエストがある場合、または機能開発を優先したい場合は、[GitHub](https://github.com/scalar-labs/scalardb/issues) で問題を作成してください。 + +::: + +### CY2025 Q2 + +#### 追加のデータベースのサポート + +- **IBM Db2** + - ユーザーは、ScalarDB Cluster を介して基盤となるデータベースとして IBM Db2 を使用できるようになります。 +- **TiDB** + - ユーザーは、ScalarDB Cluster を介して基盤となるデータベースとして TiDB を使用できるようになります。 +- **Databricks** + - ユーザーは、ScalarDB Cluster と ScalarDB Analytics を介して基盤となるデータベースとして Databricks を使用できます。 +- **Snowflake** + - ユーザーは、ScalarDB Cluster と ScalarDB Analytics を介して基盤となるデータベースとして Snowflake を使用できます。 + +#### ユーザビリティ + +- **10進データ型の追加** + - ユーザーは10進データ型を使用できるため、10進数を高精度で処理できます。 +- **Extra-write strategy の削除** + - ユーザーは、トランザクションをシリアライザブルにするためのオプションである extra-write strategy を使用できなくなります。ScalarDB は現在、トランザクションをシリアライザブルにするために2つの戦略 (extra-read strategy と extra-write strategy) を提供していますが、extra-write strategy にはいくつかの制限があります。たとえば、ユーザーは同じトランザクションで書き込み操作とスキャン操作を発行できません。したがって、この戦略は削除され、ユーザーはアプリケーションを作成するときにこのような制限について心配する必要がなくなります。 +- **ScalarDB Analytics のガバナンスの改善** + - ユーザーは、ScalarDB Core 機能を使用して認証および認可できるようになります。 + +#### パフォーマンス + +- **読み取りコミット分離の追加** + - ユーザーは、強い正確性を必要としないアプリケーションのパフォーマンスを向上させるために、read-committed 分離レベルでトランザクションを実行できるようになります。 +- **1フェーズコミットの最適化** + - ユーザーは、トランザクションの操作がすべて単一のデータベースまたは単一のパーティションに適用される場合、1フェーズコミットを使用してトランザクションをより効率的に実行できるようになります。 +- **データベースごとに複数の書き込み操作を最適化** + - ユーザーは、データベースに対して複数の書き込み操作がある場合、準備フェーズおよびコミットフェーズにおける書き込み処理をそれぞれのフェーズごとにまとめて実行することによりトランザクションをより効率的に実行できるようになります。 +- **読み取り専用トランザクションの最適化** + - ユーザーは、トランザクションをコミットする際にコーディネーターの書き込みを回避することで、トランザクションをより効率的に実行できるようになります。 +- **ScalarDB Analytics での WAL-interpreted view の削除** + - ユーザーは、WAL-interpreted view の代わりに ScalarDB Core を使用してコミットされたデータを読み取ることができます。これにより、性能の改善が期待できます。 + +#### クラウドサポート + +- **ScalarDB Cluster 向け Azure Marketplace のコンテナ提供** + - ユーザーは、Azure コンテナオファリングを使用して ScalarDB Cluster をデプロイできるようになります。これにより、従量課金制のサブスクリプションモデルを使用できます。 +- **ScalarDB Cluster の Google Cloud Platform (GCP) サポート** + - ユーザーは、GCP の Google Kubernetes Engine (GKE) で ScalarDB Cluster をデプロイできるようになります。 +- **ScalarDB Analytics 向け Amazon Marketplace のコンテナ提供** + - ユーザーは、コンテナオファリングを使用して ScalarDB Analytics をデプロイできるようになります。これにより、従量課金制のサブスクリプションモデルを使用できます。 + +### CY2025 Q3 + +#### 新機能 + +- **分離されたメタデータ管理** + - ユーザーは、既存アプリケーションのスキーマを移行または変更することなく、トランザクションメタデータを別の場所で管理することで ScalarDB Cluster を使用開始できるようになります。 + +#### ユーザビリティ + +- **ビュー** + - ユーザーは、複数の異なるデータベースをより簡単でシンプルな方法で管理できるように、ビューを定義できるようになります。 +- **集計用の SQL 操作の追加** + - ユーザーは、ScalarDB SQL で集計操作を発行できるようになります。 +- **大規模スキャンによるメモリ不足エラーの排除** + - ユーザーは、メモリ不足エラーを経験することなく、大規模スキャンを発行できます。 +- **一時停止期間中の読み取り操作の有効化** + - ユーザーは、一時停止期間中でも読み取り操作を発行できるため、バックアップを取りながらデータを読み取ることができます。 + +#### スケーラビリティと可用性 + +- **半同期レプリケーション** + - ユーザーは、災害復旧可能な方法で ScalarDB ベースのアプリケーションのデータを複製できます。たとえば、東京でプライマリサービスを提供し、大阪でスタンバイサービスを提供するとします。東京で壊滅的な障害が発生した場合、プライマリサービスを大阪に切り替えることで、データ損失や長時間のダウンタイムなしでサービスを継続できます。 + +### CY2025 Q4 + +#### 新機能 + +- **ネイティブセカンダリインデックス** + - ユーザーは、柔軟なセカンダリインデックスを定義できるようになります。既存のセカンダリインデックスは、サポートされているデータベースのセカンダリインデックスの共通機能に基づいて実装されているため、たとえば複数列のインデックスを定義することはできません。新しいセカンダリインデックスは ScalarDB レイヤーで作成されるため、複数列インデックスのような柔軟なインデックスを作成できます。 +- **ユニバーサルカタログ** + - ユーザーは、運用系および分析系データベースのメタデータ(スキーマやセマンティック情報を含む)を、異なるビジネスドメイン間で統一的に管理できるようになります。 +- **ユニバーサルな認証および認可** + - ユーザーは、統一された認証および認可方法を使用して、ScalarDB Cluster と ScalarDB Analytics へのアクセス権を付与されることが可能になります。 + +#### 追加のデータベース(オブジェクトストレージ)のサポート + +- **Azure Blob Storage** + - ユーザーは、ScalarDB Cluster を介して基盤となるデータベースとして Azure Blob Storage を使用できるようになります。 +- **Amazon S3** + - ユーザーは、ScalarDB Cluster を介して基盤となるデータベースとして Amazon S3 を使用できるようになります。 +- **Google Cloud Storage** + - ユーザーは、ScalarDB Cluster および ScalarDB Analytics を介して基盤となるデータベースとして Google Cloud Storage を使用できるようになります。 + +#### パフォーマンス + +- **ScalarDB メタデータの管理に必要なストレージ領域の削減** + - ユーザーが ScalarDB を実行するために使用するストレージ領域が少なくなる可能性があります。ScalarDB は、コミットされたトランザクションがコミットされた後に、コミットされたトランザクションの以前のイメージを削除します。ただし、コミットされたトランザクションが実際のストレージ領域に影響を与えるかどうかは、基礎となるデータベースによって異なります。 + +#### クラウドサポート + +- **Red Hat OpenShift サポート** + - ユーザーは、OpenShift 環境で ScalarDB Cluster 用の Red Hat 認定 Helm Charts を使用できます。 +- **Google Cloud Marketplace のコンテナオファリング** + - ユーザーは、Google Cloud コンテナオファリングを使用して ScalarDB Cluster をデプロイできます。これにより、ユーザーは従量課金制のサブスクリプションモデルを使用できます。 + +### CY2026 + +- **監査ログ** + - ユーザーは、主に監査目的のために ScalarDB Cluster および Analytics のアクセスログを表示および管理できるようになります。 +- **ストアドプロシージャ** + - ユーザーはストアドプロシージャを定義できるようになり、複雑なロジックを持つ一連の操作を ScalarDB Cluster 内で実行できるようになります。 +- **トリガー** + - ユーザーはトリガーを定義できるようになり、ScalarDB Cluster で特定のイベントが発生した際に自動的に一連の操作を実行できるようになります。 +- **ユーザー定義関数 (UDF)** + - ユーザーは関数を定義できるようになり、SQL 内で関数を使用してより簡単な方法で複雑なロジックを表現できるようになります。 +- **ソート用の SQL 操作の追加** + - ユーザーは、複数のデータベースまたは非 JDBC データベースに対して、ScalarDB SQL で任意のソート (ORDER BY) 操作を発行できるようになります。(現在、ScalarDB はクラスタリングキーを使用したソート操作、または単一の JDBC データベースに対する任意のソート操作を発行できます。) +- **さらなるデータ型の追加** + - ユーザーは JSON などの複雑なデータ型を使用できるようになります。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-non-transactional-storage-operations-through-library.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-non-transactional-storage-operations-through-library.mdx new file mode 100644 index 00000000..ea0259aa --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-non-transactional-storage-operations-through-library.mdx @@ -0,0 +1,275 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# コアライブラリを通じて非トランザクションストレージ操作を実行する + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB Core ライブラリを通じて非トランザクションストレージ操作を実行する方法について説明します。 + +## 準備 + +このガイドでは、ScalarDB サンプルリポジトリのサンプルを使用して、データベースと ScalarDB をセットアップします。 + +### ScalarDB サンプルリポジトリのクローンを作成する + +**Terminal** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、必要なファイルが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-sample +``` + +## データベースをセットアップする + +データベースを選択し、指示に従って ScalarDB 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](requirements.mdx#データベース)を参照してください。 + + + +

MySQLをローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://localhost:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://localhost:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//localhost:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://localhost:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントをお持ちでない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを設定する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル**を**強力**に設定します。 + +

ScalarDB を設定する

+ + 以下の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。`scalar.db.contact_points` と `scalar.db.password` の値は、説明に従って必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + ```console + docker compose up -d cassandra + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +ScalarDB の設定の包括的なリストについては、[ScalarDB 設定](configurations.mdx)を参照してください。 + +## 非トランザクションストレージ操作を実行するようにScalarDBを設定する + +非トランザクションストレージ操作を実行するには、設定ファイル **database.properties** で `scalar.db.transaction_manager` プロパティを `single-crud-operation` に設定する必要があります。 + +```properties +scalar.db.transaction_manager=single-crud-operation +``` + +## スキーマを作成またはインポートする + +ScalarDB には、実装固有のデータモデルとスキーマにマップされる独自のデータモデルとスキーマがあります。 + +- **データベーススキーマを作成する必要がありますか?** [ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 +- **既存のデータベースをインポートする必要がありますか?** [ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](schema-loader-import.mdx)を参照してください。 + +## Java アプリケーションを作成する + +このセクションでは、ScalarDB Core ライブラリをプロジェクトに追加する方法と、Java を使用して非トランザクションストレージ操作を実行するように設定する方法について説明します。 + +### ScalarDB をプロジェクトに追加する + +ScalarDB ライブラリは、[Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb) で入手できます。Gradle または Maven を使用して、ライブラリをビルド依存関係としてアプリケーションに追加できます。 + +ビルドツールを選択し、手順に従って ScalarDB のビルド依存関係をアプリケーションに追加します。 + + + + Gradle を使用して ScalarDB のビルド依存関係を追加するには、アプリケーションの `build.gradle` に以下を追加します。 + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb:3.15.4' + } + ``` + + + Maven を使用して ScalarDB のビルド依存関係を追加するには、アプリケーションの `pom.xml` に以下を追加します。 + + ```xml + + com.scalar-labs + scalardb + 3.15.4 + + ``` + + + +### Java API を使用する + +Java API の詳細については、[ScalarDB Java API ガイド](api-guide.mdx)を参照してください。 + +:::note + +非トランザクションストレージ操作には、次の制限が適用されます: + +- トランザクションの開始はサポートされていません。詳細については、[トランザクションを開始せずにトランザクションを実行する](api-guide.mdx#トランザクションを開始せずにトランザクションを実行する)を参照してください。 +- 1つのトランザクションで複数のミューテーションを実行することはサポートされていません。 + +::: + +### 詳細はこちら + +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.15.4/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-non-transactional-storage-operations-through-primitive-crud-interface.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-non-transactional-storage-operations-through-primitive-crud-interface.mdx new file mode 100644 index 00000000..c0bd067f --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-non-transactional-storage-operations-through-primitive-crud-interface.mdx @@ -0,0 +1,881 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# プリミティブ CRUD インターフェースを介して非トランザクションストレージ操作を実行する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、プリミティブ CRUD インターフェース (Storage API とも呼ばれる) を通じて非トランザクションストレージ操作を実行する方法について説明します。このガイドでは、読者が ScalarDB について高度な知識を持っていることを前提としています。 + +既存のストレージおよびデータベースシステム上でストレージに依存しない、またはデータベースに依存しない ACID トランザクションを実現するためのキーの1つは、ScalarDB が提供するストレージ抽象化機能です。ストレージ抽象化は、[データモデル](design.mdx#データモデル) と、データモデルに基づいて操作を発行する API (Storage API) を定義します。 + +ほとんどの場合、[Transactional API](api-guide.mdx#transactional-api) を使用することになりますが、別のオプションとして Storage API を使用することもできます。 + +Storage API を使用する利点は次のとおりです。 + +- トランザクション API と同様に、基盤となるストレージ実装についてあまり気にせずにアプリケーションコードを作成できます。 +- アプリケーション内の一部のデータに対してトランザクションが必要ない場合は、Storage API を使用してトランザクションを部分的に回避し、実行を高速化できます。 + +:::warning + +ストレージ API を直接使用したり、トランザクション API とストレージ API を混在させたりした場合、予期しない動作が発生する可能性があります。たとえば、ストレージ API はトランザクション機能を提供できないため、操作の実行時に障害が発生すると、API によって異常やデータの不整合が発生する可能性があります。 + +したがって、ストレージ API の使用には *非常に* 注意し、何をしているのかを正確に理解している場合にのみ使用してください。 + +::: + +## ストレージ API の例 + +このセクションでは、基本的な電子マネーアプリケーションでストレージ API を使用する方法について説明します。 + +:::warning + +この例では電子マネーアプリケーションが簡略化されており、実稼働環境には適していません。 + +::: + +### ScalarDB の設定 + +開始する前に、[ScalarDB をはじめよう](getting-started-with-scalardb.mdx) で説明されているのと同じ方法で ScalarDB を設定する必要があります。 + +これを念頭に置いて、このストレージ API の例では、設定ファイル `scalardb.properties` が存在することを前提としています。 + +### データベーススキーマの設定 + +アプリケーションでデータベーススキーマ (データを整理する方法) を定義する必要があります。サポートされているデータ型の詳細については、[ScalarDB と他のデータベース間のデータ型マッピング](schema-loader.mdx#scalardb-と他のデータベース間のデータ型マッピング)を参照してください。 + +この例では、`scalardb/docs/getting-started` ディレクトリに `emoney-storage.json` という名前のファイルを作成します。次に、次の JSON コードを追加してスキーマを定義します。 + +:::note + +次の JSON では、`transaction` フィールドが `false` に設定されており、このテーブルを Storage API で使用する必要があることを示しています。 + +::: + +```json +{ + "emoney.account": { + "transaction": false, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } +} +``` + +スキーマを適用するには、[ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) ページに移動し、使用している ScalarDB のバージョンに一致する ScalarDB Schema Loader を `getting-started` フォルダーにダウンロードします。 + +次に、`` をダウンロードした ScalarDB Schema Loader のバージョンに置き換えて、次のコマンドを実行します。 + +```console +java -jar scalardb-schema-loader-.jar --config scalardb.properties -f emoney-storage.json +``` + +### サンプルコード + +以下は、Storage API を使用する電子マネーアプリケーションのサンプルソースコードです。 + +:::warning + +前述のとおり、Storage API はトランザクション機能を提供できないため、操作の実行中に障害が発生すると、API によって異常やデータの不整合が発生する可能性があります。したがって、Storage API の使用には十分注意し、何をしているのかを正確に理解している場合にのみ使用してください。 + +::: + +```java +public class ElectronicMoney { + + private static final String SCALARDB_PROPERTIES = + System.getProperty("user.dir") + File.separator + "scalardb.properties"; + private static final String NAMESPACE = "emoney"; + private static final String TABLENAME = "account"; + private static final String ID = "id"; + private static final String BALANCE = "balance"; + + private final DistributedStorage storage; + + public ElectronicMoney() throws IOException { + StorageFactory factory = StorageFactory.create(SCALARDB_PROPERTIES); + storage = factory.getStorage(); + } + + public void charge(String id, int amount) throws ExecutionException { + // Retrieve the current balance for id + Get get = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, id)) + .build(); + Optional result = storage.get(get); + + // Calculate the balance + int balance = amount; + if (result.isPresent()) { + int current = result.get().getInt(BALANCE); + balance += current; + } + + // Update the balance + Put put = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, id)) + .intValue(BALANCE, balance) + .build(); + storage.put(put); + } + + public void pay(String fromId, String toId, int amount) throws ExecutionException { + // Retrieve the current balances for ids + Get fromGet = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, fromId)) + .build(); + Get toGet = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, toId)) + .build(); + Optional fromResult = storage.get(fromGet); + Optional toResult = storage.get(toGet); + + // Calculate the balances (it assumes that both accounts exist) + int newFromBalance = fromResult.get().getInt(BALANCE) - amount; + int newToBalance = toResult.get().getInt(BALANCE) + amount; + if (newFromBalance < 0) { + throw new RuntimeException(fromId + " doesn't have enough balance."); + } + + // Update the balances + Put fromPut = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, fromId)) + .intValue(BALANCE, newFromBalance) + .build(); + Put toPut = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, toId)) + .intValue(BALANCE, newToBalance) + .build(); + storage.put(fromPut); + storage.put(toPut); + } + + public int getBalance(String id) throws ExecutionException { + // Retrieve the current balances for id + Get get = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, id)) + .build(); + Optional result = storage.get(get); + + int balance = -1; + if (result.isPresent()) { + balance = result.get().getInt(BALANCE); + } + return balance; + } + + public void close() { + storage.close(); + } +} +``` + +## ストレージ API ガイド + +ストレージ API は、管理 API と CRUD API で設定されています。 + +### 管理 API + +このセクションで説明するように、管理操作をプログラムで実行できます。 + +:::note + +管理操作を実行するために使用できる別の方法は、[Schema Loader](schema-loader.mdx) を使用することです。 + +::: + +#### `DistributedStorageAdmin` インスタンスを取得する + +管理操作を実行するには、まず `DistributedStorageAdmin` インスタンスを取得する必要があります。次のように `StorageFactory` から `DistributedStorageAdmin` インスタンスを取得できます。 + +```java +StorageFactory storageFactory = StorageFactory.create(""); +DistributedStorageAdmin admin = storageFactory.getStorageAdmin(); +``` + +設定の詳細については、[ScalarDB 設定](configurations.mdx)を参照してください。 + +すべての管理操作を実行したら、次のように `DistributedStorageAdmin` インスタンスを閉じる必要があります。 + +```java +admin.close(); +``` + +#### 名前空間を作成する + +テーブルは1つの名前空間に属するため、テーブルを作成する前に名前空間を作成する必要があります。 + +名前空間は次のように作成できます。 + +```java +// Create the namespace "ns". If the namespace already exists, an exception will be thrown. +admin.createNamespace("ns"); + +// Create the namespace only if it does not already exist. +boolean ifNotExists = true; +admin.createNamespace("ns", ifNotExists); + +// Create the namespace with options. +Map options = ...; +admin.createNamespace("ns", options); +``` + +作成オプションの詳細については、[作成オプション](api-guide.mdx#作成オプション)を参照してください。 + +#### テーブルを作成する + +テーブルを作成するときは、テーブルメタデータを定義してからテーブルを作成する必要があります。 + +テーブルメタデータを定義するには、`TableMetadata` を使用できます。次に、テーブルの列、パーティションキー、クラスタリングキー (クラスタリング順序を含む)、およびセカンダリインデックスを定義する方法を示します。 + +```java +// Define the table metadata. +TableMetadata tableMetadata = + TableMetadata.newBuilder() + .addColumn("c1", DataType.INT) + .addColumn("c2", DataType.TEXT) + .addColumn("c3", DataType.BIGINT) + .addColumn("c4", DataType.FLOAT) + .addColumn("c5", DataType.DOUBLE) + .addPartitionKey("c1") + .addClusteringKey("c2", Scan.Ordering.Order.DESC) + .addClusteringKey("c3", Scan.Ordering.Order.ASC) + .addSecondaryIndex("c4") + .build(); +``` + +ScalarDB のデータモデルの詳細については、[データモデル](design.mdx#データモデル)を参照してください。 + +次に、次のようにテーブルを作成します。 + +```java +// Create the table "ns.tbl". If the table already exists, an exception will be thrown. +admin.createTable("ns", "tbl", tableMetadata); + +// Create the table only if it does not already exist. +boolean ifNotExists = true; +admin.createTable("ns", "tbl", tableMetadata, ifNotExists); + +// Create the table with options. +Map options = ...; +admin.createTable("ns", "tbl", tableMetadata, options); +``` + +#### セカンダリインデックスを作成する + +セカンダリインデックスは次のように作成できます。 + +```java +// Create a secondary index on column "c5" for table "ns.tbl". If a secondary index already exists, an exception will be thrown. +admin.createIndex("ns", "tbl", "c5"); + +// Create the secondary index only if it does not already exist. +boolean ifNotExists = true; +admin.createIndex("ns", "tbl", "c5", ifNotExists); + +// Create the secondary index with options. +Map options = ...; +admin.createIndex("ns", "tbl", "c5", options); +``` + +#### テーブルに新しい列を追加する + +次のように、テーブルに新しい非パーティションキー列を追加できます。 + +```java +// Add a new column "c6" with the INT data type to the table "ns.tbl". +admin.addNewColumnToTable("ns", "tbl", "c6", DataType.INT) +``` + +:::warning + +テーブルに新しい列を追加する場合は、基盤となるストレージによって実行時間が大きく異なる可能性があるため、慎重に検討する必要があります。それに応じて計画を立て、特にデータベースが本番環境で実行されている場合は、次の点を考慮してください。 + +- **Cosmos DB for NoSQL および DynamoDB の場合:** テーブルスキーマは変更されないため、列の追加はほぼ瞬時に行われます。別のテーブルに格納されているテーブルメタデータのみが更新されます。 +- **Cassandra の場合:** 列を追加すると、スキーマメタデータのみが更新され、既存のスキーマレコードは変更されません。クラスタートポロジが実行時間の主な要因です。スキーマメタデータの変更は、ゴシッププロトコルを介して各クラスターノードに共有されます。このため、クラスターが大きいほど、すべてのノードが更新されるまでの時間が長くなります。 +- **リレーショナルデータベース (MySQL、Oracle など) の場合:** 列の追加は実行にそれほど時間がかかりません。 + +::: + +#### テーブルを切り捨てる + +テーブルを切り捨てるには、次のようにします。 + +```java +// Truncate the table "ns.tbl". +admin.truncateTable("ns", "tbl"); +``` + +#### セカンダリインデックスを削除する + +セカンダリインデックスは次のように削除できます。 + +```java +// Drop the secondary index on column "c5" from table "ns.tbl". If the secondary index does not exist, an exception will be thrown. +admin.dropIndex("ns", "tbl", "c5"); + +// Drop the secondary index only if it exists. +boolean ifExists = true; +admin.dropIndex("ns", "tbl", "c5", ifExists); +``` + +#### テーブルを削除する + +テーブルを削除するには、次のようにします。 + +```java +// Drop the table "ns.tbl". If the table does not exist, an exception will be thrown. +admin.dropTable("ns", "tbl"); + +// Drop the table only if it exists. +boolean ifExists = true; +admin.dropTable("ns", "tbl", ifExists); +``` + +#### 名前空間を削除する + +名前空間を削除するには、次のようにします。 + +```java +// Drop the namespace "ns". If the namespace does not exist, an exception will be thrown. +admin.dropNamespace("ns"); + +// Drop the namespace only if it exists. +boolean ifExists = true; +admin.dropNamespace("ns", ifExists); +``` + +#### 既存の名前空間を取得する + +既存の名前空間は次のように取得できます。 + +```java +Set namespaces = admin.getNamespaceNames(); +``` + +#### 名前空間のテーブルを取得する + +名前空間のテーブルは次のように取得できます。 + +```java +// Get the tables of the namespace "ns". +Set tables = admin.getNamespaceTableNames("ns"); +``` + +#### テーブルメタデータを取得する + +テーブルメタデータは次のように取得できます。 + +```java +// Get the table metadata for "ns.tbl". +TableMetadata tableMetadata = admin.getTableMetadata("ns", "tbl"); +``` + +#### 名前空間を修復する + +名前空間が不明な状態の場合 (名前空間が基盤となるストレージに存在するが ScalarDB メタデータが存在しない、またはその逆)、このメソッドは必要に応じて名前空間とそのメタデータを再作成します。 + +名前空間は次のように修復できます。 + +```java +// Repair the namespace "ns" with options. +Map options = ...; + admin.repairNamespace("ns", options); +``` + +#### テーブルを修復する + +テーブルが不明な状態の場合 (テーブルは基盤となるストレージに存在するが ScalarDB メタデータは存在しない、またはその逆)、このメソッドは必要に応じてテーブル、そのセカンダリインデックス、およびそのメタデータを再作成します。 + +テーブルは次のように修復できます。 + +```java +// Repair the table "ns.tbl" with options. +TableMetadata tableMetadata = + TableMetadata.newBuilder() + ... + .build(); +Map options = ...; +admin.repairTable("ns", "tbl", tableMetadata, options); +``` + +#### 最新の ScalarDB API をサポートするように環境をアップグレードする + +ScalarDB API の最新バージョンをサポートするように ScalarDB 環境をアップグレードできます。通常、リリースノートに記載されているように、アプリケーション環境が使用する ScalarDB バージョンを更新した後、このメソッドを実行する必要があります。 + +```java +// Upgrade the ScalarDB environment. +Map options = ...; +admin.upgrade(options); +``` + +### CRUD 操作を実装する + +次のセクションでは、CRUD 操作について説明します。 + +#### `DistributedStorage` インスタンスを取得する + +Storage API で CRUD 操作を実行するには、`DistributedStorage` インスタンスを取得する必要があります。 + +インスタンスは次のように取得できます。 + +```java +StorageFactory storageFactory = StorageFactory.create(""); +DistributedStorage storage = storageFactory.getStorage(); +``` + +すべての CRUD 操作を実行したら、次のように `DistributedStorage` インスタンスを閉じる必要があります。 + +```java +storage.close(); +``` + +#### `Get` 操作 + +`Get` は、主キーで指定された単一のレコードを取得する操作です。 + +まず `Get` オブジェクトを作成し、次に次のように `storage.get()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Get` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .projections("c1", "c2", "c3", "c4") + .build(); + +// Execute the `Get` operation. +Optional result = storage.get(get); +``` + +また、投影を指定して、返される列を選択することもできます。 + +`Key` オブジェクトの構築方法の詳細については、[キーの構築](api-guide.mdx#キーの構築)を参照してください。また、`Result` オブジェクトの処理方法の詳細については、[Result オブジェクトの処理](api-guide.mdx#result-オブジェクトの処理)を参照してください。 + +##### 一貫性レベルを指定する + +Storage API の各操作 (`Get`、`Scan`、`Put`、`Delete`) で一貫性レベルを次のように指定できます。 + +```java +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .consistency(Consistency.LINEARIZABLE) // Consistency level + .build(); +``` + +次の表は、3つの一貫性レベルについて説明しています。 + +| 一貫性レベル | 説明 | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `SEQUENTIAL` | 順次一貫性は、基礎となるストレージ実装によってすべての操作が何らかの順次順序で実行されるようにされ、各プロセスの操作がこの順序で実行されることを前提としています。 | +| `EVENTUAL` | 結果一貫性は、基礎となるストレージ実装によってすべての操作が最終的に実行されることを前提としています。 | +| `LINEARIZABLE` | 線形化可能な一貫性は、基礎となるストレージ実装によって各操作が呼び出しから完了までの間のある時点でアトミックに実行されるようにされることを前提としています。 | + +##### セカンダリインデックスを使用して `Get` を実行する + +セカンダリインデックスを使用して `Get` 操作を実行できます。 + +パーティションキーを指定する代わりに、次のようにインデックスキー (インデックス付き列) を指定してセカンダリインデックスを使用できます。 + +```java +// Create a `Get` operation by using a secondary index. +Key indexKey = Key.ofFloat("c4", 1.23F); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .indexKey(indexKey) + .projections("c1", "c2", "c3", "c4") + .build(); + +// Execute the `Get` operation. +Optional result = storage.get(get); +``` + +:::note + +結果に複数のレコードがある場合、`storage.get()` は例外をスローします。 + +::: + +#### `Scan` 操作 + +`Scan` は、パーティション内の複数のレコードを取得する操作です。`Scan` 操作では、クラスタリングキーの境界とクラスタリングキー列の順序を指定できます。 + +まず `Scan` オブジェクトを作成し、次に次のように `storage.scan()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Scan` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key startClusteringKey = Key.of("c2", "aaa", "c3", 100L); +Key endClusteringKey = Key.of("c2", "aaa", "c3", 300L); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .start(startClusteringKey, true) // Include startClusteringKey + .end(endClusteringKey, false) // Exclude endClusteringKey + .projections("c1", "c2", "c3", "c4") + .orderings(Scan.Ordering.desc("c2"), Scan.Ordering.asc("c3")) + .limit(10) + .build(); + +// Execute the `Scan` operation. +Scanner scanner = storage.scan(scan); +``` + +クラスタリングキー境界を省略するか、`start` 境界または `end` 境界のいずれかを指定できます。`orderings` を指定しない場合は、テーブルの作成時に定義したクラスタリング順序で結果が並べられます。 + +さらに、`projections` を指定して返される列を選択し、`limit` を使用して `Scan` 操作で返されるレコードの数を指定できます。 + +##### `Scanner` オブジェクトの処理 + +Storage API の `Scan` 操作は `Scanner` オブジェクトを返します。 + +`Scanner` オブジェクトから結果を1つずつ取得する場合は、次のように `one()` メソッドを使用できます。 + +```java +Optional result = scanner.one(); +``` + +または、すべての結果のリストを取得する場合は、次のように `all()` メソッドを使用できます。 + +```java +List results = scanner.all(); +``` + +さらに、`Scanner` は `Iterable` を実装しているので、次のように for-each ループ内で `Scanner` を使用できます。 + +```java +for (Result result : scanner) { + ... +} +``` + +結果を取得した後は、`Scanner` オブジェクトを閉じることを忘れないでください。 + +```java +scanner.close(); +``` + +または、次のように `try`-with-resources を使用することもできます。 + +```java +try (Scanner scanner = storage.scan(scan)) { + ... +} +``` + +##### セカンダリインデックスを使用して `Scan` を実行する + +セカンダリインデックスを使用して `Scan` 操作を実行できます。 + +パーティションキーを指定する代わりに、次のようにインデックスキー (インデックス付き列) を指定してセカンダリインデックスを使用できます。 + +```java +// Create a `Scan` operation by using a secondary index. +Key indexKey = Key.ofFloat("c4", 1.23F); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .indexKey(indexKey) + .projections("c1", "c2", "c3", "c4") + .limit(10) + .build(); + +// Execute the `Scan` operation. +Scanner scanner = storage.scan(scan); +``` + +:::note + +セカンダリインデックスを使用して、`Scan` でクラスタリングキーの境界と順序を指定することはできません。 + +::: + +##### パーティションキーを指定せずに `Scan` を実行して、テーブルのすべてのレコードを取得します + +パーティションキーを指定せずに `Scan` 操作を実行できます。 + +ビルダーで `partitionKey()` メソッドを呼び出す代わりに、次のように `all()` メソッドを呼び出して、パーティションキーを指定せずにテーブルをスキャンできます。 + +```java +// Create a `Scan` operation without specifying a partition key. +Key partitionKey = Key.ofInt("c1", 10); +Key startClusteringKey = Key.of("c2", "aaa", "c3", 100L); +Key endClusteringKey = Key.of("c2", "aaa", "c3", 300L); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .projections("c1", "c2", "c3", "c4") + .limit(10) + .build(); + +// Execute the `Scan` operation. +Scanner scanner = storage.scan(scan); +``` + +:::note + +パーティションキーを指定せずに `Scan` でクラスタリングキーの境界と順序を指定することはできません。 + +::: + +#### `Put` 操作 + +`Put` は、主キーで指定されたレコードを配置する操作です。この操作はレコードの upsert 操作として動作し、レコードが存在する場合はレコードを更新し、レコードが存在しない場合はレコードを挿入します。 + +まず `Put` オブジェクトを作成し、次に次のように `storage.put()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Put` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Put` operation. +storage.put(put); +``` + +次のように `null` 値を持つレコードを配置することもできます。 + +```java +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", null) + .doubleValue("c5", null) + .build(); +``` + +:::note + +`Put` 操作ビルダーで `enableImplicitPreRead()`、`disableImplicitPreRead()`、または `implicitPreReadEnabled()` を指定した場合、それらは無視されます。 + +::: + +#### `Delete` 操作 + +`Delete` は、主キーで指定されたレコードを削除する操作です。 + +まず `Delete` オブジェクトを作成し、次に次のように `storage.delete()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create a `Delete` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .build(); + +// Execute the `Delete` operation. +storage.delete(delete); +``` + +#### 条件付きの `Put` および `Delete` + +条件をチェックするロジックを実装することで、操作を実行する前に満たす必要がある任意の条件 (たとえば、銀行口座の残高は0以上である必要があります) を記述できます。または、`Put` や `Delete` などのミューテーション操作で単純な条件を記述することもできます。 + +`Put` または `Delete` 操作に条件が含まれている場合、指定された条件が満たされた場合にのみ操作が実行されます。操作の実行時に条件が満たされていない場合は、`NoMutationException` という例外がスローされます。 + +##### `Put` の条件 + +Storage API の `Put` 操作では、指定された条件が一致した場合にのみ `Put` 操作が実行されるようにする条件を指定できます。この操作は、条件が比較され、更新がアトミックに実行される比較とスワップの操作に似ています。 + +`Put` 操作では次のように条件を指定できます。 + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.putIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .condition(condition) // condition + .build(); +``` + +`putIf` 条件以外に、`putIfExists` および `putIfNotExists` 条件を次のように指定できます。 + +```java +// Build a `putIfExists` condition. +MutationCondition putIfExistsCondition = ConditionBuilder.putIfExists(); + +// Build a `putIfNotExists` condition. +MutationCondition putIfNotExistsCondition = ConditionBuilder.putIfNotExists(); +``` + +##### `Delete` の条件 + +`Put` 操作と同様に、Storage API の `Delete` 操作でも条件を指定できます。 + +`Delete` 操作では、次のように条件を指定できます。 + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.deleteIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .condition(condition) // condition + .build(); +``` + +`deleteIf` 条件を使用するだけでなく、次のように `deleteIfExists` 条件を指定することもできます。 + +```java +// Build a `deleteIfExists` condition. +MutationCondition deleteIfExistsCondition = ConditionBuilder.deleteIfExists(); +``` + +#### ミューテート操作 + +ミューテートは、単一のパーティションで複数のミューテート (`Put` および `Delete` 操作) を実行する操作です。 + +まずミューテートオブジェクトを作成し、次に次のように `storage.mutate()` メソッドを使用してオブジェクトを実行する必要があります。 + +```java +// Create `Put` and `Delete` operations. +Key partitionKey = Key.ofInt("c1", 10); + +Key clusteringKeyForPut = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForPut) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +Key clusteringKeyForDelete = Key.of("c2", "bbb", "c3", 200L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForDelete) + .build(); + +// Execute the operations. +storage.mutate(Arrays.asList(put, delete)); +``` + +:::note + +Mutate 操作では、単一のパーティションのミューテーションのみが受け入れられます。それ以外の場合は、例外がスローされます。 + +さらに、Mutate 操作で複数の条件を指定すると、すべての条件が一致した場合にのみ操作が実行されます。 + +::: + +#### CRUD 操作のデフォルト名前空間 + +すべての CRUD 操作のデフォルト名前空間は、ScalarDB 設定のプロパティを使用して設定できます。 + +```properties +scalar.db.default_namespace_name= +``` + +名前空間を指定しない操作では、設定で設定されたデフォルトの名前空間が使用されます。 + +```java +// This operation will target the default namespace. +Scan scanUsingDefaultNamespace = + Scan.newBuilder() + .table("tbl") + .all() + .build(); +// This operation will target the "ns" namespace. +Scan scanUsingSpecifiedNamespace = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .build(); +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-transactions-through-scalardb-core-library.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-transactions-through-scalardb-core-library.mdx new file mode 100644 index 00000000..61e64e40 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/run-transactions-through-scalardb-core-library.mdx @@ -0,0 +1,223 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Core ライブラリを介してトランザクションを実行する + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB Core ライブラリを使用して、ScalarDB プロパティファイルを設定し、1フェーズまたは2フェーズのコミットインターフェイスを介してトランザクションを実行するためのスキーマを作成する方法について説明します。 + +## 準備 + +このガイドでは、ScalarDB サンプルリポジトリのサンプルを使用して、データベースと ScalarDB をセットアップします。 + +### ScalarDB サンプルリポジトリのクローンを作成する + +**Terminal** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、必要なファイルが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-sample +``` + +## データベースをセットアップする + +データベースを選択し、指示に従って ScalarDB 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](requirements.mdx#データベース)を参照してください。 + + + +

MySQLをローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://localhost:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://localhost:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//localhost:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://localhost:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントをお持ちでない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを設定する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル**を**強力**に設定します。 + +

ScalarDB を設定する

+ + 以下の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。`scalar.db.contact_points` と `scalar.db.password` の値は、説明に従って必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-sample` ディレクトリの `docker-compose.yml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d cassandra + ``` + +

ScalarDB を設定する

+ + `scalardb-samples/scalardb-sample` ディレクトリの **database.properties** ファイルには、ScalarDB のデータベース設定が含まれています。**database.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +ScalarDB の設定の包括的なリストについては、[ScalarDB 設定](configurations.mdx)を参照してください。 + +## スキーマを作成またはインポートする + +ScalarDB には、実装固有のデータモデルとスキーマにマップされる独自のデータモデルとスキーマがあります。 + +- **データベーススキーマを作成する必要がありますか?** [ScalarDB Schema Loader](schema-loader.mdx) を参照してください。 +- **既存のデータベースをインポートする必要がありますか?** [ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](schema-loader-import.mdx)を参照してください。 + +## Javaを使用してトランザクションを実行する + +- **1フェーズコミットインターフェイスを使用してトランザクションを実行しますか?** [ScalarDB Java API ガイド](api-guide.mdx#transactional-api)を参照してください。 +- **2フェーズコミットインターフェイスを使用してトランザクションを実行しますか?** [2フェーズコミットインターフェースを使用したトランザクション](two-phase-commit-transactions.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AccessScalarProducts.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AccessScalarProducts.mdx new file mode 100644 index 00000000..156edb6e --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AccessScalarProducts.mdx @@ -0,0 +1,198 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes クラスター環境にデプロイされた ScalarDB または ScalarDL をアプリケーションから利用できるようにする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Kubernetes クラスター環境にデプロイされた ScalarDB または ScalarDL をアプリケーションから利用できるようにする方法について説明します。ScalarDB または ScalarDL をアプリケーションから利用できるようにするには、`-envoy` という名前の Kubernetes サービスリソース経由で Scalar Envoy を使用します。`-envoy` は次のようないくつかの方法で使用できます。 + +* ScalarDB または ScalarDL と同じ Kubernetes クラスター内から直接。 +* Kubernetes クラスターの外部からのロードバランサー経由。 +* `kubectl port-forward` コマンドを使用して踏み台サーバーから実行します (テスト目的のみ)。 + +リソース名 `-envoy` は Helm リリース名に基づいて決定されます。次のコマンドを実行すると、helm リリース名を確認できます。 + +```console +helm list -n ns-scalar +``` + +次のような結果が表示されます: + +```console +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +scalardb ns-scalar 1 2023-02-09 19:31:40.527130674 +0900 JST deployed scalardb-2.5.0 3.8.0 +scalardl-auditor ns-scalar 1 2023-02-09 19:32:03.008986045 +0900 JST deployed scalardl-audit-2.5.1 3.7.1 +scalardl-ledger ns-scalar 1 2023-02-09 19:31:53.459548418 +0900 JST deployed scalardl-4.5.1 3.7.1 +``` + +次のコマンドを実行すると、envoy サービス名 `-envoy` を確認することもできます。 + +```console +kubectl get service -n ns-scalar +``` + +次のような結果が表示されます: + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-envoy LoadBalancer 10.99.245.143 60051:31110/TCP 2m2s +scalardb-envoy-metrics ClusterIP 10.104.56.87 9001/TCP 2m2s +scalardb-headless ClusterIP None 60051/TCP 2m2s +scalardb-metrics ClusterIP 10.111.213.194 8080/TCP 2m2s +scalardl-auditor-envoy LoadBalancer 10.111.141.43 40051:31553/TCP,40052:31171/TCP 99s +scalardl-auditor-envoy-metrics ClusterIP 10.104.245.188 9001/TCP 99s +scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 99s +scalardl-auditor-metrics ClusterIP 10.105.119.158 8080/TCP 99s +scalardl-ledger-envoy LoadBalancer 10.96.239.167 50051:32714/TCP,50052:30857/TCP 109s +scalardl-ledger-envoy-metrics ClusterIP 10.97.204.18 9001/TCP 109s +scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 109s +scalardl-ledger-metrics ClusterIP 10.104.216.189 8080/TCP 109s +``` + +## 同じ Kubernetes クラスター内からサービスリソースを介して、ScalarDB または ScalarDL へのアプリケーション (クライアント) リクエストを直接実行します。 + +アプリケーション (クライアント) を ScalarDB または ScalarDL と同じ Kubernetes クラスターにデプロイする場合 (たとえば、アプリケーション [クライアント] を同じ Kubernetes クラスター内の別のノードグループまたはプールにデプロイする場合)、アプリケーションは次の方法で ScalarDB または ScalarDL にアクセスできます。Kubernetes サービスリソースを使用します。サービスリソース名 (FQDN) の形式は、`-envoy..svc.cluster.local` です。 + +以下は、`ns-scalar` 名前空間での ScalarDB および ScalarDL のデプロイメントの例です。 + +* **ScalarDB Server** + ```console + scalardb-envoy.ns-scalar.svc.cluster.local + ``` +* **ScalarDL Ledger** + ```console + scalardl-ledger-envoy.ns-scalar.svc.cluster.local + ``` +* **ScalarDL Auditor** + ```console + scalardl-auditor-envoy.ns-scalar.svc.cluster.local + ``` + +Kubernetes サービスリソースを使用する場合、アプリケーション (クライアント) のプロパティファイルに上記の FQDN を次のように設定する必要があります。 + +* **ScalarDB Server のクライアントプロパティファイル** + ```properties + scalar.db.contact_points=-envoy..svc.cluster.local + scalar.db.contact_port=60051 + scalar.db.storage=grpc + scalar.db.transaction_manager=grpc + ``` +* **ScalarDL Ledger のクライアントプロパティファイル** + ```properties + scalar.dl.client.server.host=-envoy..svc.cluster.local + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + ``` +* **ScalarDL Auditor モードが有効になっている ScalarDL Ledger のクライアントプロパティファイル** + ```properties + # Ledger + scalar.dl.client.server.host=-envoy..svc.cluster.local + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=-envoy..svc.cluster.local + scalar.dl.auditor.server.port=40051 + scalar.dl.auditor.server.privileged_port=40052 + ``` + +## Kubernetes クラスターの外部からロードバランサー経由で ScalarDB または ScalarDL へのアプリケーション (クライアント) リクエストを実行します + +ScalarDB または ScalarDL の Kubernetes クラスターの外部の環境にアプリケーション (クライアント) をデプロイする場合 (たとえば、アプリケーション [クライアント] を別の Kubernetes クラスター、コンテナープラットフォーム、またはサーバーにデプロイする場合)、アプリケーションは ScalarDB または ScalarDL にアクセスできます。各クラウドサービスが提供するロードバランサーを利用します。 + +カスタム値ファイルで `envoy.service.type` を `LoadBalancer` に設定することで、ロードバランサーを作成できます。カスタム値ファイルを構成した後、ロードバランサーを使用して、Kubernetes サービスリソースを通じて Scalar Envoy を使用できるようになります。注釈を使用してロードバランサーの構成を設定することもできます。 + +カスタム値ファイルの設定方法の詳細については、[サービス設定](../helm-charts/configure-custom-values-envoy.mdx#サービス構成)を参照してください。 + +ロードバランサを使用する場合、アプリケーション (クライアント) のプロパティファイルにロードバランサのFQDNまたはIPアドレスを以下のように設定する必要があります。 + +* **ScalarDB Server のクライアントプロパティファイル** + ```properties + scalar.db.contact_points= + scalar.db.contact_port=60051 + scalar.db.storage=grpc + scalar.db.transaction_manager=grpc + ``` +* **ScalarDL Ledger のクライアントプロパティファイル** + ```properties + scalar.dl.client.server.host= + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + ``` +* **ScalarDL Auditor モードが有効になっている ScalarDL Ledger のクライアントプロパティファイル** + ```properties + # Ledger + scalar.dl.client.server.host= + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host= + scalar.dl.auditor.server.port=40051 + scalar.dl.auditor.server.privileged_port=40052 + ``` + +ロードバランサーの具体的な実装とアクセス方法は、Kubernetes クラスターに依存します。マネージド Kubernetes クラスターを使用している場合は、クラウドサービスプロバイダーに基づいて次の公式ドキュメントを参照してください。 + +* **Amazon Elastic Kubernetes Service (EKS)** + * [Network load balancing on Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/network-load-balancing.html) +* **Azure Kubernetes Service (AKS)** + * [Use a public standard load balancer in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/load-balancer-standard) + * [Use an internal load balancer with Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/internal-lb) + +## 踏み台サーバーから ScalarDB または ScalarDL へのクライアントリクエストを実行します (テスト目的のみ。運用環境では推奨されません) + +`kubectl port-forward` コマンドを実行すると、踏み台サーバーから ScalarDB または ScalarDL へのクライアントリクエストを実行できます。ただし、ScalarDL Auditor モード環境を作成する場合、2つの Kubernetes クラスターにアクセスするには、1つの踏み台サーバーから異なる kubeconfig ファイルを使用して2つの `kubectl port-forward` コマンドを実行する必要があります。 + +1. **(ScalarDL Auditor モードのみ)** ScalarDL Ledger の踏み台サーバーで、ScalarDL Auditor の Kubernetes クラスターにアクセスするために既存の kubeconfig ファイルを構成するか、新しい kubeconfig ファイルを追加します。管理対象の各 Kubernetes クラスターの kubeconfig ファイルを構成する方法の詳細については、[kubeconfig の構成](CreateBastionServer.mdx#kubeconfig-の構成)を参照してください。 +2. 踏み台サーバーから各サービスへのポート転送を構成します。 + * **ScalarDB Server** + ```console + kubectl port-forward -n svc/-envoy 60051:60051 + ``` + * **ScalarDL Ledger** + ```console + kubectl --context port-forward -n svc/-envoy 50051:50051 + kubectl --context port-forward -n svc/-envoy 50052:50052 + ``` + * **ScalarDL Auditor** + ```console + kubectl --context port-forward -n svc/-envoy 40051:40051 + kubectl --context port-forward -n svc/-envoy 40052:40052 + ``` +3. `localhost` 経由で ScalarDB または ScalarDL にアクセスするようにプロパティファイルを設定します。 + * **ScalarDB Server のクライアントプロパティファイル** + ```properties + scalar.db.contact_points=localhost + scalar.db.contact_port=60051 + scalar.db.storage=grpc + scalar.db.transaction_manager=grpc + ``` + * **ScalarDL Ledger のクライアントプロパティファイル** + ```properties + scalar.dl.client.server.host=localhost + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + ``` + * **ScalarDL Auditor モードが有効になっている ScalarDL Ledger のクライアントプロパティファイル** + ```properties + # Ledger + scalar.dl.client.server.host=localhost + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=localhost + scalar.dl.auditor.server.port=40051 + scalar.dl.auditor.server.privileged_port=40052 + ``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AwsMarketplaceGuide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AwsMarketplaceGuide.mdx new file mode 100644 index 00000000..c503f8a6 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AwsMarketplaceGuide.mdx @@ -0,0 +1,472 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# AWS Marketplace を通じて Scalar 製品をインストールする方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Scalar 製品 (ScalarDB、ScalarDL、およびそれらのツール) は、AWS Marketplace でコンテナイメージとして入手できます。 このガイドでは、AWS Marketplace を通じて Scalar 製品をインストールする方法について説明します。 + +:::note + +- 一部の Scalar 製品は商用ライセンスで利用可能であり、AWS Marketplace ではそれらの製品を従量課金制 (PAYG) 料金で提供しています。従量課金制料金を使用する場合、AWS は使用量に基づいて Scalar 製品のライセンス料を請求します。 +- 以前は、AWS Marketplace でライセンス持ち込み (BYOL) オプションが提供されていました。ただし、このオプションは廃止され、削除されたため、AWS Marketplace ではサポートされなくなりました。 +- BYOL オプションは、AWS Marketplace ではなく、次のパブリックコンテナリポジトリで提供されています。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact-jp)ください。 + - [ScalarDB Cluster Enterprise Standard](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-node-byol-standard) + - [ScalarDB Cluster Enterprise Premium](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-node-byol-premium) + - [ScalarDL Ledger](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-ledger-byol) + - [ScalarDL Auditor](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-auditor-byol) + +::: + +## AWS Marketplace から Scalar 製品を購読する + +1. Scalar 製品を選択すると、AWS Marketplace へのリンクが表示されます。 + + + + ScalarDB Enterprise のエディションを選択します。 + + + | PAYG | BYOL (非推奨) | + |:---------------------------------------------------------------------------------|:---------------------------------------------------------------------------------| + | [ScalarDB Cluster](https://aws.amazon.com/marketplace/pp/prodview-jx6qxatkxuwm4) | [ScalarDB Cluster](https://aws.amazon.com/marketplace/pp/prodview-alcwrmw6v4cfy) | + + + | PAYG | BYOL (非推奨) | + |:---------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------| + | [ScalarDB Cluster](https://aws.amazon.com/marketplace/pp/prodview-djqw3zk6dwyk6) | [ScalarDB Cluster](https://aws.amazon.com/marketplace/pp/prodview-alcwrmw6v4cfy) | + + + + + | PAYG | BYOL (非推奨) | + |:---------------------------------------------------------------------------------|:---------------------------------------------------------------------------------| + | [ScalarDL Ledger](https://aws.amazon.com/marketplace/pp/prodview-wttioaezp5j6e) | [ScalarDL Ledger](https://aws.amazon.com/marketplace/pp/prodview-3jdwfmqonx7a2) | + + + | PAYG | BYOL (非推奨) | + |:---------------------------------------------------------------------------------|:---------------------------------------------------------------------------------| + | [ScalarDL Auditor](https://aws.amazon.com/marketplace/pp/prodview-ke3yiw4mhriuu) | [ScalarDL Auditor](https://aws.amazon.com/marketplace/pp/prodview-tj7svy75gu7m6) | + + + +1. [**購読を続ける**] を選択します。 + +1. IAM ユーザーを使用して AWS Marketplace にサインインします。 + すでにサインインしている場合、この手順は自動的にスキップされます。 + +1. **利用規約**を読み、**利用規約に同意する**を選択します。 + 時間がかかります。完了すると、**発効日**列に現在の日付が表示されます。 + また、AWS コンソールの [Manage subscriptions](https://us-east-1.console.aws.amazon.com/marketplace/home#/subscriptions) ページでも製品を確認できます。 + +## Scalar Helm Charts を使用して AWS Marketplace から EKS (Amazon Elastic Kubernetes Service) にコンテナをデプロイする +AWS Marketplace で Scalar 製品をサブスクライブすると、AWS Marketplace のプライベートコンテナレジストリ ([ECR](https://aws.amazon.com/ecr/)) から Scalar 製品のコンテナイメージをプルできます。このセクションでは、プライベートコンテナーレジストリから [EKS](https://aws.amazon.com/eks/) クラスターに従量課金制の価格で Scalar 製品をデプロイする方法について説明します。 + +1. OIDC プロバイダーを作成します。 + + ScalarDL ポッドから AWS Marketplace Metering Service を実行するには、ID およびアクセス管理 (IAM) OpenID Connect (OIDC) プロバイダーを作成する必要があります。 + + ```console + eksctl utils associate-iam-oidc-provider --region --cluster --approve + ``` + + 詳細については、[Creating an IAM OIDC provider for your cluster](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html) を参照してください。 + +1. サービスアカウントを作成します。 + + ポッドが AWS Marketplace Metering Service を実行できるようにするには、[IAM roles for service accounts](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) を使用できます。 + + ```console + eksctl create iamserviceaccount \ + --name \ + --namespace \ + --region \ + --cluster \ + --attach-policy-arn arn:aws:iam::aws:policy/AWSMarketplaceMeteringFullAccess \ + --approve \ + --override-existing-serviceaccounts + ``` + +1. インストールする Scalar 製品の Helm Chart のカスタム値ファイルを更新します。 + カスタム値ファイルの `[].image.repository` の値として、AWS Marketplace のプライベートコンテナレジストリ (ECR) を指定する必要があります。また、前の手順で作成したサービスアカウント名を `[].serviceAccount.serviceAccountName` の値として指定し、 `[].serviceAccount.automountServiceAccountToken` を `true` に設定する必要があります。使用している製品に応じて、次の例を参照してください。 + + + + ScalarDB Enterprise のエディションを選択します。 + + + `scalardb-cluster-standard-custom-values.yaml` ファイル内: + + ```yaml + scalardbCluster: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-cluster-node-aws-payg-standard" + serviceAccount: + serviceAccountName: "" + automountServiceAccountToken: true + ``` + + :::note + + 設定の詳細については、[ScalarDB Cluster のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardb-cluster.mdx)を参照してください。 + + ::: + + + + `scalardb-cluster-premium-custom-values.yaml` ファイル内: + + ```yaml + scalardbCluster: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-cluster-node-aws-payg-premium" + serviceAccount: + serviceAccountName: "" + automountServiceAccountToken: true + ``` + + :::note + + 設定の詳細については、[ScalarDB Cluster のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardb-cluster.mdx)を参照してください。 + + ::: + + + + + +

ScalarDL Ledger

+ + `scalardl-ledger-custom-values.yaml` ファイル内: + + ```yaml + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-ledger-aws-payg" + serviceAccount: + serviceAccountName: "" + automountServiceAccountToken: true + ``` + + :::note + + 設定の詳細については、[ScalarDL Ledger のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-ledger.mdx)を参照してください。 + + ::: + +

ScalarDL Schema Loader for Ledger

+ + `schema-loader-ledger-custom-values.yaml` ファイル内の `[].image.repository` 構成を更新する必要はありません。ScalarDL Schema Loader のコンテナイメージは、[パブリックコンテナリポジトリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader)で提供されています。 + + :::note + + 設定の詳細については、[ScalarDL Schema Loader のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx)を参照してください。 + + ::: + +
+ +

ScalarDL Auditor

+ + `scalardl-auditor-custom-values.yaml` ファイル内: + + ```yaml + auditor: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-auditor-aws-payg" + serviceAccount: + serviceAccountName: "" + automountServiceAccountToken: true + ``` + + :::note + + 設定の詳細については、[ScalarDL Auditor のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-auditor.mdx)を参照してください。 + + ::: + +

ScalarDL Schema Loader for Auditor

+ + `schema-loader-auditor-custom-values.yaml` ファイル内の `[].image.repository` 構成を更新する必要はありません。ScalarDL Schema Loader のコンテナイメージは、[パブリックコンテナリポジトリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader) で提供されています。 + + :::note + + 設定の詳細については、[ScalarDL Schema Loader のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx)を参照してください。 + + ::: + +
+
+ +1. Helm Charts を上記のカスタム値ファイルと組み合わせて使用して、Scalar 製品をデプロイします。使用している製品に応じて、次の例を参照してください。 + + + + ScalarDB Enterprise のエディションを選択します。 + + + ```console + helm install scalardb-cluster-standard scalar-labs/scalardb-cluster -f scalardb-cluster-standard-custom-values.yaml + ``` + + + ```console + helm install scalardb-cluster-premium scalar-labs/scalardb-cluster -f scalardb-cluster-premium-custom-values.yaml + ``` + + + + +

ScalarDL Ledger

+ + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + +

ScalarDL Schema Loader for Ledger

+ + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-ledger-custom-values.yaml + ``` +
+ +

ScalarDL Auditor

+ + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + +

ScalarDL Schema Loader for Auditor

+ + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-auditor-custom-values.yaml + ``` +
+
+ +## **[非推奨] [BYOL]** Scalar Helm Chart を使用して AWS Marketplace から EKS (Amazon Elastic Kubernetes Service) にコンテナをデプロイする + +AWS Marketplace で Scalar 製品をサブスクライブすると、AWS Marketplace のプライベートコンテナレジストリ ([ECR](https://aws.amazon.com/ecr/)) から Scalar 製品のコンテナイメージをプルできます。このセクションでは、プライベートコンテナーレジストリから [EKS](https://aws.amazon.com/eks/) クラスターに BYOL オプションを使用して Scalar 製品をデプロイする方法について説明します。 + +1. インストールする Scalar 製品の Helm Chart のカスタム値ファイルを更新します。 + AWS Marketplace のプライベートコンテナレジストリ (ECR) をカスタム値ファイルの `[].image.repository` の値として指定する必要があります。使用している製品に応じて、次の例を参照してください。 + + + + ```yaml + scalardbCluster: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-cluster-node-aws-byol" + ``` + + :::note + + 設定の詳細については、[ScalarDB Cluster のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardb-cluster.mdx)を参照してください。 + + ::: + + + +

ScalarDL Ledger

+ + `scalardl-ledger-custom-values.yaml` ファイル内: + + ```yaml + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger" + ``` + + :::note + + 設定の詳細については、[ScalarDL Ledger のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-ledger.mdx)を参照してください。 + + ::: + +

ScalarDL Schema Loader for Ledger

+ + `schema-loader-ledger-custom-values.yaml` ファイル内の `[].image.repository` 構成を更新する必要はありません。ScalarDL Schema Loader のコンテナイメージは、[パブリックコンテナリポジトリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader) で提供されています。 + + :::note + + 設定の詳細については、[ScalarDL Schema Loader のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx)を参照してください。 + + ::: + +
+ +

ScalarDL Auditor

+ + `scalardl-auditor-custom-values.yaml` ファイル内: + + ```yaml + auditor: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-auditor" + ``` + + :::note + + 設定の詳細については、[ScalarDL Auditor のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-auditor.mdx)を参照してください。 + + ::: + +

ScalarDL Schema Loader for Auditor

+ + `schema-loader-auditor-custom-values.yaml` ファイル内の `[].image.repository` 構成を更新する必要はありません。ScalarDL Schema Loader のコンテナイメージは、[パブリックコンテナリポジトリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader) で提供されています。 + + :::note + + 設定の詳細については、[ScalarDL Schema Loader のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx)を参照してください。 + + ::: + +
+
+ +1. 上記のカスタム値ファイルを含む Helm Chart を使用して、Scalar 製品をデプロイします。使用している製品に応じて、次の例を参照してください。 + + + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f scalardb-cluster-custom-values.yaml + ``` + + +

ScalarDL Ledger

+ + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + +

ScalarDL Schema Loader for Ledger

+ + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-ledger-custom-values.yaml + ``` +
+ +

ScalarDL Auditor

+ + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + +

ScalarDL Schema Loader for Auditor

+ + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-auditor-custom-values.yaml + ``` +
+
+ +## **[非推奨] [BYOL]** Scalar Helm Chart を使用して、AWS Marketplace から EKS 以外の Kubernetes にコンテナをデプロイする + +1. [AWS Official Document (Installing or updating the latest version of the AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) に従って `aws` コマンドをインストールします。 + +1. [AWS Official Document (Configuration basics)](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html) に従って、認証情報を使用して AWS CLI を設定します。 + +1. AWS Marketplace の ECR からコンテナイメージをプルするための `reg-ecr-mp-secrets` シークレットリソースを作成します。 + + ```console + kubectl create secret docker-registry reg-ecr-mp-secrets \ + --docker-server=709825985650.dkr.ecr.us-east-1.amazonaws.com \ + --docker-username=AWS \ + --docker-password=$(aws ecr get-login-password --region us-east-1) + ``` + +1. インストールする Scalar 製品の Helm Chart のカスタム値ファイルを更新します。 + AWS Marketplace のプライベートコンテナレジストリ (ECR) をカスタム値ファイルの `[].image.repository` の値として指定する必要があります。 + また、`[].imagePullSecrets` の値として `reg-ecr-mp-secrets` を指定する必要があります。使用している製品に応じて、次の例を参照してください。 + + + + ```yaml + scalardbCluster: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-cluster-node-aws-byol" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ``` + + :::note + + 設定の詳細については、[ScalarDB Cluster のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardb-cluster.mdx)を参照してください。 + + ::: + + + +

ScalarDL Ledger

+ + `scalardl-ledger-custom-values.yaml` ファイル内: + + ```yaml + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ``` + + :::note + + 設定の詳細については、[ScalarDL Ledger のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-ledger.mdx)を参照してください。 + + ::: + +

ScalarDL Schema Loader for Ledger

+ + `schema-loader-ledger-custom-values.yaml` ファイル内の `[].image.repository` 構成を更新する必要はありません。ScalarDL Schema Loader のコンテナイメージは、[パブリックコンテナリポジトリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader)で提供されています。 + + :::note + + 設定の詳細については、[ScalarDL Schema Loader のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx)を参照してください。 + + ::: + +
+ +

ScalarDL Auditor

+ + `scalardl-auditor-custom-values.yaml` ファイル内: + + ```yaml + auditor: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-auditor" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ``` + + :::note + + 設定の詳細については、[ScalarDL Auditor のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-auditor.mdx)を参照してください。 + + ::: + +

ScalarDL Schema Loader for Auditor

+ + `schema-loader-auditor-custom-values.yaml` ファイル内の `[].image.repository` 構成を更新する必要はありません。ScalarDL Schema Loader のコンテナイメージは、[パブリックコンテナリポジトリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader)で提供されています。 + + :::note + + 設定の詳細については、[ScalarDL Schema Loader のカスタム値ファイルを構成する](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx)を参照してください。 + + ::: + +
+
+ +1. 上記のカスタム値ファイルを含む Helm Chart を使用して、Scalar 製品をデプロイします。 + * 例 + このドキュメントの **[非推奨] [BYOL] Scalar Helm Chart を使用して AWS Marketplace から EKS (Amazon Elastic Kubernetes Service) にコンテナをデプロイする** セクションを参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AzureMarketplaceGuide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AzureMarketplaceGuide.mdx new file mode 100644 index 00000000..e9d69bd5 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/AzureMarketplaceGuide.mdx @@ -0,0 +1,239 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Azure Marketplace を通じて Scalar 製品をインストールする方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +:::warning + +現在、Scalar 製品は Azure Marketplace では入手できません。Scalar 製品のコンテナイメージを取得するその他の方法については、[Scalar 製品のコンテナイメージを取得する方法](./HowToGetContainerImages.mdx)を参照してください。 + +::: + +Scalar 製品 (ScalarDB、ScalarDL、およびそれらのツール) は、コンテナーオファーとして Azure Marketplace で提供されます。このガイドでは、Azure Marketplace を通じて Scalar 製品をインストールする方法について説明します。 + +一部の Scalar 製品は商用ライセンスに基づいてライセンスされており、Azure Marketplace では BYOL (Bring Your Own License) として提供されていることに注意してください。適切なライセンスを持っていることを確認してください。 + +## Microsoft Azure Marketplace から Scalar 製品を入手する + +1. Scalar 製品を選択すると、Microsoft Azure Marketplace へのリンクが表示されます。 + + + + - [ScalarDB](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) + + + - [ScalarDL](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardl) + + + +1. **Get It Now** を選択します。 + +1. 職場の電子メールアドレスを使用して Azure Marketplace にサインインします。 + Microsoft Azureのアカウントとして使用している仕事用メールアドレスをご利用ください。 + すでにサインインしている場合、この手順は自動的にスキップされます。 + +1. あなたの情報を入力してください。 + **会社**は必須ではありませんが、入力してください。 + +1. 必要な **ソフトウェアプラン** をプルダウンから選択します。 + **ソフトウェアプラン** とは、コンテナイメージとライセンスの組み合わせを意味します。ご使用の *ソフトウェアプラン* を選択してください。 + +1. [**続行**] を選択します。 + [**続行**] を選択すると、自動的に Azure ポータルに移動します。 + +1. プライベートコンテナーレジストリ (Azure Container Registry) を作成します。 + 画面上のコマンドに従って、プライベートコンテナーレジストリを作成してください。 + Scalar 製品のコンテナイメージは、プライベートコンテナレジストリにコピーされます。 + +1. 必要に応じてこれらの手順を繰り返します。 + Kubernetes 上で Scalar 製品を実行するには複数のコンテナーイメージが必要ですが、Azure Marketplace は一度に1つのコンテナーイメージのみをコピーします。したがって、必要に応じて複数のソフトウェアプランを購読する (繰り返し購読操作) 必要があります。 + - 必要なコンテナイメージは以下となります。コンテナイメージの詳細を表示するには、Scalar 製品を選択します。 + + + + - ScalarDB Cluster (BYOL) + - [非推奨] ScalarDB Server のデフォルト (2vCPU、 4GiB Memory) + - [非推奨] ScalarDB GraphQL Server (optional) + - [非推奨] ScalarDB SQL Server (optional) + + + - ScalarDL Ledger のデフォルト (2vCPU、 4GiB Memory) + - ScalarDL Auditor のデフォルト (2vCPU、 4GiB Memory) + - **ScalarDL Auditor** はオプションです。**ScalarDL Auditor** を使用している場合は、サブスクライブしてください。 + - ScalarDL Schema Loader + + + +これで、プライベートコンテナーレジストリから Scalar 製品のコンテナーイメージをプルできるようになりました。 +Azure Container Registry の詳細については、 [Azure Container Registry documentation](https://docs.microsoft.com/en-us/azure/container-registry/) を参照してください。 + +## Scalar Helm Charts を使用して、プライベートコンテナーレジストリから AKS (Azure Kubernetes Service) にコンテナーをデプロイします。 + +1. AKS クラスターを作成するときに、プライベートコンテナーレジストリ (Azure Container Registry) を指定します。 + * GUI (Azure ポータル) + [**統合**] タブの **Azure Container Registry** パラメーターで、プライベートコンテナーレジストリを指定してください。 + * CLI ([az aks create](https://docs.microsoft.com/en-us/cli/azure/aks?view=azure-cli-latest#az-aks-create) コマンド) + `--attach-acr` フラグにプライベートコンテナーレジストリの名前を指定してください。また、`--attach-acr` フラグを指定した [az aks update](https://docs.microsoft.com/en-us/cli/azure/aks?view=azure-cli-latest#az-aks-update) コマンドを使用して、既存の AKS クラスターの Azure Container Registry 統合を構成できます。詳細は [Azure Official Document](https://docs.microsoft.com/en-us/azure/aks/cluster-container-registry-integration) をご参照ください。 + +1. インストールする Scalar 製品の Helm Chart のカスタム値ファイルを更新します。 + プライベートコンテナレジストリをカスタム値ファイルの `[].image.repository` の値として指定する必要があります。使用している製品に応じて、次の例を参照してください。 + + + + ```yaml + scalardbCluster: + image: + repository: "example.azurecr.io/scalarinc/scalardb-cluster-node-azure-byol" + ``` + + + 使用している ScalarDL 製品を選択します。 + + + `scalardl-ledger-custom-values.yaml` ファイル内: + + ```yaml + ledger: + image: + repository: "example.azurecr.io/scalarinc/scalar-ledger" + ``` + + + `scalardl-auditor-custom-values.yaml` ファイル内: + + ```yaml + auditor: + image: + repository: "example.azurecr.io/scalarinc/scalar-auditor" + ``` + + + `schema-loader-custom-values.yaml` ファイル内: + + ```yaml + schemaLoading: + image: + repository: "example.azurecr.io/scalarinc/scalardl-schema-loader" + ``` + + + + + +1. 上記のカスタム値ファイルを含む Helm Chart を使用して、Scalar 製品をデプロイします。使用している製品に応じて、次の例を参照してください。 + + + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f scalardb-cluster-custom-values.yaml + ``` + + + 使用している ScalarDL 製品を選択します。 + + + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + + + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + + + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-custom-values.yaml + ``` + + + + + +## Scalar Helm Chart を使用して、プライベートコンテナーレジストリから AKS (Azure Kubernetes Service) 以外の Kubernetes にコンテナーをデプロイします。 + +1. [Azure Official Document (How to install the Azure CLI)](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) に従って`az`コマンドをインストールします。 + +1. Azure CLI を使用してサインインします。 + ```console + az login + ``` + +1. [Azure Official Document (Azure Container Registry authentication with service principals)](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-auth-service-principal) に従って、プライベートコンテナーレジストリへの認証用の **service principal** を作成します。 + 次のステップでは、**Service principal ID** と **Service principal パスワード**を使用します。 + +1. プライベートコンテナーレジストリからコンテナーイメージをプルするための `reg-acr-secrets` シークレットリソースを作成します。 + ```console + kubectl create secret docker-registry reg-acr-secrets \ + --docker-server= \ + --docker-username= \ + --docker-password= + ``` + +1. インストールする Scalar 製品の Helm Chart のカスタム値ファイルを更新します。 + プライベートコンテナレジストリをカスタム値ファイルの `[].image.repository` の値として指定する必要があります。 + また、`[].imagePullSecrets` の値として `reg-acr-secrets` を指定する必要があります。使用している製品に応じて、次の例を参照してください。 + + + + ```yaml + scalardbCluster: + image: + repository: "example.azurecr.io/scalarinc/scalardb-cluster-node-azure-byol" + imagePullSecrets: + - name: "reg-acr-secrets" + ``` + + + 使用している ScalarDL 製品を選択します。 + + + `scalardl-ledger-custom-values.yaml` ファイル内: + + ```yaml + ledger: + image: + repository: "example.azurecr.io/scalarinc/scalar-ledger" + imagePullSecrets: + - name: "reg-acr-secrets" + ``` + + + `scalardl-auditor-custom-values.yaml` ファイル内: + + ```yaml + auditor: + image: + repository: "example.azurecr.io/scalarinc/scalar-auditor" + imagePullSecrets: + - name: "reg-acr-secrets" + ``` + + + `schema-loader-custom-values.yaml` ファイル内: + + ```yaml + schemaLoading: + image: + repository: "example.azurecr.io/scalarinc/scalardl-schema-loader" + imagePullSecrets: + - name: "reg-acr-secrets" + ``` + + + + + +1. 上記のカスタム値ファイルを含む Helm Chart を使用して、Scalar 製品をデプロイします。 + * 例 + このドキュメントの **Scalar Helm Charts を使用して、プライベートコンテナーレジストリから AKS (Azure Kubernetes Service) にコンテナーをデプロイします** セクションを参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupNoSQL.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupNoSQL.mdx new file mode 100644 index 00000000..afc68ea3 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupNoSQL.mdx @@ -0,0 +1,149 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes 環境で NoSQL データベースをバックアップする + +このガイドでは、ScalarDB または ScalarDL が Kubernetes 環境で使用するマネージドデータベースのトランザクション的に一貫したバックアップを作成する方法について説明します。NoSQL データベースまたは複数のデータベースを使用する場合は、トランザクション的に一貫したバックアップを作成するために ScalarDB または ScalarDL を**一時停止する必要がある**ことに注意してください。 + +ScalarDB がデータベースをバックアップする方法の詳細については、[A Guide on How to Backup and Restore Databases Used Through ScalarDB](https://scalardb.scalar-labs.com/docs/latest/backup-restore/) を参照してください。 + +このガイドでは、ポイントインタイムリカバリ (PITR) または同等の機能を使用していることを前提としています。そのため、復旧のためには継続的な取引がない期間を設ける必要があります。その後、PITR を使用してデータをその特定の期間に復元できます。進行中のトランザクションがない期間を作成せずにデータをある時点に復元すると、復元されたデータはトランザクション的に不整合となり、ScalarDB または ScalarDL がデータを適切に処理できなくなる可能性があります。 + +## データを復元する期間を作成し、バックアップを実行します + +1. バックアップ操作を開始する前に、`kubectl get pod` コマンドを実行して、次の4つの点を確認します。 + * **ScalarDB または ScalarDL ポッドの数。** ポッドの数を書き留めて、その数をバックアップの実行後のポッドの数と比較できるようにします。 + * **`NAME` 列の ScalarDB または ScalarDL ポッド名。** バックアップの実行後にそれらの名前とポッド名を比較できるように、ポッド名を書き留めます。 + * **ScalarDB または ScalarDL ポッドのステータスは、`STATUS` 列で `Running` になっています。** バックアップを続行する前に、ポッドが実行中であることを確認してください。次のステップではポッドを一時停止する必要があります。 + * ** `RESTARTS` 列の各ポッドの再起動回数。** バックアップ実行後の再起動回数と比較できるように、各ポッドの再起動回数を書き留めます。 +2. `scalar-admin` を使用して、ScalarDB または ScalarDL ポッドを一時停止します。ポッドを一時停止する方法の詳細については、このガイドの [`scalar-admin` の使用の詳細](BackupNoSQL.mdx#scalar-admin-の使用の詳細)セクションを参照してください。 +3. `pause completed` 時間を書き留めます。PITR 機能を使用してデータを復元する場合は、その時間を参照する必要があります。 +4. バックアップ機能を使用して、各データベースをバックアップします。自動バックアップと PITR 機能を有効にしている場合、管理されたデータベースは自動的にバックアップを実行します。クライアントクロックとデータベースクロック間のクロックスキューの問題を回避するのに十分な長い期間を作成できるように、約10秒待つ必要があることに注意してください。この10秒の期間は、PITR 機能を使用してデータを復元できる正確な期間です。 +5. `scalar-admin` を使用して、ScalarDB または ScalarDL ポッドの一時停止を解除します。ポッドの一時停止を解除する方法の詳細については、このガイドの [`scalar-admin` の使用の詳細](BackupNoSQL.mdx#scalar-admin-の使用の詳細)の使用の詳細」セクションを参照してください。 +6. `unpause started` 時刻を確認します。PITR 機能を使用してデータを復元できる正確な期間を確認するには、`unpause started` 時間を確認する必要があります。 +7. バックアップの実行後にポッドのステータスを確認します。バックアップ操作完了後、`kubectl get pod` コマンドを使用して以下の4点を確認する必要があります。 + * **ScalarDB または ScalarDL ポッドの数。** この数が、バックアップを実行する前に書き留めたポッドの数と一致することを確認します。 + * **`NAME` 列の ScalarDB または ScalarDL ポッド名。** 名前がバックアップを実行する前に書き留めたポッド名と一致することを確認します。 + * **ScalarDB または ScalarDL ポッドのステータスは、`STATUS` 列で `Running` になっています。** + * **`RESTARTS` 列の各ポッドの再起動回数。** カウントが、バックアップを実行する前に書き留めた再起動回数と一致することを確認します。 + + **2つの値のいずれかが異なる場合は、バックアップ操作を最初から再試行する必要があります。** 値が異なる理由は、バックアップの実行中に追加または再起動されたポッドが原因である可能性があります。そのような場合、それらのポッドは `unpause` 状態で実行されます。ポッドが `unpause` 状態にあると、バックアップデータのトランザクションの不整合が発生します。 +8. **(Amazon DynamoDB のみ)** DynamoDB の PITR 機能を使用する場合、この機能は PITR を使用して別の名前テーブルでデータを復元するため、バックアップを作成するために追加の手順を実行する必要があります。データを復元できる正確な期間を作成した後の追加手順の詳細については、[Kubernetes 環境でのデータベースの復元](RestoreDatabase.mdx#amazon-dynamodb) を参照してください。 + +## 複数のデータベースをバックアップする + +[Multi-storage Transactions](https://scalardb.scalar-labs.com/docs/latest/multi-storage-transactions/) または [Two-phase Commit Transactions](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions/) 機能が使用するデータベースが2つ以上ある場合は、ScalarDB または ScalarDL のすべてのインスタンスを一時停止し、データベース内に進行中のトランザクションが存在しない同じ期間を作成する必要があります。 + +複数のデータベース間の整合性を確保するには、PITR 機能を使用してデータベースを同じ時点に復元する必要があります。 + +## `scalar-admin` の使用の詳細 + +### Kubernetes リソース名を確認する + +SRV サービス URL を `-s (--srv-service-url)` フラグに指定する必要があります。Kubernetes 環境では、SRV サービス URL の形式は `_my-port-name._my-port-protocol.my-svc.my-namespace.svc.cluster.local` です。 + +Scalar Helm Chart を使用して ScalarDB または ScalarDL をデプロイする場合、`my-svc` および `my-namespace` は環境によって異なる場合があります。ヘッドレスサービス名を `my-svc` として指定し、名前空間を `my-namespace` として指定する必要があります。 + +* 例 + * ScalarDB Server + ```console + _scalardb._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Ledger + ```console + _scalardl-admin._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Auditor + ```console + _scalardl-auditor-admin._tcp.-headless..svc.cluster.local + ``` + +Helm リリース名によって、ヘッドレスサービス名 `-headless` が決まります。次のコマンドを実行すると、helm リリース名を確認できます。 + +```console +helm list -n ns-scalar +``` + +次のような結果が表示されます: + +```console +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +scalardb ns-scalar 1 2023-02-09 19:31:40.527130674 +0900 JST deployed scalardb-2.5.0 3.8.0 +scalardl-auditor ns-scalar 1 2023-02-09 19:32:03.008986045 +0900 JST deployed scalardl-audit-2.5.1 3.7.1 +scalardl-ledger ns-scalar 1 2023-02-09 19:31:53.459548418 +0900 JST deployed scalardl-4.5.1 3.7.1 +``` + +次のコマンドを実行すると、ヘッドレスサービス名 `-headless` を確認することもできます。 + +```console +kubectl get service -n ns-scalar +``` + +次のような結果が表示されます: + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-envoy LoadBalancer 10.99.245.143 60051:31110/TCP 2m2s +scalardb-envoy-metrics ClusterIP 10.104.56.87 9001/TCP 2m2s +scalardb-headless ClusterIP None 60051/TCP 2m2s +scalardb-metrics ClusterIP 10.111.213.194 8080/TCP 2m2s +scalardl-auditor-envoy LoadBalancer 10.111.141.43 40051:31553/TCP,40052:31171/TCP 99s +scalardl-auditor-envoy-metrics ClusterIP 10.104.245.188 9001/TCP 99s +scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 99s +scalardl-auditor-metrics ClusterIP 10.105.119.158 8080/TCP 99s +scalardl-ledger-envoy LoadBalancer 10.96.239.167 50051:32714/TCP,50052:30857/TCP 109s +scalardl-ledger-envoy-metrics ClusterIP 10.97.204.18 9001/TCP 109s +scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 109s +scalardl-ledger-metrics ClusterIP 10.104.216.189 8080/TCP 109s +``` + +### 一時停止 + +Kubernetes 環境の ScalarDB または ScalarDL ポッドに一時停止リクエストを送信できます。 + +* 例 + * ScalarDB Server + ```console + kubectl run scalar-admin-pause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c pause -s _scalardb._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Ledger + ```console + kubectl run scalar-admin-pause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c pause -s _scalardl-admin._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Auditor + ```console + kubectl run scalar-admin-pause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c pause -s _scalardl-auditor-admin._tcp.-headless..svc.cluster.local + ``` + +### 一時停止を解除する + +Kubernetes 環境の ScalarDB または ScalarDL ポッドに一時停止解除リクエストを送信できます。 + +* 例 + * ScalarDB Server + ```console + kubectl run scalar-admin-unpause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c unpause -s _scalardb._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Ledger + ```console + kubectl run scalar-admin-unpause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c unpause -s _scalardl-admin._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Auditor + ```console + kubectl run scalar-admin-unpause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c unpause -s _scalardl-auditor-admin._tcp.-headless..svc.cluster.local + ``` + +### `pause completed` 時刻と `unpause started` 時刻を確認する + +`scalar-admin` ポッドは、`pause completed` 時刻と `unpause started` 時刻を標準出力に出力します。`kubectl logs` コマンドを実行すると、それらの時間を確認することもできます。 + +```console +kubectl logs scalar-admin-pause +``` +```console +kubectl logs scalar-admin-unpause +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupRDB.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupRDB.mdx new file mode 100644 index 00000000..cb8586f8 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupRDB.mdx @@ -0,0 +1,21 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes 環境で RDB をバックアップする + +このガイドでは、ScalarDB または ScalarDL が Kubernetes 環境で使用する単一のリレーショナルデータベース (RDB) のバックアップを作成する方法について説明します。このガイドは、クラウドサービスプロバイダーの管理されたデータベースを使用していることを前提としていることに注意してください。 + +[Multi-storage Transactions](https://scalardb.scalar-labs.com/docs/latest/multi-storage-transactions/) または [Two-phase Commit Transactions](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions/) 機能が使用する RDB が2つ以上ある場合は、代わりに [Kubernetes 環境で NoSQL データベースをバックアップする](BackupNoSQL.mdx)の手順に従う必要があります。 + +## バックアップを実行する + +バックアップを実行するには、管理されたデータベースで使用できる自動バックアップ機能を有効にする必要があります。この機能を有効にすると、追加のバックアップ操作を実行する必要がなくなります。各管理データベースのバックアップ構成の詳細については、次のガイドを参照してください。 + +* [AWS での ScalarDB/ScalarDL デプロイメント用のデータベースのセットアップ](SetupDatabaseForAWS.mdx) +* [Azure 上で ScalarDB/ScalarDL デプロイメント用のデータベースをセットアップする](SetupDatabaseForAzure.mdx) + +マネージド RDB はトランザクションの観点からバックアップデータの一貫性を保つため、マネージド RDB のポイントインタイムリカバリ (PITR) 機能を使用して、バックアップデータを任意の時点に復元できます。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupRestoreGuide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupRestoreGuide.mdx new file mode 100644 index 00000000..bc70bfc1 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/BackupRestoreGuide.mdx @@ -0,0 +1,48 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes 環境で ScalarDB または ScalarDL データをバックアップおよび復元する + +このガイドでは、Kubernetes 環境で ScalarDB または ScalarDL データをバックアップおよび復元する方法について説明します。このガイドは、クラウドサービスプロバイダーのマネージドデータベースを ScalarDB または ScalarDL のバックエンドデータベースとして使用していることを前提としていることに注意してください。以下は、このガイドで使用が想定されている管理データベースのリストです。 + +* NoSQL: トランザクションをサポートしません + * Amazon DynamoDB + * Azure Cosmos DB for NoSQL +* リレーショナルデータベース (RDB):トランザクションをサポート + * Amazon RDS + * MySQL + * Oracle + * PostgreSQL + * SQL Server + * Amazon Aurora + * MySQL + * PostgreSQL + * Azureデータベース + * MySQL + * PostgreSQL + +ScalarDB で使用されるデータベースをトランザクション的に一貫した方法でバックアップおよび復元する方法の詳細については、[A Guide on How to Backup and Restore Databases Used Through ScalarDB](https://scalardb.scalar-labs.com/docs/latest/backup-restore/) を参照してください。 + +## バックアップを実行する + +### 使用しているデータベースの種類とデータベースの数を確認します。 + +バックアップと復元の実行方法は、データベースの種類 (NoSQL または RDB) と使用しているデータベースの数によって異なります。 + +#### NoSQL または複数のデータベース + +NoSQL データベースを使用している場合、または [Multi-storage Transactions](https://scalardb.scalar-labs.com/docs/latest/multi-storage-transactions/) または [Two-phase Commit Transactions](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions/) 機能が使用するデータベースが2つ以上ある場合、詳細については [Kubernetes 環境で NoSQL データベースをバックアップする](BackupNoSQL.mdx)を参照してください。バックアップの実行方法について。 + +#### 単一 RDB + +単一のRDBを使用している場合のバックアップ方法については、[Kubernetes環境でRDBをバックアップする](BackupRDB.mdx)を参照してください。 + +[Multi-storage Transactions](https://scalardb.scalar-labs.com/docs/latest/multi-storage-transactions/) または [Two-phase Commit Transactions](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions/) 機能が使用する RDB が2つ以上ある場合は、代わりに [Kubernetes 環境で NoSQL データベースをバックアップする](BackupNoSQL.mdx)の手順に従う必要があります。 + +## データベースを復元する + +管理されたデータベースからデータを復元する方法の詳細については、[Kubernetes 環境でのデータベースの復元](RestoreDatabase.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDB.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDB.mdx new file mode 100644 index 00000000..1ee3c5e8 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDB.mdx @@ -0,0 +1,107 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsJapanese +--- + +# ScalarDB Server 用の AKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDB Server デプロイ用の Azure Kubernetes Service (AKS) クラスターを作成するための要件と推奨事項について説明します。ScalarDB Server を AKS クラスターにデプロイする方法の詳細については、[AKS に ScalarDB Server をデプロイする](ManualDeploymentGuideScalarDBServerOnAKS.mdx)を参照してください。 + +## あなたが始める前に + +次の要件、推奨事項、およびプロジェクトの要件に基づいて AKS クラスターを作成する必要があります。AKS クラスターの作成方法の詳細については、環境で使用しているツールに基づいて、次の Microsoft 公式ドキュメントを参照してください。 + +* [Azure CLI](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-cli) +* [PowerShell](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-powershell) +* [Azure Portal](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal) + +## 要件 + +ScalarDB Server を展開するときは、次のことを行う必要があります。 + +* [サポートされている Kubernetes バージョン](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes)を使用して AKS クラスターを作成します。 +* Kubernetes のバージョンとプロジェクトの要件に基づいて AKS クラスターを構成します。 + +## 推奨事項 (オプション) + +以下に、ScalarDB Server を展開するための推奨事項をいくつか示します。これらの推奨事項は必須ではないため、ニーズに基づいてこれらの推奨事項を適用するかどうかを選択できます。 + +### 少なくとも3つのワーカーノードと3つのポッドを作成します + +AKS クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つのポッドをワーカーノードに分散させるための `podAntiAffinity` の [サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardb-custom-values.yaml)を参照できます。 + +:::note + +ワーカーノードを異なる [availability zones](https://learn.microsoft.com/en-us/azure/availability-zones/az-overview) (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### ScalarDB Server ノードプールのワーカーノードには 4vCPU / 8GB メモリノードを使用します。 + +商用ライセンスの観点から、ScalarDB Server を実行する1つのポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDB Server ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDB Server ポッド (2vCPU / 4GB) +* Envoy プロキシ +* アプリケーションポッド (同じワーカーノード上でアプリケーションのポッドを実行することを選択した場合) +* 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) +* Kubernetes コンポーネント + +これを念頭に置き、[少なくとも3つのワーカーノードと3つのポッドを作成する](#create-at-least-three-worker-nodes-and-three-pods)で説明されているように、少なくとも 4vCPU / 8 GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。 + +ただし、運用環境では、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが最小条件となります。また、システムのワークロードに応じて、AKS クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDB Server ポッド、アプリケーションのポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、ワーカーノードのリソースを決定するときにワーカーノード上の最大ポッド数を考慮する必要があります。 + +### ScalarDB Server ポッドのノードプールを作成する + +AKS は、既定でシステムポッド (AKS を実行し続けるために使用される) に優先される **agentpool** という名前のシステムノードプールを1つ作成します。ScalarDB Server ポッド用に **user** モードで別のノードプールを作成し、この追加のノードプールに ScalarDB Server ポッドをデプロイすることをお勧めします。 + +### AKS でクラスターオートスケーラーを構成する + +[Horizontal Pod Autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#horizontal-pod-autoscaler) を使用して ScalarDB Server ポッドを自動的にスケーリングする場合は、AKS でもクラスターオートスケーラーを構成する必要があります。詳細については、Microsoft の公式ドキュメント [Cluster autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#cluster-autoscaler) を参照してください。 + +さらに、クラスターオートスケーラーを構成する場合は、AKS がスケーリング後にネットワークの問題なく動作できるように、十分な数の IP が存在することを確認するために、AKS の仮想ネットワーク (VNet) にサブネットを作成する必要があります。必要な IP の数は、ネットワークプラグインによって異なります。必要な IP 数の詳細については、以下を参照してください。 + +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### プライベートネットワーク上に AKS クラスターを作成する + +ScalarDB Server はインターネットアクセス経由でユーザーにサービスを直接提供しないため、プライベートネットワーク (VNet のプライベートサブネット) 上に AKS クラスターを作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDB Server にアクセスすることをお勧めします。 + +### 必要に応じて、Azure CNI を使用して AKS クラスターを作成します。 + +AKS の既定のネットワークプラグインは [kubenet](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) です。要件が kubenet と一致しない場合は、[Azure Container Networking Interface (CNI)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) を使用する必要があります。 + +たとえば、1つの AKS クラスターに複数の ScalarDB Server 環境をデプロイし (マルチテナントの ScalarDB Server をデプロイするなど)、[Kubernetes NetworkPolicies](https://kubernetes.io/docs/concepts/services-networking/network-policies/) を使用して各テナント間の接続を制御したい場合、kubenet は Calico Network のみをサポートします。[Azure support team does not support](https://learn.microsoft.com/en-us/azure/aks/use-network-policies#differences-between-azure-network-policy-manager-and-calico-network-policy-and-their-capabilities) ポリシー。Calico ネットワークポリシーは、Calico コミュニティまたは追加の有料サポートを通じてのみサポートされることに注意してください。 + +ただし、Azure サポートチームとエンジニアリングチームは Azure CNI をサポートします。したがって、Kubernetes NetworkPolicies を使用して Azure サポートチームからサポートを受けたい場合は、Azure CNI を使用する必要があります。kubenet と Azure CNI の違いの詳細については、次の Microsoft 公式ドキュメントを参照してください。 + +* [Network concepts for applications in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/concepts-network) +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### 要件に基づいていくつかのセキュリティ機能を使用して接続を制限する + +ScalarDB Server では未使用の接続を制限する必要があります。未使用の接続を制限するには、[network security groups](https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview) など、Azure のいくつかのセキュリティ機能を使用できます。 + +ScalarDB Server がデフォルトで使用する接続 (ポート) は次のとおりです。 + +* ScalarDB Server + * 60051/TCP (クライアントからのリクエストを受け付ける) + * 8080/TCP (監視リクエストを受け付ける) +* Scalar Envoy (ScalarDB Server とともに使用) + * 60051/TCP (ScalarDB Server の負荷分散) + * 9001/TCP (Scalar Envoy 自体の監視リクエストを受け入れます) + +:::note + +- 構成ファイル (`database.properties`) で ScalarDB Server のデフォルトのリスニングポートを変更する場合は、構成したポートを使用して接続を許可する必要があります。 +- AKS 自体が使用する接続も許可する必要があります。AKS トラフィック要件の詳細については、[Control egress traffic using Azure Firewall in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/limit-egress-traffic) を参照してください。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDL.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDL.mdx new file mode 100644 index 00000000..ad064480 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDL.mdx @@ -0,0 +1,113 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger の AKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDL Ledger デプロイ用の Azure Kubernetes Service (AKS) クラスターを作成するための要件と推奨事項について説明します。ScalarDL Ledger を AKS クラスターにデプロイする方法の詳細については、[AKS に ScalarDL Ledger をデプロイする](ManualDeploymentGuideScalarDLOnAKS.mdx)を参照してください。 + +## あなたが始める前に + +次の要件、推奨事項、およびプロジェクトの要件に基づいて AKS クラスターを作成する必要があります。AKS クラスターの作成方法の詳細については、環境で使用しているツールに基づいて、次の Microsoft 公式ドキュメントを参照してください。 + +* [Azure CLI](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-cli) +* [PowerShell](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-powershell) +* [Azure portal](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal) + +## 要件 + +ScalarDL Ledger を展開するときは、次のことを行う必要があります。 + +* [サポートされている Kubernetes バージョン](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes)を使用して AKS クラスターを作成します。 +* Kubernetes のバージョンとプロジェクトの要件に基づいて AKS クラスターを構成します。 + +:::warning + +ScalarDL でのビザンチン障害検出が適切に機能するには、ScalarDL Ledger デプロイと同じ AKS クラスターにアプリケーションポッドをデプロイしないでください。 + +::: + +## 推奨事項 (オプション) + +以下は、ScalarDL Ledger を展開するための推奨事項の一部です。これらの推奨事項は必須ではないため、ニーズに基づいてこれらの推奨事項を適用するかどうかを選択できます。 + +### 少なくとも3つのワーカーノードと3つのポッドを作成します + +AKS クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つのポッドをワーカーノードに分散させるための `podAntiAffinity` の [サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml)を参照できます。 + +:::note + +ワーカーノードを異なる [availability zones](https://learn.microsoft.com/en-us/azure/availability-zones/az-overview) (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### ScalarDL Ledger ノードプールのワーカーノードには 4vCPU / 8GB メモリノードを使用します + +商用ライセンスの観点から、ScalarDL Ledger を実行する1つのポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDL Ledger ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDL Ledger ポッド (2vCPU / 4GB) +* Envoy プロキシ +* 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) +* Kubernetes コンポーネント + +これを念頭に置き、[少なくとも3つのワーカーノードと3つのポッドを作成する](#create-at-least-three-worker-nodes-and-three-pods)で説明されているように、少なくとも 4vCPU / 8 GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。 + +ただし、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが運用環境の最小環境となります。また、システムのワークロードに応じて、AKS クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDL Ledger ポッドなど) も考慮する必要があります。さらに、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、 ワーカーノードのリソースを決定するときは、ワーカーノード上のポッドの最大数を考慮する必要があります。 + +### ScalarDL Ledger ポッドのノードプールを作成する + +AKS は、既定でシステムポッド (AKS を実行し続けるために使用される) に優先される **agentpool** という名前のシステムノードプールを1つ作成します。ScalarDL Ledger ポッド用に **user** モードで別のノードプールを作成し、この追加のノードプールに ScalarDL Ledger ポッドをデプロイすることをお勧めします。 + +### AKS でクラスターオートスケーラーを構成する + +[Horizontal Pod Autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#horizontal-pod-autoscaler) を使用して ScalarDL Ledger ポッドを自動的にスケーリングする場合は、クラスターを構成する必要があります。AKS のオートスケーラーも同様です。詳細については、[Cluster autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#cluster-autoscaler) にある Microsoft の公式ドキュメントを参照してください。 + +さらに、クラスターオートスケーラーを構成する場合は、AKS がスケーリング後にネットワークの問題なく動作できるように、十分な数の IP が存在することを確認するために、AKS の仮想ネットワーク (VNet) にサブネットを作成する必要があります。必要な IP の数は、ネットワークプラグインによって異なります。必要な IP 数の詳細については、以下を参照してください。 + +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### プライベートネットワーク上に AKS クラスターを作成する + +ScalarDL Ledger はインターネットアクセス経由でユーザーにサービスを直接提供しないため、プライベートネットワーク (VNet のプライベートサブネット) 上に AKS クラスターを作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDL Ledger にアクセスすることをお勧めします。 + +### 必要に応じて、Azure CNI を使用して AKS クラスターを作成します。 + +AKS の既定のネットワークプラグインは [kubenet](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) です。要件が kubenet と一致しない場合は、[Azure Container Networking Interface (CNI)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) を使用する必要があります。 + +たとえば、1つの AKS クラスターに複数の ScalarDL Ledger 環境をデプロイし (マルチテナントの ScalarDL Ledger をデプロイするなど)、[Kubernetes NetworkPolicies](https://kubernetes.io/docs/concepts/services-networking/network-policies/) を使用して各テナント間の接続を制御する場合、kubenet は Calico ネットワークポリシーのみをサポートします。[Azure サポートチームはサポートしていません](https://learn.microsoft.com/en-us/azure/aks/use-network-policies#differences-between-azure-network-policy-manager-and-calico-network-policy-and-their-capabilities)。Calico ネットワークポリシーは、Calico コミュニティまたは追加の有料サポートを通じてのみサポートされることに注意してください。 + +ただし、Azure サポートチームとエンジニアリングチームは Azure CNI をサポートします。したがって、Kubernetes NetworkPolicies を使用して Azure サポートチームからサポートを受けたい場合は、Azure CNI を使用する必要があります。kubenet と Azure CNI の違いの詳細については、次の Microsoft 公式ドキュメントを参照してください。 + +* [Network concepts for applications in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/concepts-network) +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### 要件に基づいていくつかのセキュリティ機能を使用して接続を制限する + +ScalarDL Ledger では未使用の接続を制限する必要があります。未使用の接続を制限するには、[ネットワークセキュリティグループ] など、Azure のいくつかのセキュリティ機能を使用できます。 + +ScalarDL Ledger がデフォルトで使用する接続 (ポート) は次のとおりです。 + +* ScalarDL Ledger + * 50051/TCP (クライアントからのリクエストを受け付ける) + * 50052/TCP (クライアントからの特権リクエストを受け入れます) + * 50053/TCP (scalar-admin クライアントツールからの一時停止および一時停止解除リクエストを受け入れます) + * 8080/TCP (監視リクエストを受け付ける) +* Scalar Envoy (ScalarDL Ledger とともに使用) + * 50051/TCP (ScalarDL Ledger の負荷分散) + * 50052/TCP (ScalarDL Ledger の負荷分散) + * 9001/TCP (Scalar Envoy 自体の監視リクエストを受け入れます) + +:::note + +- 設定ファイル (`ledger.properties`) で ScalarDL Ledger のデフォルトのリスニングポートを変更する場合は、設定したポートを使用して接続を許可する必要があります。 +- AKS 自体が使用する接続も許可する必要があります。AKS トラフィック要件の詳細については、[Azure Kubernetes Service (AKS) の Azure Firewall を使用した下りトラフィックの制御](https://learn.microsoft.com/en-us/azure/aks/limit-egress-traffic)を参照してください。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDLAuditor.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDLAuditor.mdx new file mode 100644 index 00000000..84fba9c5 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDLAuditor.mdx @@ -0,0 +1,132 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger および ScalarDL Auditor 用の AKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDL Ledger および ScalarDL Auditor のデプロイ用の Azure Kubernetes Service (AKS) クラスターを作成するための要件と推奨事項について説明します。AKS クラスターに ScalarDL Ledger と ScalarDL Auditor をデプロイする方法の詳細については、[AKS に ScalarDL Ledger と ScalarDL Auditor をデプロイする](ManualDeploymentGuideScalarDLAuditorOnAKS.mdx)を参照してください。 + +## あなたが始める前に + +次の要件、推奨事項、およびプロジェクトの要件に基づいて AKS クラスターを作成する必要があります。AKS クラスターの作成方法の詳細については、環境で使用しているツールに基づいて、次の Microsoft 公式ドキュメントを参照してください。 + +* [Azure CLI](https://learn.microsoft.com/ja-jp/azure/aks/learn/quick-kubernetes-deploy-cli) +* [PowerShell](https://learn.microsoft.com/ja-jp/azure/aks/learn/quick-kubernetes-deploy-powershell) +* [Azure portal](https://learn.microsoft.com/ja-jp/azure/aks/learn/quick-kubernetes-deploy-portal) + +## 要件 + +ScalarDL Ledger と ScalarDL Auditor を展開する場合は、次のことを行う必要があります。 + +* [サポートされている Kubernetes バージョン](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes)を使用して2つの AKS クラスターを作成します。 + * ScalarDL Ledger 用の1つの AKS クラスター + * ScalarDL Auditor 用の1つの AKS クラスター +* Kubernetes のバージョンとプロジェクトの要件に基づいて AKS クラスターを構成します。 + * 仮想ネットワーク(VNet) は以下のように設定します。 + * [Virtual network peering](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-manage-peering) を使用して、**AKS の VNet (Ledger 用)** と **AKS の VNet (Auditor 用)** を接続します。これを行うには、VNet の作成時に **AKS の VNet (Ledger 用)** と **AKS の VNet (Auditor 用)** に異なる IP 範囲を指定する必要があります。 + * ScalarDL (Auditor モード) が適切に動作するように **Ledger と Auditor 間の接続**を許可します。 + * これらのネットワーク要件の詳細については、[ScalarDL Auditor Mode のネットワークピアリングの構成](NetworkPeeringForScalarDLAuditor.mdx)を参照してください。 + +:::warning + +ScalarDL でのビザンチン障害検出が適切に機能するには、ScalarDL Ledger および ScalarDL Auditor のデプロイと同じ AKS クラスターにアプリケーションポッドをデプロイしないでください。 + +::: + +## 推奨事項 (オプション) + +以下は、ScalarDL Ledger および ScalarDL Auditor を展開するための推奨事項の一部です。これらの推奨事項は必須ではないため、ニーズに基づいてこれらの推奨事項を適用するかどうかを選択できます。 + +### AKS クラスターごとに少なくとも3つのワーカーノードと3つのポッドを作成します。 + +AKS クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。ワーカーノードに3つのPodを分散させるための `podAntiAffinity` の [ScalarDL Ledgerサンプル設定](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml) と [ScalarDL Auditorサンプル設定](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-audit-custom-values.yaml)をご覧ください。 + +:::note + +ワーカーノードを異なる[アベイラビリティゾーン](https://learn.microsoft.com/en-us/azure/availability-zones/az-overview) (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### ScalarDL Ledger および ScalarDL Auditor ノードプールのワーカーノードには 4vCPU / 8GB メモリノードを使用します。 + +商用ライセンスの観点から、ScalarDL Ledger または ScalarDL Auditor を実行する各ポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDL Ledger および ScalarDL Auditor ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDL Ledger の AKS クラスター + * ScalarDL Ledger ポッド (2vCPU / 4GB) + * Envoy プロキシ + * 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) + * Kubernetes コンポーネント +* ScalarDL Auditor 用の AKS クラスター + * ScalarDL Auditor ポッド (2vCPU / 4GB) + * Envoy プロキシ + * 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) + * Kubernetes コンポーネント + +これを念頭に置き、[少なくとも3つのワーカーノードと3つのポッドを作成する](#create-at-least-three-worker-nodes-and-three-pods-per-aks-cluster)で説明されているように、少なくとも 4vCPU / 8 GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。また、ビザンチン障害検出が適切に機能するには、ScalarDL Ledger および ScalarDL Auditor のデプロイと同じ AKS クラスターにアプリケーションポッドをデプロイできないことに注意してください。 + +ただし、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが運用環境の最小環境となります。また、システムのワークロードに応じて、AKS クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDL Ledger ポッド、ScalarDL Auditor ポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、ワーカーノードのリソースを決定するときにワーカーノード上の最大ポッド数を考慮する必要があります。 + +### ScalarDL Ledger および ScalarDL Auditor ポッドのノードプールを作成する + +AKS は、既定でシステムポッド (AKS を実行し続けるために使用される) に優先される **agentpool** という名前のシステムノードプールを1つ作成します。ScalarDL Ledger および ScalarDL Auditor ポッド用に **user** モードで追加のノードプールを作成し、それらの追加のノードプールに ScalarDL Ledger および ScalarDL Auditor ポッドをデプロイすることをお勧めします。 + +### AKS でクラスターオートスケーラーを構成する + +[Horizontal Pod Autoscaler)](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#horizontal-pod-autoscaler) を使用して ScalarDL Ledger および ScalarDL Auditor ポッドを自動的にスケーリングする場合は、AKS でもクラスターオートスケーラーを構成する必要があります。詳細については、Microsoft の公式ドキュメント [Cluster autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#cluster-autoscaler) を参照してください。 + +さらに、クラスターオートスケーラーを構成する場合は、AKS がスケーリング後にネットワークの問題なく動作できるように、十分な数の IP が存在することを確認するために AKS 用の VNet にサブネットを作成する必要があります。必要な IP の数は、ネットワークプラグインによって異なります。必要な IP 数の詳細については、以下を参照してください。 + +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### プライベートネットワーク上に AKS クラスターを作成する + +ScalarDL Ledger と ScalarDL Auditor はインターネットアクセス経由でユーザーに直接サービスを提供しないため、プライベートネットワーク (VNet のプライベートサブネット) 上に AKS クラスターを作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDL Ledger および ScalarDL Auditor にアクセスすることをお勧めします。 + +### 必要に応じて、Azure CNI を使用して AKS クラスターを作成します。 + +AKS の既定のネットワークプラグインは [kubenet](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) です。要件が kubenet と一致しない場合は、[Azure Container Networking Interface (CNI)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) を使用する必要があります。 + +たとえば、複数の ScalarDL Ledger 環境と ScalarDL Auditor 環境を2つの AKS クラスターではなく1つの AKS クラスターのみにデプロイし (マルチテナントの ScalarDL をデプロイするなど)、[Kubernetes NetworkPolicies](https://kubernetes.io/docs/concepts/services-networking/network-policies/) を使用して各テナント間の接続を制御する場合、kubenet は Calico ネットワークポリシーのみ。[Azure サポートチームはサポートしていません](https://learn.microsoft.com/en-us/azure/aks/use-network-policies#differences-between-azure-network-policy-manager-and-calico-network-policy-and-their-capabilities)。Calico ネットワークポリシーは、Calico コミュニティまたは追加の有料サポートを通じてのみサポートされることに注意してください。 + +ただし、Azure サポートチームとエンジニアリングチームは Azure CNI をサポートします。したがって、Kubernetes NetworkPolicies を使用して Azure サポートチームからサポートを受けたい場合は、Azure CNI を使用する必要があります。kubenet と Azure CNI の違いの詳細については、次の Microsoft 公式ドキュメントを参照してください。 + +* [Network concepts for applications in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/concepts-network) +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### 要件に基づいていくつかのセキュリティ機能を使用して接続を制限する + +ScalarDL および ScalarDL Auditor では、未使用の接続を制限する必要があります。未使用の接続を制限するには、[network security groups](https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview) などの Azure のセキュリティ機能を使用できます。 + +ScalarDL Ledger および ScalarDL Auditor がデフォルトで使用する接続 (ポート) は次のとおりです。 + +* ScalarDL Ledger + * 50051/TCP (クライアントおよび ScalarDL Auditor からのリクエストを受け入れる) + * 50052/TCP (クライアントおよび ScalarDL Auditor からの特権リクエストを受け入れます) + * 50053/TCP (scalar-admin クライアントツールからの一時停止/一時停止解除リクエストを受け入れます) + * 8080/TCP (監視リクエストを受け付ける) +* ScalarDL Auditor + * 40051/TCP (クライアントからのリクエストを受け付ける) + * 40052/TCP (クライアントからの特権リクエストを受け入れます) + * 40053/TCP (scalar-admin クライアントツールからの一時停止および一時停止解除リクエストを受け入れます) + * 8080/TCP (監視リクエストを受け付ける) +* Scalar Envoy (ScalarDL Ledger および ScalarDL Auditor とともに使用) + * 50051/TCP (ScalarDL Ledger の負荷分散) + * 50052/TCP (ScalarDL Ledger の負荷分散) + * 40051/TCP (ScalarDL Auditor の負荷分散) + * 40052/TCP (ScalarDL Auditor の負荷分散) + * 9001/TCP (Scalar Envoy 自体の監視リクエストを受け入れます) + +:::note + +- 設定ファイル (それぞれ `ledger.properties` と `auditor.properties`) で ScalarDL Ledger と ScalarDL Auditor のデフォルトのリスニングポートを変更する場合は、設定したポートを使用して接続を許可する必要があります。 +- AKS 自体が使用する接続も許可する必要があります。AKS トラフィック要件の詳細については、[Control egress traffic using Azure Firewall in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/limit-egress-traffic) を参照してください。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarProducts.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarProducts.mdx new file mode 100644 index 00000000..9e8927fc --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarProducts.mdx @@ -0,0 +1,24 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar 製品用の AKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Scalar 製品用の Azure Kubernetes Service (AKS) クラスターを作成するには、次を参照してください。 + +* [ScalarDB Server 用の AKS クラスターを作成するためのガイドライン](CreateAKSClusterForScalarDB.mdx) +* [ScalarDL Ledger 用の AKS クラスターを作成するためのガイドライン](CreateAKSClusterForScalarDL.mdx) +* [ScalarDL Ledger および ScalarDL Auditor 用の AKS クラスターを作成するためのガイドライン](CreateAKSClusterForScalarDLAuditor.mdx) + +Scalar 製品を AKS にデプロイするには、次を参照してください。 + +* [AKS に ScalarDB Server をデプロイする](ManualDeploymentGuideScalarDBServerOnAKS.mdx) +* [AKS に ScalarDL Ledger をデプロイする](ManualDeploymentGuideScalarDLOnAKS.mdx) +* [ScalarDL Ledger と ScalarDL Auditor を AKS にデプロイする](ManualDeploymentGuideScalarDLAuditorOnAKS.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateBastionServer.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateBastionServer.mdx new file mode 100644 index 00000000..059eb28b --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateBastionServer.mdx @@ -0,0 +1,51 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 踏み台サーバーを作成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、踏み台サーバーを作成し、Scalar 製品を展開するためのいくつかのツールをインストールする方法について説明します。 + +## Kubernetes クラスターと同じプライベートネットワーク上にサーバーを作成します + +Scalar 製品用の Kubernetes クラスターはプライベートネットワーク上に作成することをお勧めします。プライベートネットワーク上に Kubernetes クラスターを作成する場合は、Kubernetes クラスターにアクセスするために、同じプライベートネットワーク上に踏み台サーバーを作成する必要があります。 + +## ツールをインストールする + +公式ドキュメントに従って、次のツールを踏み台サーバーにインストールしてください。 + +* [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) +* [helm](https://helm.sh/docs/intro/install/) + +## kubeconfig の構成 + +kubectl コマンドをインストールした後、Kubernetes クラスターにアクセスできるように **kubeconfig** を構成する必要があります。各マネージド Kubernetes での kubeconfig の設定方法の詳細については、次の公式ドキュメントを参照してください。 + +Amazon EKS (Amazon Elastic Kubernetes Service) を使用する場合は、公式ドキュメント [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) に従って **AWS CLI** をインストールする必要があります。その後、[Creating or updating a kubeconfig file for an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html) で kubeconfig を設定する方法を確認できます。 + +AKS (Azure Kubernetes Service) を使用する場合は、公式ドキュメント [How to install the Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) に従って **Azure CLI** をインストールする必要があります。その後、[az aks get-credentials](https://learn.microsoft.com/en-us/cli/azure/aks?view=azure-cli-latest#az-aks-get-credentials) で kubeconfig を構成する方法を確認できます。 + +## インストールを確認する + +ツールがインストールされているかどうかは、次のようにして確認できます。 + +* kubectl + ```console + kubectl version --client + ``` +* helm + ```console + helm version + ``` + +次のように、kubeconfig が適切に構成されているかどうかを確認することもできます。URL 応答が表示された場合、kubectl はクラスターにアクセスするように正しく構成されています。 +```console +kubectl cluster-info +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDB.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDB.mdx new file mode 100644 index 00000000..57c58162 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDB.mdx @@ -0,0 +1,90 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsJapanese +--- + +# (非推奨) ScalarDB Server 用の EKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +:::warning + +ScalarDB Server は非推奨になりました。代わりに [ScalarDB Cluster](ManualDeploymentGuideScalarDBClusterOnEKS.mdx) を使用してください。 + +::: + +このドキュメントでは、ScalarDB Server デプロイメント用の Amazon Elastic Kubernetes Service (EKS) クラスターを作成するための要件と推奨事項について説明します。ScalarDB Server を EKS クラスターにデプロイする方法の詳細については、[ScalarDB Server を Amazon EKS にデプロイする](ManualDeploymentGuideScalarDBServerOnEKS.mdx)を参照してください。 + +## あなたが始める前に + +EKS クラスターは、次の要件、推奨事項、およびプロジェクトの要件に基づいて作成する必要があります。EKS クラスターの作成方法の詳細については、Amazon の公式ドキュメント [Creating an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html) を参照してください。 + +## 要件 + +ScalarDB Server を展開するときは、次のことを行う必要があります。 + +* [サポートされている Kubernetes バージョン](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes)を使用して EKS クラスターを作成します。 +* Kubernetes のバージョンとプロジェクトの要件に基づいて EKS クラスターを構成します。 + +## 推奨事項 (オプション) + +以下に、ScalarDB Server を展開するための推奨事項をいくつか示します。これらの推奨事項は必須ではないため、ニーズに基づいてこれらの推奨事項を適用するかどうかを選択できます。 + +### 少なくとも3つのワーカーノードと3つのポッドを作成します + +EKS クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つのポッドをワーカーノードに分散させるための `podAntiAffinity` の[サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardb-custom-values.yaml)を参照できます。 + +:::note + +ワーカーノードを異なる [availability zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### ScalarDB Server ノードグループのワーカーノードには 4vCPU / 8GB メモリノードを使用します。 + +商用ライセンスの観点から、ScalarDB Server を実行する1つのポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDB Server ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDB Server ポッド (2vCPU / 4GB) +* Envoy プロキシ +* アプリケーションポッド (同じワーカーノード上でアプリケーションのポッドを実行することを選択した場合) +* 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) +* Kubernetes コンポーネント + +これを念頭に置き、[少なくとも3つのワーカーノードと3つのポッドを作成する](#create-at-least-three-worker-nodes-and-three-pods)で説明されているように、少なくとも 4vCPU / 8 GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。 + +ただし、運用環境では、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが最小条件となります。システムのワークロードに応じて、EKS クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDB Server ポッド、アプリケーションのポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、ワーカーノードのリソースを決定するときにワーカーノード上の最大ポッド数を考慮する必要があります。 + +### EKS でクラスターオートスケーラーを構成する + +[Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html) を使用して ScalarDB Server ポッドを自動的にスケーリングする場合は、EKS でクラスターオートスケーラーも構成する必要があります。詳細については、Amazon の公式ドキュメント [Autoscaling](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html#cluster-autoscaler) を参照してください。 + +さらに、クラスターオートスケーラーを構成する場合は、プレフィックス (`/24` など) を付けて EKS 用の Amazon Virtual Private Cloud (VPC) にサブネットを作成し、十分な数の IP が存在することを確認して、EKS がクラスターオートスケーラーなしで動作できるようにする必要があります。スケーリング後のネットワークの問題。 + +### プライベートネットワーク上に EKS クラスターを作成する + +ScalarDB Server はインターネットアクセス経由でユーザーにサービスを直接提供しないため、プライベートネットワーク (VPC 内のプライベートサブネット) 上に EKS クラスターを作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDB Server にアクセスすることをお勧めします。 + +### 要件に基づいていくつかのセキュリティ機能を使用して接続を制限する + +ScalarDB Server では未使用の接続を制限する必要があります。未使用の接続を制限するには、[security groups](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) や [network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) など、AWS のいくつかのセキュリティ機能を使用できます。 + +ScalarDB Server がデフォルトで使用する接続 (ポート) は次のとおりです。 + +* ScalarDB Server + * 60051/TCP (クライアントからのリクエストを受け付ける) + * 8080/TCP (監視リクエストを受け付ける) +* Scalar Envoy (ScalarDB Server とともに使用) + * 60051/TCP (ScalarDB Server の負荷分散) + * 9001/TCP (Scalar Envoy 自体の監視リクエストを受け入れます) + +:::note + +- 構成ファイル (`database.properties`) で ScalarDB Server のデフォルトのリスニングポートを変更する場合は、構成したポートを使用して接続を許可する必要があります。 +- EKS 自体が使用する接続も許可する必要があります。Amazon EKS セキュリティグループの要件の詳細については、[Amazon EKS security group requirements and considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html) を参照してください。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDBCluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDBCluster.mdx new file mode 100644 index 00000000..4a46d3c6 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDBCluster.mdx @@ -0,0 +1,90 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster 用の EKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDB Cluster 展開用の Amazon Elastic Kubernetes Service (EKS) クラスターを作成するための要件と推奨事項について説明します。ScalarDB Cluster を EKS クラスターにデプロイする方法の詳細については、[Amazon EKS に ScalarDB Cluster をデプロイする](ManualDeploymentGuideScalarDBClusterOnEKS.mdx) を参照してください。 + +## あなたが始める前に + +EKS クラスターは、次の要件、推奨事項、およびプロジェクトの要件に基づいて作成する必要があります。EKS クラスターの作成方法の詳細については、Amazon の公式ドキュメント [Creating an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html) を参照してください。 + +## 要件 + +ScalarDB Cluster をデプロイする場合は、次のことを行う必要があります。 + +* [サポートされている Kubernetes バージョン](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes)を使用して EKS クラスターを作成します。 +* Kubernetes のバージョンとプロジェクトの要件に基づいて EKS クラスターを構成します。 + +## 推奨事項 (オプション) + +以下は、ScalarDB Cluster をデプロイするための推奨事項の一部です。これらの推奨事項は必須ではないため、ニーズに基づいてこれらの推奨事項を適用するかどうかを選択できます。 + +### 少なくとも3つのワーカーノードと3つのポッドを作成します + +EKS クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つのポッドをワーカーノードに分散させるための `podAntiAffinity` の[サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardb-cluster-custom-values-indirect-mode.yaml)を参照できます。 + +:::note + +ワーカーノードを異なる [availability zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### ScalarDB Cluster ノードグループのワーカーノードには 4vCPU / 8GB メモリノードを使用します。 + +商用ライセンスの観点から、ScalarDB Cluster を実行する1つのポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDB Cluster ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDB Cluster ポッド (2vCPU / 4GB) +* Envoy プロキシ (`indirect` クライアントモードを使用する場合、または Java 以外のプログラミング言語を使用する場合) +* アプリケーションポッド (同じワーカーノード上でアプリケーションのポッドを実行することを選択した場合) +* 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) +* Kubernetes コンポーネント + +:::note + +`direct-kubernetes` モードを使用する場合は、Envoy ポッドをデプロイする必要はありません。 + +::: + +これを念頭に置き、[少なくとも3つのワーカーノードと3つのポッドを作成する](#create-at-least-three-worker-nodes-and-three-pods)で説明されているように、少なくとも 4vCPU / 8 GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。 + +ただし、運用環境では、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが最小条件となります。システムのワークロードに応じて、EKS クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDB Cluster ポッド、アプリケーションのポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、ワーカーノードのリソースを決定するときにワーカーノード上の最大ポッド数を考慮する必要があります。 + +### EKS でクラスターオートスケーラーを構成する + +[Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html) を使用して ScalarDB Cluster ポッドを自動的にスケーリングする場合は、EKS でもクラスターオートスケーラーを構成する必要があります。詳細については、Amazon の公式ドキュメント [Autoscaling](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html#cluster-autoscaler) を参照してください。 + +さらに、クラスターオートスケーラーを構成する場合は、プレフィックス (`/24` など) を付けて EKS 用の Amazon Virtual Private Cloud (VPC) にサブネットを作成し、十分な数の IP が存在することを確認して、EKS がクラスターオートスケーラーなしで動作できるようにする必要があります。スケーリング後のネットワークの問題。 + +### プライベートネットワーク上に EKS クラスターを作成する + +ScalarDB Cluster はインターネットアクセス経由でユーザーにサービスを直接提供しないため、EKS クラスターはプライベートネットワーク (VPC 内のプライベートサブネット) 上に作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDB Cluster にアクセスすることをお勧めします。 + +### 要件に基づいていくつかのセキュリティ機能を使用して接続を制限する + +ScalarDB Cluster で未使用の接続を制限する必要があります。未使用の接続を制限するには、[security groups](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) や [network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) など、AWS のいくつかのセキュリティ機能を使用できます。 + +ScalarDB Cluster がデフォルトで使用する接続 (ポート) は次のとおりです。 + +* ScalarDB Cluster + * 60053/TCP (クライアントからの gRPC または SQL リクエストを受け入れます) + * 8080/TCP (クライアントからの GraphQL リクエストを受け入れます) + * 9080/TCP (監視リクエストを受け付ける) +* Scalar Envoy (ScalarDB Cluster の `間接` モードで使用) + * 60053/TCP (ScalarDB Cluster の負荷分散) + * 9001/TCP (Scalar Envoy 自体の監視リクエストを受け入れます) + +:::note + +- 構成ファイル (`scalardb-cluster-node.properties`) で ScalarDB Clusterのデフォルトのリスニングポートを変更する場合は、構成したポートを使用して接続を許可する必要があります。 +- EKS 自体が使用する接続も許可する必要があります。Amazon EKS セキュリティグループの要件の詳細については、[Amazon EKS security group requirements and considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html) を参照してください。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDL.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDL.mdx new file mode 100644 index 00000000..2e58840a --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDL.mdx @@ -0,0 +1,90 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger の EKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDL Ledger デプロイ用の Amazon Elastic Kubernetes Service (EKS) クラスターを作成するための要件と推奨事項について説明します。ScalarDL Ledger を EKS クラスターにデプロイする方法の詳細については、[ScalarDL Ledger を Amazon EKS にデプロイする](ManualDeploymentGuideScalarDLOnEKS.mdx)を参照してください。 + +## あなたが始める前に + +EKS クラスターは、次の要件、推奨事項、およびプロジェクトの要件に基づいて作成する必要があります。EKS クラスターの作成方法の詳細については、Amazon の公式ドキュメント [Creating an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html) を参照してください。 + +## 要件 + +ScalarDL Ledger を展開するときは、次のことを行う必要があります。 + +* [サポートされている Kubernetes バージョン](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes)を使用して EKS クラスターを作成します。 +* Kubernetes のバージョンとプロジェクトの要件に基づいて EKS クラスターを構成します。 + +:::warning + +ScalarDL でのビザンチン障害検出が適切に機能するには、ScalarDL Ledger デプロイメントと同じ EKS クラスターにアプリケーションポッドをデプロイしないでください。 + +::: + +## 推奨事項 (オプション) + +以下は、ScalarDL Ledger を展開するための推奨事項の一部です。これらの推奨事項は必須ではないため、ニーズに基づいてこれらの推奨事項を適用するかどうかを選択できます。 + +### 少なくとも3つのワーカーノードと3つのポッドを作成します + +EKS クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つのポッドをワーカーノードに分散させるための `podAntiAffinity` の[サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml)を参照できます。 + +:::note + +ワーカーノードを異なる [availability zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### ScalarDL Ledger ノードグループのワーカーノードには 4vCPU / 8GB メモリノードを使用します + +商用ライセンスの観点から、ScalarDL Ledger を実行する1つのポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDL Ledger ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDL Ledger ポッド (2vCPU / 4GB) +* Envoy プロキシ +* 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) +* Kubernetes コンポーネント + +これを念頭に置き、[少なくとも3つのワーカーノードと3つのポッドを作成する](#create-at-least-three-worker-nodes-and-three-pods)で説明されているように、少なくとも 4vCPU / 8 GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。 + +ただし、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが運用環境の最小環境となります。システムのワークロードに応じて、EKS クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDL Ledger ポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、ワーカーノードのリソースを決定するときにワーカーノード上の最大ポッド数を考慮する必要があります。 + +### EKS でクラスターオートスケーラーを構成する + +[Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html) を使用して ScalarDL Ledger ポッドを自動的にスケーリングする場合は、EKS でクラスターオートスケーラーも構成する必要があります。詳細については、Amazon の公式ドキュメント [Autoscaling](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html#cluster-autoscaler) を参照してください。 + +さらに、クラスターオートスケーラーを構成する場合は、プレフィックス (`/24`など) を付けて EKS 用の Amazon Virtual Private Cloud (VPC) にサブネットを作成し、十分な数の IP が存在することを確認して、EKS がクラスターオートスケーラーなしで動作できるようにする必要があります。スケーリング後のネットワークの問題。 + +### プライベートネットワーク上に EKS クラスターを作成する + +ScalarDL Ledger はインターネットアクセス経由でユーザーにサービスを直接提供しないため、プライベートネットワーク (VPC 内のプライベートサブネット) 上に EKS クラスターを作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDL Ledger にアクセスすることをお勧めします。 + +### 要件に基づいていくつかのセキュリティ機能を使用して接続を制限する + +ScalarDL Ledger では未使用の接続を制限する必要があります。未使用の接続を制限するには、[security groups](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) や [network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) など、AWS のいくつかのセキュリティ機能を使用できます。 + +ScalarDL Ledger がデフォルトで使用する接続 (ポート) は次のとおりです。 + +* ScalarDL Ledger + * 50051/TCP (クライアントからのリクエストを受け付ける) + * 50052/TCP (クライアントからの特権リクエストを受け入れます) + * 50053/TCP (scalar-admin クライアントツールからの一時停止および一時停止解除リクエストを受け入れます) + * 8080/TCP (監視リクエストを受け付ける) +* Scalar Envoy (ScalarDL Ledger とともに使用) + * 50051/TCP (ScalarDL Ledger の負荷分散) + * 50052/TCP (ScalarDL Ledger の負荷分散) + * 9001/TCP (Scalar Envoy 自体の監視リクエストを受け入れます) + +:::note + +- 設定ファイル (`ledger.properties`) で ScalarDL Ledger のデフォルトのリスニングポートを変更する場合は、設定したポートを使用して接続を許可する必要があります。 +- EKS 自体が使用する接続も許可する必要があります。Amazon EKS セキュリティグループの要件の詳細については、[Amazon EKS security group requirements and considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html) を参照してください。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDLAuditor.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDLAuditor.mdx new file mode 100644 index 00000000..191c562f --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDLAuditor.mdx @@ -0,0 +1,109 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger および ScalarDL Auditor 用の EKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDL Ledger および ScalarDL Auditor のデプロイ用の Amazon Elastic Kubernetes Service (EKS) クラスターを作成するための要件と推奨事項について説明します。ScalarDL Ledger と ScalarDL Auditor を EKS クラスターにデプロイする方法の詳細については、[ScalarDL Ledger と ScalarDL Auditor を Amazon EKS にデプロイする](ManualDeploymentGuideScalarDLAuditorOnEKS.mdx) を参照してください。 + +## あなたが始める前に + +EKS クラスターは、次の要件、推奨事項、およびプロジェクトの要件に基づいて作成する必要があります。EKS クラスターの作成方法の詳細については、Amazon の公式ドキュメント [Creating an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html) を参照してください。 + +## 要件 + +ScalarDL Ledger と ScalarDL Auditor を展開する場合は、次のことを行う必要があります。 + +* [サポートされている Kubernetes バージョン](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes)を使用して2つの EKS クラスターを作成します。 + * ScalarDL Ledger 用の1つの EKS クラスター + * ScalarDL Auditor 用の1つの EKS クラスター +* Kubernetes のバージョンとプロジェクトの要件に基づいて EKS クラスターを構成します。 + ※ Amazon Virtual Private Cloud (VPC) は次のように設定します。 + * **EKS の VPC (Ledger 用)** と **EKS の VPC (Auditor 用)** を [VPC peering](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html) を使用して接続します。これを行うには、VPC の作成時に **EKS の VPC (Ledger 用)** と **EKS の VPC (Auditor 用)** に異なる IP 範囲を指定する必要があります。 + * ScalarDL (Auditor モード) が適切に動作するように **Ledger と Auditor 間の接続**を許可します。 + * これらのネットワーク要件の詳細については、[ScalarDL Auditor Mode のネットワークピアリングの構成](NetworkPeeringForScalarDLAuditor.mdx)を参照してください。 + +:::warning + +ScalarDL でのビザンチン障害検出が適切に機能するには、ScalarDL Ledger および ScalarDL Auditor のデプロイメントと同じ EKS クラスターにアプリケーションポッドをデプロイしないでください。 + +::: + +## 推奨事項 (オプション) + +以下は、ScalarDL Ledger および ScalarDL Auditor を展開するための推奨事項の一部です。これらの推奨事項は必須ではないため、ニーズに基づいてこれらの推奨事項を適用するかどうかを選択できます。 + +### EKS クラスターごとに少なくとも3つのワーカーノードと3つのポッドを作成します + +EKS クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つの Pod をワーカーノードに分散させるための `podAntiAffinity` の [ScalarDL Ledger サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml)と [ScalarDL Auditor サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-audit-custom-values.yaml)を参照できます。 + +:::note + +ワーカーノードを異なる [availability zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### ScalarDL Ledger および ScalarDL Auditor ノードグループのワーカーノードには 4vCPU / 8GB メモリノードを使用します。 + +商用ライセンスの観点から、ScalarDL Ledger または ScalarDL Auditor を実行する各ポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDL Ledger および ScalarDL Auditor ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDL Ledger 用の EKS クラスター + * ScalarDL Ledger ポッド (2vCPU / 4GB) + * Envoy プロキシ + * 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) + * Kubernetes コンポーネント +* ScalarDL Auditor 用の EKS クラスター + * ScalarDL Auditor ポッド (2vCPU / 4GB) + * Envoy プロキシ + * 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) + * Kubernetes コンポーネント + +これを念頭に置き、[少なくとも3つのワーカーノードと3つのポッドを作成する](#create-at-least-three-worker-nodes-and-three-pods-per-eks-cluster)で説明されているように、少なくとも 4vCPU / 8 GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。また、ビザンチン障害検出が適切に機能するには、ScalarDL Ledger および ScalarDL Auditor のデプロイメントと同じ EKS クラスターにアプリケーションポッドをデプロイできないことを覚えておいてください。 + +ただし、実稼働環境としては、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを持つ3つのノードが必要です。システムのワークロードに応じて、EKS クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDL Ledger ポッド、ScalarDL Auditor ポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、ワーカーノードのリソースを決定するときにワーカーノード上の最大ポッド数を考慮する必要があります。 + +### EKS でクラスターオートスケーラーを構成する + +[Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html) を使用して ScalarDL Ledger または ScalarDL Auditor ポッドを自動的にスケーリングする場合は、EKS でクラスターオートスケーラーも構成する必要があります。詳細については、Amazon の公式ドキュメント [Autoscaling](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html#cluster-autoscaler) を参照してください。 + +さらに、クラスターオートスケーラーを構成する場合は、スケーリング後にネットワークの問題なく EKS が動作できるように、十分な数の IP が存在することを確認するために、プレフィックス (`/24` など) を付けて EKS 用の VPC にサブネットを作成する必要があります。 + +### プライベートネットワーク上に EKS クラスターを作成する + +ScalarDL Ledger と ScalarDL Auditor はインターネットアクセス経由でユーザーに直接サービスを提供しないため、プライベートネットワーク (VPC 内のプライベートサブネット) 上に EKS クラスターを作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDL Ledger および ScalarDL Auditor にアクセスすることをお勧めします。 + +### 要件に基づいていくつかのセキュリティ機能を使用して接続を制限する + +ScalarDL Ledger および ScalarDL Auditor で未使用の接続を制限する必要があります。未使用の接続を制限するには、[security groups](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) や [network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) など、AWS のいくつかのセキュリティ機能を使用できます。 + +ScalarDL Ledger および ScalarDL Auditor がデフォルトで使用する接続 (ポート) は次のとおりです。 + +* ScalarDL Ledger + * 50051/TCP (クライアントおよび ScalarDL Auditor からのリクエストを受け入れる) + * 50052/TCP (クライアントおよび ScalarDL Auditor からの特権リクエストを受け入れます) + * 50053/TCP (scalar-admin クライアントツールからの一時停止および一時停止解除リクエストを受け入れます) + * 8080/TCP (監視リクエストを受け付ける) +* ScalarDL Auditor + * 40051/TCP (クライアントからのリクエストを受け付ける) + * 40052/TCP (クライアントからの特権リクエストを受け入れます) + * 40053/TCP (scalar-admin クライアントツールからの一時停止および一時停止解除リクエストを受け入れます) + * 8080/TCP (監視リクエストを受け付ける) +* Scalar Envoy (ScalarDL Ledger および ScalarDL Auditor とともに使用) + * 50051/TCP (ScalarDL Ledger の負荷分散) + * 50052/TCP (ScalarDL Ledger の負荷分散) + * 40051/TCP (ScalarDL Auditor の負荷分散) + * 40052/TCP (ScalarDL Auditor の負荷分散) + * 9001/TCP (Scalar Envoy 自体の監視リクエストを受け入れます) + +:::note + +- 設定ファイル (それぞれ `ledger.properties` と `auditor.properties`) で ScalarDL Ledger と ScalarDL Auditor のデフォルトのリスニングポートを変更する場合は、設定したポートを使用して接続を許可する必要があります。 +- EKS 自体が使用する接続も許可する必要があります。Amazon EKS セキュリティグループの要件の詳細については、[Amazon EKS security group requirements and considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html) を参照してください。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarProducts.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarProducts.mdx new file mode 100644 index 00000000..fce1470b --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarProducts.mdx @@ -0,0 +1,25 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar 製品用の Amazon EKS クラスターを作成するためのガイドライン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Scalar 製品用の Amazon Elastic Kubernetes Service (EKS) クラスターを作成するには、以下を参照してください。 + +* [ScalarDB Cluster 用の EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarDBCluster.mdx) +* [(非推奨) ScalarDB Server 用の EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarDB.mdx) +* [ScalarDL Ledger 用の EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarDL.mdx) +* [ScalarDL Ledger および ScalarDL Auditor 用の EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarDLAuditor.mdx) + +Scalar 製品を Amazon EKS にデプロイするには、以下を参照してください。 + +* [ScalarDB Server を Amazon EKS (Amazon Elastic Kubernetes Service) にデプロイする](ManualDeploymentGuideScalarDBServerOnEKS.mdx) +* [ScalarDL Ledger を Amazon EKS (Amazon Elastic Kubernetes Service) にデプロイする](ManualDeploymentGuideScalarDLOnEKS.mdx) +* [ScalarDL Ledger と ScalarDL Auditor を Amazon EKS (Amazon Elastic Kubernetes Service) にデプロイする](ManualDeploymentGuideScalarDLAuditorOnEKS.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx new file mode 100644 index 00000000..3cf970de --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx @@ -0,0 +1,151 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar 製品で TLS 接続に利用する秘密鍵と証明書ファイルを作成する方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB Cluster および ScalarDL で TLS 接続に利用する秘密鍵と証明書ファイルを作成する方法について説明します。TLS 機能を有効にする場合は、秘密鍵と証明書ファイルを準備する必要があります。 + +## 証明書の要件 + +* 秘密鍵と証明書ファイルのアルゴリズムとしては `RSA` または `ECDSA` のみ使用可能です。 + +## サンプルの秘密鍵と証明書ファイルを作成する手順の例 + +[`cfssl` および `cfssljson`](https://github.com/cloudflare/cfssl) を使用して、サンプルの秘密鍵と証明書ファイルを作成できます。`cfssl` と `cfssljson` をまだインストールしていない場合は、まずインストールしてください。 + +:::note + +* `openssl` などの他のツールを使用して、秘密鍵と証明書ファイルを作成することもできます。あるいは、サードパーティ CA またはプライベート CA の管理者に本番環境用の秘密鍵と証明書の作成を依頼することもできます。 +* この例では自己署名証明書を作成します。ただし、これらの証明書を運用環境では使用しないことを強くお勧めします。セキュリティ要件に基づいて実稼働環境用の証明書ファイルを作成するように、信頼できる発行者 (パブリック CA またはプライベート CA) に依頼してください。 + +::: + +1. 作業ディレクトリを作成します。 + + ```console + mkdir -p ${HOME}/scalar/example/certs/ + ``` + +1. 作業ディレクトリを `${HOME}/scalar/example/certs/` ディレクトリに変更します。 + + ```console + cd ${HOME}/scalar/example/certs/ + ``` + +1. CA の情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalar/example/certs/ca.json + { + "CN": "scalar-example-ca", + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Example CA" + } + ] + } + EOF + ``` + +1. CA の秘密鍵と証明書ファイルを作成します。 + + ```console + cfssl gencert -initca ca.json | cfssljson -bare ca + ``` + +1. CA の設定情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalar/example/certs/ca-config.json + { + "signing": { + "default": { + "expiry": "87600h" + }, + "profiles": { + "scalar-example-ca": { + "expiry": "87600h", + "usages": [ + "signing", + "key encipherment", + "server auth" + ] + } + } + } + } + EOF + ``` + +1. サーバーの情報を含む JSON ファイルを作成します。 + + ```console + cat << 'EOF' > ${HOME}/scalar/example/certs/server.json + { + "CN": "scalar-example-server", + "hosts": [ + "server.scalar.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Example Server" + } + ] + } + EOF + ``` + +1. サーバーの秘密鍵と証明書ファイルを作成します。 + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-example-ca server.json | cfssljson -bare server + ``` + +1. 秘密鍵と証明書ファイルが作成されたことを確認します。 + + ```console + ls -1 + ``` + + [コマンド実行結果] + + ```console + ca-config.json + ca-key.pem + ca.csr + ca.json + ca.pem + server-key.pem + server.csr + server.json + server.pem + ``` + + この場合: + + * `server-key.pem` は秘密鍵ファイルです。 + * `server.pem` は証明書ファイルです。 + * `ca.pem` はルート CA 証明書ファイルです。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToGetContainerImages.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToGetContainerImages.mdx new file mode 100644 index 00000000..9867c099 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToGetContainerImages.mdx @@ -0,0 +1,28 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar 製品のコンテナイメージの取得方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Scalar 製品のコンテナイメージは、いくつかの方法で取得できます。以下のいずれかの方法をお選びください。 + + + + 商用ライセンスをお持ちの場合は、パブリックコンテナーリポジトリからコンテナイメージを取得できます。コンテナイメージの使用方法の詳細については、[コンテナイメージの使用方法](./HowToUseContainerImages.mdx)を参照してください。 + + + Scalar 製品は AWS Marketplace から入手できます。AWS Marketplace の詳細については、[AWS Marketplace 経由で Scalar 製品をインストールする方法](./AwsMarketplaceGuide.mdx)を参照してください。 + + + 現在、Azure Marketplace の Scalar 製品は利用できません。代わりに他の方法を使用してください。 + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToScaleScalarDB.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToScaleScalarDB.mdx new file mode 100644 index 00000000..addedef2 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToScaleScalarDB.mdx @@ -0,0 +1,49 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB をスケーリングする方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB をスケーリングする方法について説明します。ここでは、[Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) (推奨されているデプロイ方法) を使用して ScalarDB Cluster をデプロイしていることを前提としています。 + +:::note + +ScalarDB Cluster 側にボトルネックがある場合は、ScalarDB Cluster をスケーリングすることでパフォーマンスの問題を解決できる場合があります。ただし、パフォーマンスの問題はバックエンドデータベースのボトルネックによって発生することがあります。このような場合、ScalarDB Cluster をスケーリングしてもパフォーマンスの問題は解決されません。 + +代わりに、ボトルネックが存在する場所を確認してください。ボトルネックがバックエンドデータベースに存在する場合は、バックエンドデータベースのスケーリングを検討してください。 + +::: + + + + + 1. カスタム値ファイルに以下を追加します。`` を、スケーリングするポッドの数に置き換えます。 + + ```yaml + scalardbCluster: + replicaCount: + ``` + + 1. 更新されたカスタム値ファイルを使用する次の `helm upgrade` コマンドを実行して、ScalarDB Cluster のデプロイメントをアップグレードします。説明に従って、山括弧内の内容を必ず置き換えてください。 + + ```console + helm upgrade scalar-labs/scalardb-cluster -n -f / --version + ``` + + + + + ScalarDB Core は Java ライブラリとして提供されます。そのため、アプリケーションをスケールさせると、ScalarDB もアプリケーションに合わせてスケールされます。 + + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToScaleScalarDL.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToScaleScalarDL.mdx new file mode 100644 index 00000000..dda47411 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToScaleScalarDL.mdx @@ -0,0 +1,58 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL をスケーリングする方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDL をスケーリングする方法について説明します。ここでは、[Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) (推奨されているデプロイ方法) を使用して ScalarDL をデプロイしていることを前提としています。 + +:::note + +ScalarDL 側にボトルネックがある場合は、ScalarDL をスケーリングすることでパフォーマンスの問題を解決できる場合があります。ただし、パフォーマンスの問題はバックエンドデータベースのボトルネックによって発生することがあります。このような場合、ScalarDL をスケーリングしてもパフォーマンスの問題は解決されません。 + +代わりに、ボトルネックが存在する場所を確認してください。ボトルネックがバックエンドデータベースに存在する場合は、バックエンドデータベースのスケーリングを検討してください。 + +::: + + + + + 1. カスタム値ファイルに以下を追加します。`` を、スケーリングするポッドの数に置き換えます。 + + ```yaml + ledger: + replicaCount: + ``` + + 1. 更新されたカスタム値ファイルを使用する次の `helm upgrade` コマンドを実行して、ScalarDL Ledger のデプロイメントをアップグレードします。説明に従って、山括弧内の内容を必ず置き換えてください。 + + ```console + helm upgrade scalar-labs/scalardl -n -f / --version + ``` + + + + + 1. カスタム値ファイルに以下を追加します。`` を、スケーリングするポッドの数に置き換えます。 + + ```yaml + auditor: + replicaCount: + ``` + + 1. 更新されたカスタム値ファイルを使用する次の `helm upgrade` コマンドを実行して、ScalarDL Auditor のデプロイメントをアップグレードします。説明に従って、山括弧内の内容を必ず置き換えてください。 + + ```console + helm upgrade scalar-labs/scalardl-audit -n -f / --version + ``` + + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDB.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDB.mdx new file mode 100644 index 00000000..fac778aa --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDB.mdx @@ -0,0 +1,89 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB のアップグレード方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB を新しいバージョンにアップグレードする方法について説明します。 + +## 始める前に + +新しいバージョンにアップグレードする前に、[ScalarDB Cluster 互換性マトリックス](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/compatibility/)をチェックして、ScalarDB Cluster とクライアント SDK 間の互換性を確認してください。 + +## アップグレード + +ScalarDB のバージョンのアップグレードについて詳しくは、実行するアップグレードの種類を選択してください。 + + + + メジャーバージョンでは下位互換性が維持されません。そのため、あるメジャーバージョンから別のメジャーバージョンにアップグレードするときには、特別な操作が必要になる場合があります。例: + + - バックエンドデータベース側のデータベーススキーマを更新します。 + - アプリケーションの API を更新します。 + + メジャーバージョンにアップグレードするときに必要なものの詳細については、アップグレードするメジャーバージョンのリリースノートを参照してください。 + + + マイナーバージョンは下位互換性を維持します。そのため、特別な操作を行わなくても、ScalarDB を同じメジャーバージョン内のマイナーバージョンから別のマイナーバージョンにアップグレードできます。たとえば、バックエンドデータベース側のデータベーススキーマを更新したり、アプリケーション内の API を更新したりする必要はありません。 + + + + [Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) を使用して ScalarDB Cluster をデプロイする場合は、次のようにして ScalarDB Cluster のデプロイをアップグレードできます。 + + 1. ScalarDB Cluster Helm Chart のバージョンを環境変数として設定します。これを行うには、次のコマンドを実行して、チャートのバージョンを環境変数 `SCALAR_DB_CLUSTER_CHART_VERSION` に設定します。 + + ```console + SCALAR_DB_CLUSTER_CHART_VERSION=1.5.0 + ``` + + :::tip + + ScalarDB Cluster バージョンに対応するチャートバージョンを検索するには、次のコマンドを実行します。 + + ```console + helm search repo scalar-labs/scalardb-cluster -l + ``` + + 次のコマンドは役に立つかもしれませんが、山括弧内の内容を ScalarDB Cluster のバージョンに置き換えてください。 + + ```console + SCALAR_DB_CLUSTER_VERSION=..; SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + + ::: + + 1. 次のように山括弧内の内容を置き換えて、ScalarDB Cluster のデプロイメントをアップグレードします。 + + ```console + helm upgrade scalar-labs/scalardb-cluster -n -f / --version ${SCALAR_DB_CLUSTER_CHART_VERSION} + ``` + + ScalarDB Cluster のデプロイメントをアップグレードした後は、アプリケーション側の [ScalarDB Cluster Java Client SDK](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-cluster-java-client-sdk) または [ScalarDB Cluster .NET Client SDK](https://www.nuget.org/packages/ScalarDB.Net.Client) のバージョンをアップグレードすることを検討する必要があります。 + + + ScalarDB Core は Java ライブラリとして提供されます。そのため、Java プロジェクトの依存関係を更新し、アプリケーションを再構築して ScalarDB のバージョンをアップグレードできます。 + + + + + パッチバージョンは下位互換性を維持します。そのため、特別な操作を行わなくても、メジャーバージョンとマイナーバージョンが同じであれば、ScalarDB をあるパッチバージョンから別のパッチバージョンにアップグレードできます。たとえば、バックエンドデータベース側でデータベーススキーマを更新したり、アプリケーションで API を更新したりする必要はありません。 + + パッチバージョンへのアップグレード方法は、マイナーバージョンへのアップグレード方法と同様です。アップグレード方法の詳細については、[マイナーバージョンへのアップグレード](?versions=upgrade-minor-version)タブを参照してください。 + + + +:::warning + +ScalarDB は、以前のバージョン (メジャー、マイナー、またはパッチ) へのダウングレードをサポートしていません。新しいバージョンへのアップグレードのみ可能です。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDL.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDL.mdx new file mode 100644 index 00000000..31d2c704 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDL.mdx @@ -0,0 +1,117 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL のアップグレード方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDL の新しいバージョンにアップグレードする方法について説明します。 + +## 始める前に + +新しいバージョンにアップグレードする前に、[ScalarDL 互換性マトリックス](https://scalardl.scalar-labs.com/docs/latest/compatibility/)をチェックして、ScalarDL とクライアント SDK 間の互換性を確認してください。 + +## アップグレード + +ScalarDL のバージョンのアップグレードについて詳しくは、実行するアップグレードの種類を選択してください。 + + + + メジャーバージョンでは下位互換性が維持されません。そのため、あるメジャーバージョンから別のメジャーバージョンにアップグレードするときには、特別な操作が必要になる場合があります。例: + + - バックエンドデータベース側のデータベーススキーマを更新します。 + - アプリケーションの API を更新します。 + + メジャーバージョンにアップグレードするときに必要なものの詳細については、アップグレードするメジャーバージョンのリリースノートを参照してください。 + + + マイナーバージョンは下位互換性を維持します。そのため、特別な操作を行わなくても、ScalarDL を同じメジャーバージョン内のマイナーバージョンから別のマイナーバージョンにアップグレードできます。たとえば、バックエンドデータベース側のデータベーススキーマを更新したり、アプリケーション内の API を更新したりする必要はありません。 + + + + [Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) を使用して ScalarDL Ledger をデプロイする場合は、次のようにして ScalarDL Ledger のデプロイをアップグレードできます。 + + 1. ScalarDL Ledger Helm Chart のバージョンを環境変数として設定します。これを行うには、次のコマンドを実行して、チャートのバージョンを環境変数 `SCALAR_DL_LEDGER_CHART_VERSION` に設定します。 + + ```console + SCALAR_DL_LEDGER_CHART_VERSION=4.8.0 + ``` + + :::tip + + ScalarDL Ledger バージョンに対応するチャートバージョンは、次のように検索できます。 + + ```console + helm search repo scalar-labs/scalardl -l + ``` + + 次のコマンドは役に立つかもしれませんが、山括弧内の内容を ScalarDL Ledger のバージョンに置き換えてください。 + + ```console + SCALAR_DL_VERSION=..; SCALAR_DL_LEDGER_CHART_VERSION=$(helm search repo scalar-labs/scalardl -l | grep -v -e "scalar-labs/scalardl-audit" | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + + ::: + + 1. 次のように山括弧内の内容を置き換えて、ScalarDL Ledger デプロイメントをアップグレードします。 + + ```console + helm upgrade scalar-labs/scalardl -n -f / --version ${SCALAR_DL_LEDGER_CHART_VERSION} + ``` + + ScalarDL Ledger デプロイメント (および Auditor モードを使用している場合は ScalarDL Auditor デプロイメント) をアップグレードした後、アプリケーション側で [ScalarDL Java Client SDK](https://mvnrepository.com/artifact/com.scalar-labs/scalardl-java-client-sdk) のバージョンをアップグレードすることを検討する必要があります。 + + + [Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) を使用して ScalarDL Auditor をデプロイする場合は、次のようにして ScalarDL Auditor のデプロイをアップグレードできます。 + + 1. ScalarDL Auditor Helm Chart のバージョンを環境変数として設定します。これを行うには、次のコマンドを実行して、チャートのバージョンを環境変数 `SCALAR_DL_AUDITOR_CHART_VERSION` に設定します。 + + ```console + SCALAR_DL_AUDITOR_CHART_VERSION=2.8.0 + ``` + + :::tip + + ScalarDL Auditor バージョンに対応するチャートバージョンは、次のように検索できます。 + + ```console + helm search repo scalar-labs/scalardl-audit -l + ``` + + 次のコマンドは役に立つかもしれませんが、山括弧内の内容を ScalarDL Auditor のバージョンに置き換えてください。 + + ```console + SCALAR_DL_VERSION=..; SCALAR_DL_AUDITOR_CHART_VERSION=$(helm search repo scalar-labs/scalardl-audit -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + + ::: + + 1. 次のように山括弧内の内容を置き換えて、ScalarDL Auditor のデプロイメントをアップグレードします。 + + ```console + helm upgrade scalar-labs/scalardl-audit -n -f / --version ${SCALAR_DL_AUDITOR_CHART_VERSION} + ``` + + ScalarDL Auditor デプロイメントと ScalarDL Ledger デプロイメントをアップグレードした後、アプリケーション側で [ScalarDL Java Client SDK](https://mvnrepository.com/artifact/com.scalar-labs/scalardl-java-client-sdk) のバージョンをアップグレードすることを検討する必要があります。 + + + + + パッチバージョンは下位互換性を維持します。そのため、特別な操作を行わなくても、メジャーバージョンとマイナーバージョンが同じであれば、ScalarDL を 1つのパッチバージョンから別のパッチバージョンにアップグレードできます。たとえば、バックエンドデータベース側でデータベーススキーマを更新したり、アプリケーションで API を更新したりする必要はありません。 + + パッチバージョンへのアップグレード方法は、マイナーバージョンへのアップグレード方法と同様です。アップグレード方法の詳細については、[マイナーバージョンへのアップグレード](?versions=upgrade-minor-version)タブを参照してください。 + + + +:::warning + +ScalarDL は、以前のバージョン (メジャー、マイナー、またはパッチ) へのダウングレードをサポートしていません。新しいバージョンへのアップグレードのみ可能です。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUseContainerImages.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUseContainerImages.mdx new file mode 100644 index 00000000..61a7ec7f --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/HowToUseContainerImages.mdx @@ -0,0 +1,139 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# コンテナイメージの使用方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +パブリックコンテナリポジトリからコンテナイメージをプルできます。コンテナイメージを使用する場合は、`.properties` ファイルにライセンスキーと証明書を設定する必要があります。 + +## 前提条件 + +パブリックコンテナイメージは、次の製品とバージョンで利用できます。 + +* ScalarDB Cluster v3.12以降 +* ScalarDL v3.9以降 + +## パブリックコンテナリポジトリからコンテナイメージをプルします。 + +各製品のコンテナイメージをパブリックコンテナリポジトリからプルできます。コンテナイメージをプルするには、Scalar 製品を選択して、コンテナイメージへのリンクを表示します。 + + + + ScalarDB Enterprise のエディションを選択します。 + + + https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-node-byol-standard + + + https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-node-byol-premium + + + + + https://github.com/orgs/scalar-labs/packages/container/package/scalardl-ledger-byol + + + https://github.com/orgs/scalar-labs/packages/container/package/scalardl-auditor-byol + + + +Scalar Helm Chart を使用する場合は、カスタム値ファイルに `*.image.repository` を次のように設定してください。Scalar 製品を選択して、`*.image.repository` を設定する方法を確認してください。 + + + + ScalarDB Enterprise のエディションを選択します。 + + + ```yaml + scalardbCluster: + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-standard" + ``` + + + ```yaml + scalardbCluster: + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium" + ``` + + + + + ```yaml + ledger: + image: + repository: "ghcr.io/scalar-labs/scalardl-ledger-byol" + ``` + + + ```yaml + auditor: + image: + repository: "ghcr.io/scalar-labs/scalardl-auditor-byol" + ``` + + + +## `.properties` ファイルにライセンスキーを設定します + +コンテナイメージを実行するには、`.properties` ファイルに `ライセンスキー` と `証明書` を設定する必要があります。Scalar 製品を選択して、`license key` と `certificate` を設定する方法を確認してください。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)までご連絡ください。 + + + + ```properties + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem= + ``` + + + ```properties + scalar.dl.licensing.license_key= + scalar.dl.licensing.license_check_cert_pem= + ``` + + + ```properties + scalar.dl.licensing.license_key= + scalar.dl.licensing.license_check_cert_pem= + ``` + + + +Scalar Helm Chart を使用する場合は、カスタム値ファイルのプロパティを次のように設定してください。Scalar 製品を選択して、カスタム値ファイルでプロパティを設定する方法を確認します。 + + + + ```yaml + scalardbCluster: + scalardbClusterNodeProperties: | + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem= + ``` + + + ```yaml + ledger: + ledgerProperties: | + scalar.dl.licensing.license_key= + scalar.dl.licensing.license_check_cert_pem= + ``` + + + ```yaml + auditor: + auditorProperties: | + scalar.dl.licensing.license_key= + scalar.dl.licensing.license_check_cert_pem= + ``` + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/K8sLogCollectionGuide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/K8sLogCollectionGuide.mdx new file mode 100644 index 00000000..0ca21c3d --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/K8sLogCollectionGuide.mdx @@ -0,0 +1,186 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes クラスター上の Scalar 製品からのログの収集 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Helm を使用して Grafana Loki と Promtail を Kubernetes にデプロイする方法について説明します。このドキュメントに従うと、Kubernetes 環境で Scalar 製品のログを収集できます。 + +マネージド Kubernetes クラスターを使用しており、監視とログ記録にクラウドサービス機能を使用したい場合は、次のドキュメントを参照してください。 + +* [Logging and monitoring on Amazon EKS](https://docs.aws.amazon.com/prescriptive-guidance/latest/implementing-logging-monitoring-cloudwatch/amazon-eks-logging-monitoring.html) +* [Monitoring Azure Kubernetes Service (AKS) with Azure Monitor](https://learn.microsoft.com/en-us/azure/aks/monitor-aks) + +## 前提条件 + +* Kubernetes クラスターを作成します。 + * [Scalar 製品用の EKS クラスターを作成する](CreateEKSClusterForScalarProducts.mdx) + * [Scalar 製品用の AKS クラスターを作成する](CreateAKSClusterForScalarProducts.mdx) +* 踏み台サーバーを作成し、`kubeconfig` を設定します。 + * [踏み台サーバーの作成](CreateBastionServer.mdx) +* Prometheus Operator をデプロイします (収集されたログを調査するために Grafana を使用します) + * [Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx) + +## Grafana helm リポジトリを追加します + +このドキュメントでは、Prometheus Operator のデプロイメントに Helm を使用します。 + +```console +helm repo add grafana https://grafana.github.io/helm-charts +``` +```console +helm repo update +``` + +## カスタム値ファイルを準備する + +loki-stack のサンプルファイル [scalar-loki-stack-custom-values.yaml](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalar-loki-stack-custom-values.yaml) を入手してください。Scalar 製品のロギングには、このサンプルファイルの構成をお勧めします。 + +### カスタム値ファイルで nodeSelector を設定する (オプション) + +Kubernetes ワーカーノードにラベルを追加している場合は、次のようにカスタム値ファイル (scalar-loki-stack-custom-values.yaml) で nodeSelector を設定する必要がある場合があります。使用している製品に応じて、次の例を参照してください。 + + + + 使用している ScalarDB 製品を選択します。 + + + ```yaml + promtail: + nodeSelector: + scalar-labs.com/dedicated-node: scalardb-cluster + ``` + + + ```yaml + promtail: + nodeSelector: + scalar-labs.com/dedicated-node: scalardb + ``` + + + + + 使用している ScalarDL 製品を選択します。 + + + ```yaml + promtail: + nodeSelector: + scalar-labs.com/dedicated-node: scalardl-ledger + ``` + + + ```yaml + promtail: + nodeSelector: + scalar-labs.com/dedicated-node: scalardl-auditor + ``` + + + + + +### カスタム値ファイルで許容値を設定する (オプション) + +Kubernetes ワーカーノードにテイントを追加している場合は、次のようにカスタム値ファイル (scalar-loki-stack-custom-values.yaml) で許容値を設定する必要がある場合があります。使用している製品に応じて、次の例を参照してください。 + + + + 使用している ScalarDB 製品を選択します。 + + + ```yaml + promtail: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb-cluster + ``` + + + ```yaml + promtail: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb + ``` + + + + + 使用している ScalarDL 製品を選択します。 + + + ```yaml + promtail: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardl-ledger + ``` + + + ```yaml + promtail: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardl-auditor + ``` + + + + + +## Loki と Promtail をデプロイする + +Loki と Promtail は、Prometheus や Grafana と同じ名前空間 `Monitoring` にデプロイすることをお勧めします。`Monitoring` 名前空間は、ドキュメント [Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)ですでに作成済みです。 + +```console +helm install scalar-logging-loki grafana/loki-stack -n monitoring -f scalar-loki-stack-custom-values.yaml +``` + +## Loki と Promtail がデプロイされているかどうかを確認する + +Loki および Promtail ポッドが適切にデプロイされている場合は、次のコマンドを使用して、`STATUS` が `Running` であることが確認できます。promtail ポッドは DaemonSet としてデプロイされるため、promtail ポッドの数は Kubernetes ノードの数によって異なります。次の例では、Kubernetes クラスター内に Scalar 製品のワーカーノードが3つあります。 + +```console +kubectl get pod -n monitoring +``` + +次のような結果が表示されます: + +```console +NAME READY STATUS RESTARTS AGE +scalar-logging-loki-0 1/1 Running 0 35m +scalar-logging-loki-promtail-2fnzn 1/1 Running 0 32m +scalar-logging-loki-promtail-2pwkx 1/1 Running 0 30m +scalar-logging-loki-promtail-gfx44 1/1 Running 0 32m +``` + +## Grafana ダッシュボードでログを表示する + +収集されたログは、次のように Grafana ダッシュボードで確認できます。 + +1. Grafana ダッシュボードにアクセスします。 +1. `Explore` ページに移動します。 +1. 左上のプルダウンから `Loki` を選択します。 +1. ログを問い合わせる条件を設定する。 +1. 右上の `Run query` ボタンを選択します。 + +Grafana ダッシュボードへのアクセス方法の詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/K8sMonitorGuide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/K8sMonitorGuide.mdx new file mode 100644 index 00000000..69faf426 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/K8sMonitorGuide.mdx @@ -0,0 +1,160 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes クラスター上の Scalar 製品の監視 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、Helm を使用して Prometheus Operator を Kubernetes にデプロイする方法について説明します。このドキュメントに従うと、Prometheus、Alertmanager、および Grafana を使用して、Kubernetes 環境上の Scalar 製品を監視できるようになります。 + +マネージド Kubernetes クラスターを使用しており、監視とログ記録にクラウドサービス機能を使用したい場合は、次のドキュメントを参照してください。 + +* [Logging and monitoring on Amazon EKS](https://docs.aws.amazon.com/prescriptive-guidance/latest/implementing-logging-monitoring-cloudwatch/amazon-eks-logging-monitoring.html) +* [Monitoring Azure Kubernetes Service (AKS) with Azure Monitor](https://learn.microsoft.com/en-us/azure/aks/monitor-aks) + +## 前提条件 + +* Kubernetes クラスターを作成します。 + * [Scalar 製品用の EKS クラスターを作成する](CreateEKSClusterForScalarProducts.mdx) + * [Scalar 製品用の AKS クラスターを作成する](CreateAKSClusterForScalarProducts.mdx) +* 踏み台サーバーを作成し、`kubeconfig`を設定します。 + * [踏み台サーバーの作成](CreateBastionServer.mdx) + +## prometheus-community helm リポジトリを追加します + +このドキュメントでは、Prometheus Operator のデプロイメントに Helm を使用します。 + +```console +helm repo add prometheus-community https://prometheus-community.github.io/helm-charts +``` +```console +helm repo update +``` + +## カスタム値ファイルを準備する + +kube-prometheus-stack のサンプルファイル [scalar-prometheus-custom-values.yaml](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalar-prometheus-custom-values.yaml) を取得してください。Scalar 製品の監視には、このサンプルファイルの構成をお勧めします。 + +このサンプルファイルでは、サービスリソースは Kubernetes クラスターの外部からのアクセスに公開されていません。Kubernetes クラスターの外部からダッシュボードにアクセスしたい場合は、`*.service.type` を `LoadBalancer` に設定するか、`*.ingress.enabled` を `true` に設定する必要があります。 + +kube-prometheus-stackの設定の詳細については、以下の公式ドキュメントを参照してください。 + +* [kube-prometheus-stack - Configuration](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack#configuration) + +## Prometheus Operator をデプロイする + +Scalar 製品は、Prometheus Operator がデフォルトで `monitoring` 名前空間にデプロイされていることを前提としています。したがって、`monitoring` 名前空間を作成し、`monitoring` 名前空間に Prometheus Operator をデプロイしてください。 + +1. Kubernetes 上に名前空間 `monitoring` を作成します。 + ```console + kubectl create namespace monitoring + ``` + +1. kube-prometheus-stack をデプロイします。 + ```console + helm install scalar-monitoring prometheus-community/kube-prometheus-stack -n monitoring -f scalar-prometheus-custom-values.yaml + ``` + +## Prometheus Operator がデプロイされているかどうかを確認する + +Prometheus Operator (Prometheus、Alertmanager、Grafana を含む) ポッドが適切にデプロイされている場合は、次のコマンドを使用して `STATUS` が `Running` であることを確認できます。 + +```console +kubectl get pod -n monitoring +``` + +次のような結果が表示されます: + +```console +NAME READY STATUS RESTARTS AGE +alertmanager-scalar-monitoring-kube-pro-alertmanager-0 2/2 Running 0 55s +prometheus-scalar-monitoring-kube-pro-prometheus-0 2/2 Running 0 55s +scalar-monitoring-grafana-cb4f9f86b-jmkpz 3/3 Running 0 62s +scalar-monitoring-kube-pro-operator-865bbb8454-9ppkc 1/1 Running 0 62s +``` + +## Helm Chart を使用して Scalar 製品をデプロイ (またはアップグレード) + +1. Scalar 製品の Prometheus 監視を有効にするには、カスタム値ファイルの次の構成に `true` を設定する必要があります。 + + * 構成 + * `*.prometheusRule.enabled` + * `*.grafanaDashboard.enabled` + * `*.serviceMonitor.enabled` + + 各Scalar製品のカスタム値ファイルの詳細については、以下のドキュメントを参照してください。 + + * [ScalarDB Cluster](../helm-charts/configure-custom-values-scalardb-cluster.mdx#prometheus-および-grafana-構成-実稼働環境で推奨) + * [(Deprecated) ScalarDB Server](../helm-charts/configure-custom-values-scalardb.mdx#prometheusgrafana-構成-運用環境で推奨) + * [(Deprecated) ScalarDB GraphQL](../helm-charts/configure-custom-values-scalardb-graphql.mdx#prometheusgrafana-構成-運用環境で推奨) + * [ScalarDL Ledger](../helm-charts/configure-custom-values-scalardl-ledger.mdx#prometheusgrafana-構成-運用環境で推奨) + * [ScalarDL Auditor](../helm-charts/configure-custom-values-scalardl-auditor.mdx#prometheusgrafana-構成-運用環境で推奨) + +1. 上記のカスタム値ファイルを含む Helm Chart を使用して、Scalar 製品をデプロイ (またはアップグレード) します。 + + Scalar 製品の導入/アップグレード方法の詳細については、次のドキュメントを参照してください。 + + * [ScalarDB Cluster](../helm-charts/how-to-deploy-scalardb-cluster.mdx) + * [(Deprecated) ScalarDB Server](../helm-charts/how-to-deploy-scalardb.mdx) + * [(Deprecated) ScalarDB GraphQL](../helm-charts/how-to-deploy-scalardb-graphql.mdx) + * [ScalarDL Ledger](../helm-charts/how-to-deploy-scalardl-ledger.mdx) + * [ScalarDL Auditor](../helm-charts/how-to-deploy-scalardl-auditor.mdx) + +## ダッシュボードにアクセスする方法 + +`*.service.type` を `LoadBalancer` に設定するか、`*.ingress.enabled` を `true` に設定すると、Kubernetes の Service または Ingress 経由でダッシュボードにアクセスできます。具体的な実装とアクセス方法はKubernetesクラスタに依存します。マネージド Kubernetes クラスターを使用する場合、詳細についてはクラウドプロバイダーの公式ドキュメントを参照してください。 + +* EKS + * [Network load balancing on Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/network-load-balancing.html) + * [Application load balancing on Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/alb-ingress.html) +* AKS + * [Use a public standard load balancer in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/load-balancer-standard) + * [Create an ingress controller in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/ingress-basic) + +## ローカルマシンからダッシュボードにアクセスします (テスト目的のみ / 運用環境では推奨されません) + +`kubectl port-forward` コマンドを使用して、ローカルマシンから各ダッシュボードにアクセスできます。 + +1. ローカルマシンから各サービスへのポート転送。 + * Prometheus + ```console + kubectl port-forward -n monitoring svc/scalar-monitoring-kube-pro-prometheus 9090:9090 + ``` + * Alertmanager + ```console + kubectl port-forward -n monitoring svc/scalar-monitoring-kube-pro-alertmanager 9093:9093 + ``` + * Grafana + ```console + kubectl port-forward -n monitoring svc/scalar-monitoring-grafana 3000:3000 + ``` + +1. 各ダッシュボードにアクセスします。 + * Prometheus + ```console + http://localhost:9090/ + ``` + * Alertmanager + ```console + http://localhost:9093/ + ``` + * Grafana + ```console + http://localhost:3000/ + ``` + * 注記: + * Grafanaのユーザーとパスワードは以下で確認できます。 + * ユーザー + ```console + kubectl get secrets scalar-monitoring-grafana -n monitoring -o jsonpath='{.data.admin-user}' | base64 -d + ``` + * パスワード + ```console + kubectl get secrets scalar-monitoring-grafana -n monitoring -o jsonpath='{.data.admin-password}' | base64 -d + ``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS.mdx new file mode 100644 index 00000000..abf62867 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS.mdx @@ -0,0 +1,70 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Amazon Elastic Kubernetes Service (EKS) に ScalarDB Cluster をデプロイする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB Cluster を Amazon Elastic Kubernetes Service (EKS) にデプロイする方法について説明します。 + +このガイドでは、AWS 環境に次の2つの環境のいずれかを作成します。環境は、使用する [client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#client-modes) によって異なります。 + +* **[`direct-kubernetes` client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#direct-kubernetes-client-mode).** このモードでは、ScalarDB Cluster のデプロイメントと同じ EKS クラスターにアプリケーションをデプロイします。 + + ![image](./images/png/EKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png) + +* **[`indirect` client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#indirect-client-mode).** このモードでは、ScalarDB Cluster のデプロイメントを含む EKS クラスターとは異なる環境にアプリケーションをデプロイします。 + + ![image](./images/png/EKS_ScalarDB_Cluster_Indirect_Mode.drawio.png) + +## ステップ1. AWS Marketplace で ScalarDB Cluster にサブスクライブする + +ScalarDB Cluster コンテナイメージを取得するには、AWS Marketplace にアクセスし、[ScalarDB Cluster Standard Edition (Pay-As-You-Go)](https://aws.amazon.com/marketplace/pp/prodview-jx6qxatkxuwm4) または [ScalarDB Cluster Premium Edition (Pay-As-You-Go)](https://aws.amazon.com/marketplace/pp/prodview-djqw3zk6dwyk6) をサブスクライブする必要があります。AWS Marketplace で ScalarDB Cluster をサブスクライブする方法の詳細については、[AWS Marketplace から Scalar 製品を購読する](AwsMarketplaceGuide.mdx#aws-marketplace-から-scalar-製品を購読する)を参照してください。 + +## ステップ2. EKS クラスターを作成する + +ScalarDB Cluster のデプロイメント用の EKS クラスターを作成する必要があります。詳細については、[Scalar 製品用の Amazon EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarProducts.mdx)を参照してください。 + +## ステップ3. ScalarDB Cluster のデータベースをセットアップする + +ScalarDB Cluster をデプロイする前にデータベースを準備する必要があります。ScalarDB がサポートするデータベースのタイプを確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[AWS での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAWS.mdx)を参照してください。 + +## ステップ4. 踏み台サーバーを作成する + +EKS 上で ScalarDB Cluster をデプロイおよび管理するためのいくつかのツールを実行するには、**ステップ2**で作成した EKS クラスターの同じ Amazon Virtual Private Cloud (VPC) 内に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ5. Scalar Helm Chart のカスタム値ファイルを準備する + +**ステップ3**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDB Cluster の Scalar Helm Chart のカスタム値ファイルを構成する必要があります。詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + +**注意:** ScalarDB Cluster がデプロイされている EKS クラスターとは異なる環境にアプリケーションをデプロイする場合 (つまり、`indirect` クライアントモードを使用する場合)、`envoy.enabled` パラメーターを次のように設定する必要があります。アプリケーションから Scalar Envoy にアクセスするには、`true` と `envoy.service.type` パラメータを `LoadBalancer` に設定します。 + +## ステップ6. Scalar Helm Chart を使用して ScalarDB Cluster をデプロイする + +ScalarDB Cluster の Helm Chart を使用して、EKS クラスターに ScalarDB Cluster をデプロイします。詳細については、[Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注意:** `kubectl create ns scalardb-cluster` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardb-cluster` オプションを使用して名前空間に ScalarDB Cluster をデプロイすることをお勧めします。 + +## ステップ7. ScalarDB Cluster のデプロイメントのステータスを確認する + +EKS クラスターに ScalarDB Cluster をデプロイした後、各コンポーネントのステータスを確認する必要があります。詳細については、[Kubernetes 環境で実行するときに定期的に確認するコンポーネント](./ RegularCheck.mdx) を参照してください。 + +## ステップ8. ScalarDB Cluster のデプロイメントを監視する + +EKS クラスターに ScalarDB Cluster をデプロイした後、特に本番環境では、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## ステップ9. アプリケーションをデプロイする + +[`direct-kubernetes` client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#direct-kubernetes-client-mode) を使用する場合は、追加の Kubernetes リソースをデプロイする必要があります。詳細については、[Deploy your client application on Kubernetes with `direct-kubernetes` mode](../helm-charts/how-to-deploy-scalardb-cluster.mdx#direct-kubernetes-モードを使用してクライアント-アプリケーションを-kubernetes-にデプロイします) を参照してください。 + +## EKS から ScalarDB Cluster を削除 + +作成した環境を削除する場合は、作成時とは逆の順序ですべてのリソースを削除してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnAKS.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnAKS.mdx new file mode 100644 index 00000000..6d195871 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnAKS.mdx @@ -0,0 +1,67 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsJapanese +--- + +# [非推奨] Azure Kubernetes Service (AKS) に ScalarDB Server をデプロイする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB Server を Azure Kubernetes Service (AKS) にデプロイする方法について説明します。 + +このガイドでは、Azure 環境に次の2つの環境のいずれかを作成します。2つの環境の違いは、アプリケーションのデプロイをどのように計画するかです。 + +* アプリケーションを ScalarDB Server デプロイメントと同じ AKS クラスターにデプロイします。この場合、アプリケーションから Scalar Envoy にアクセスするために Azure が提供するロードバランサーを使用する必要はありません。 + + ![image](./images/png/AKS_ScalarDB_Server_App_In_Cluster.drawio.png) + +* ScalarDB Server デプロイを含む AKS クラスターとは異なる環境にアプリケーションをデプロイします。この場合、アプリケーションから Scalar Envoy にアクセスするには、Azure が提供するロードバランサーを使用する必要があります。 + + ![image](./images/png/AKS_ScalarDB_Server_App_Out_Cluster.drawio.png) + +## ステップ1. Azure Marketplace で ScalarDB Server にサブスクライブする + +[Azure Marketplace](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) にアクセスし、ScalarDB Server をサブスクライブして、ScalarDB Server コンテナーイメージを取得する必要があります。Azure Marketplace で ScalarDB Server をサブスクライブする方法の詳細については、[Microsoft Azure Marketplace から Scalar 製品を入手する](AzureMarketplaceGuide.mdx#microsoft-azure-marketplace-から-scalar-製品を入手する)を参照してください。 + +## ステップ2. AKS クラスターを作成する + +ScalarDB Server デプロイ用の AKS クラスターを作成する必要があります。詳細については、[Scalar 製品用の AKS クラスターを作成するためのガイドライン](CreateAKSClusterForScalarProducts.mdx)を参照してください。 + +## ステップ3. ScalarDB Server のデータベースをセットアップする + +ScalarDB Server を展開する前にデータベースを準備する必要があります。ScalarDB がサポートするデータベースのタイプを確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[Azure での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAzure.mdx)を参照してください。 + +## ステップ4. 踏み台サーバーを作成する + +AKS 上で ScalarDB Server をデプロイおよび管理するためのいくつかのツールを実行するには、**手順2**で作成した AKS クラスターの同じ Azure Virtual Networks (VNet) 内に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ5. Scalar Helm Chart のカスタム値ファイルを準備する + +**ステップ3**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDB Server の Scalar Helm Chart のカスタム値ファイルを構成する必要があります。詳細については、[Configure a custom values file of Scalar Helm Chart](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + +**注:** ScalarDB Server がデプロイされている AKS クラスターとは異なる環境にアプリケーションをデプロイする場合、Scalar Envoy にアクセスするには、`envoy.service.type` パラメーターを `LoadBalancer` に設定する必要があります。応用。 + +## ステップ6. Scalar Helm Chart を使用して ScalarDB Server をデプロイする + +ScalarDB Server の Helm Chart を使用して、AKS クラスターに ScalarDB Server をデプロイします。詳細については、[Deploy Scalar Products using Scalar Helm Chart](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注意:** `kubectl create ns scalardb` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardb` オプションを使用して名前空間に ScalarDB Server をデプロイすることをお勧めします。 + +## ステップ7. ScalarDB Server デプロイメントのステータスを確認する + +ScalarDB Server を AKS クラスターにデプロイした後、各コンポーネントの状態を確認する必要があります。詳細については、[Kubernetes 環境で実行する場合に定期的に確認するコンポーネント](RegularCheck.mdx)を参照してください。 + +## ステップ8. ScalarDB Server の展開を監視する + +ScalarDB Server を AKS クラスターにデプロイした後、特に運用環境では、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## ScalarDB Server を AKS から削除します + +作成した環境を削除する場合は、作成時とは逆の順序ですべてのリソースを削除してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnEKS.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnEKS.mdx new file mode 100644 index 00000000..92c7f178 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnEKS.mdx @@ -0,0 +1,67 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsJapanese +--- + +# ScalarDB Server を Amazon Elastic Kubernetes Service (EKS) にデプロイする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、Amazon Elastic Kubernetes Service (EKS) に ScalarDB Server をデプロイする方法について説明します。 + +このガイドでは、AWS 環境に次の2つの環境のいずれかを作成します。2つの環境の違いは、アプリケーションのデプロイをどのように計画するかです。 + +* アプリケーションを ScalarDB Server デプロイメントと同じ EKS クラスターにデプロイします。この場合、アプリケーションから Scalar Envoy にアクセスするために AWS が提供するロードバランサーを使用する必要はありません。 + + ![image](./images/png/EKS_ScalarDB_Server_App_In_Cluster.drawio.png) + +* ScalarDB Server デプロイメントを含む EKS クラスターとは異なる環境にアプリケーションをデプロイします。この場合、アプリケーションから Scalar Envoy にアクセスするには、AWS が提供するロードバランサーを使用する必要があります。 + + ![image](./images/png/EKS_ScalarDB_Server_App_Out_Cluster.drawio.png) + +## ステップ1. AWS Marketplace で ScalarDB Server にサブスクライブする + +[AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-rzbuhxgvqf4d2) にアクセスし、ScalarDB Server をサブスクライブして、ScalarDB Server コンテナイメージを取得する必要があります。AWS Marketplace で ScalarDB Server をサブスクライブする方法の詳細については、[AWS Marketplace から Scalar 製品を購読する](AwsMarketplaceGuide.mdx#aws-marketplace-から-scalar-製品を購読する)を参照してください。 + +## ステップ2. EKS クラスターを作成する + +ScalarDB Server デプロイメント用の EKS クラスターを作成する必要があります。詳細については、[Scalar 製品用の Amazon EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarProducts.mdx) を参照してください。 + +## ステップ3. ScalarDB Server のデータベースをセットアップする + +ScalarDB Server を展開する前にデータベースを準備する必要があります。ScalarDB がサポートするデータベースのタイプを確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[AWS での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAWS.mdx)を参照してください。 + +## ステップ4. 踏み台サーバーを作成する + +EKS 上で ScalarDB Server をデプロイおよび管理するためのいくつかのツールを実行するには、**ステップ2**で作成した EKS クラスターの同じ Amazon Virtual Private Cloud (VPC) 内に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ5. Scalar Helm Chartのカスタム値ファイルを準備する + +**ステップ3**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDB Server の Scalar Helm Chartのカスタム値ファイルを構成する必要があります。詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + +**注意:** ScalarDB Server がデプロイされている EKS クラスターとは異なる環境にアプリケーションをデプロイする場合は、`envoy.service.type` パラメーターを `LoadBalancer` に設定して、ユーザーから Scalar Envoy にアクセスする必要があります。応用。 + +## ステップ6. Scalar Helm Chart を使用して ScalarDB Server をデプロイする + +ScalarDB Server の Helm Chart を使用して、ScalarDB Server を EKS クラスターにデプロイします。詳細については、[Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注意:** `kubectl create ns scalardb` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardb` オプションを使用して名前空間に ScalarDB Server をデプロイすることをお勧めします。 + +## ステップ7. ScalarDB Server デプロイメントのステータスを確認する + +EKS クラスターに ScalarDB Server をデプロイした後、各コンポーネントのステータスを確認する必要があります。詳細については、[Kubernetes環境で実行する場合に定期的に確認するコンポーネント](RegularCheck.mdx)を参照してください。 + +## ステップ8. ScalarDB Server の展開を監視する + +EKS クラスターに ScalarDB Server をデプロイした後、特に本番環境では、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## ScalarDB Server を EKS から削除する + +作成した環境を削除する場合は、作成時とは逆の順序ですべてのリソースを削除してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnAKS.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnAKS.mdx new file mode 100644 index 00000000..62e83d6a --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnAKS.mdx @@ -0,0 +1,105 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger と ScalarDL Auditor を Azure Kubernetes Service (AKS) にデプロイする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、Azure Kubernetes Service (AKS) に ScalarDL Ledger と ScalarDL Auditor をデプロイする方法について説明します。 + +このガイドでは、Azure 環境に次の3つの環境のいずれかを作成します。ビザンチン障害検出を適切に機能させるには、ScalarDL Ledger と ScalarDL Auditor を異なる管理ドメイン (つまり、別の環境) に展開することをお勧めします。 + +* 別の Azure アカウントを使用する (最も推奨される方法) + + ![image](./images/png/AKS_ScalarDL_Auditor_Multi_Account.drawio.png) + +* 別の Azure Virtual Networks (VNet) を使用する (2番目に推奨される方法) + + ![image](./images/png/AKS_ScalarDL_Auditor_Multi_VNet.drawio.png) + +* 異なる名前空間を使用する (3番目に推奨される方法) + + ![image](./images/png/AKS_ScalarDL_Auditor_Multi_Namespace.drawio.png) + +**注意:** このガイドは、2番目に推奨される方法「別の VNet を使用する」に従います。 + +## ステップ1. ScalarDL Ledger および ScalarDL Auditor コンテナーイメージを取得する + +ScalarDL Ledger および ScalarDL Auditor コンテナーイメージを取得する必要があります。Scalar 製品のコンテナリポジトリの詳細については、[Scalar 製品のコンテナイメージを取得する方法](HowToGetContainerImages.mdx)を参照してください。 + +## ステップ2. ScalarDL Ledger の AKS クラスターを作成する + +ScalarDL Ledger デプロイ用の AKS クラスターを作成する必要があります。詳細については、[Scalar 製品用の AKS クラスターを作成するためのガイドライン](CreateAKSClusterForScalarProducts.mdx)を参照してください。 + +## ステップ3. ScalarDL Auditor の AKS クラスターを作成する + +ScalarDL Auditor デプロイ用の AKS クラスターも作成する必要があります。詳細については、[Scalar 製品用の AKS クラスターを作成するためのガイドライン](CreateAKSClusterForScalarProducts.mdx)を参照してください。 + +## ステップ4. ScalarDL Ledger のデータベースをセットアップする + +ScalarDL Ledger を展開する前にデータベースを準備する必要があります。ScalarDL Ledger は内部で ScalarDB を使用してデータベースにアクセスするため、ScalarDB がサポートするデータベースの種類を確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[Azure での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAzure.mdx)を参照してください。 + +## ステップ5. ScalarDL Auditor のデータベースをセットアップする + +ScalarDL Auditor を展開する前にデータベースを準備する必要もあります。ScalarDL Auditor は内部で ScalarDB を使用してデータベースにアクセスするため、ScalarDB がサポートするデータベースの種類を確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[Azure での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAzure.mdx)を参照してください。 + +## ステップ6. ScalarDL Ledger の踏み台サーバーを作成する + +AKS で ScalarDL Ledger をデプロイおよび管理するためのいくつかのツールを実行するには、**手順2**で作成した AKS クラスターの同じ VNet に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ7. ScalarDL Auditor の踏み台サーバーを作成する + +AKS で ScalarDL Auditor をデプロイおよび管理するためのいくつかのツールを実行するには、**手順3**で作成した AKS クラスターの同じ VNet に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ8. 2つの AKS クラスター間のネットワークピアリングを作成する + +ScalarDL を適切に動作させるには、ScalarDL Ledger と ScalarDL Auditor が相互に接続する必要があります。[仮想ネットワークピアリング](https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview)を使用して2つの VNet を接続する必要があります。詳細については、[ScalarDL Auditor モードのネットワークピアリングの構成](NetworkPeeringForScalarDLAuditor.mdx)を参照してください。 + +## ステップ9. ScalarDL Ledger と ScalarDL Schema Loader の両方の Scalar Helm Chart のカスタム値ファイルを準備する + +**ステップ4**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDL Ledger と ScalarDL Schema Loader (Ledger 用) の両方の Scalar Helm Chart のカスタム値ファイルを構成する必要があります。詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx を参照してください。 + +## ステップ10. Scalar Helm Chart を使用して ScalarDL Ledger をデプロイする + +ScalarDL Ledger の Helm Chart を使用して、ScalarDL Ledger を AKS クラスターにデプロイします。詳細については、[Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注意:** `kubectl create ns scalardl-ledger` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardl-ledger` オプションを使用して名前空間に ScalarDL Ledger をデプロイすることをお勧めします。 + +## ステップ11. ScalarDL Auditor と ScalarDL Schema Loader の両方の Scalar Helm Chart のカスタム値ファイルを準備する + +**ステップ5**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDL Auditor と ScalarDL Schema Loader (Auditor 用) の両方の Scalar Helm Chart のカスタム値ファイルを構成する必要もあります 。詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + +## ステップ12. Scalar Helm Chart を使用して ScalarDL Auditor をデプロイする + +ScalarDL Auditor の Helm Chart を使用して、AKS クラスターに ScalarDL Auditor をデプロイします。詳細については、[Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注意:** `kubectl create ns scalardl-auditor` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardl-auditor` オプションを使用して名前空間に ScalarDL Auditor をデプロイすることをお勧めします。 + +## ステップ13. ScalarDL Ledger 導入のステータスを確認する + +ScalarDL Ledger を AKS クラスターにデプロイした後、各コンポーネントの状態を確認する必要があります。詳細については、[Kubernetes環境で実行する場合に定期的に確認するコンポーネント](RegularCheck.mdx)を参照してください。 + +## ステップ14. ScalarDL Auditor デプロイメントのステータスを確認する + +ScalarDL Auditor を AKS クラスターにデプロイした後、各コンポーネントの状態を確認する必要があります。詳細については、[Kubernetes環境で実行する場合に定期的に確認するコンポーネント](RegularCheck.mdx)を参照してください。 + +## ステップ15. ScalarDL Ledger の展開を監視する + +AKS クラスターに ScalarDL Ledger をデプロイした後、特に運用環境では、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## ステップ16. ScalarDL Auditor の展開を監視する + +AKS クラスターに ScalarDL Auditor をデプロイした後、特に運用環境では、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](./K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## ScalarDL Ledger と ScalarDL Auditor を AKS から削除します + +作成した環境を削除する場合は、作成時とは逆の順序ですべてのリソースを削除してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnEKS.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnEKS.mdx new file mode 100644 index 00000000..3b0d498d --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnEKS.mdx @@ -0,0 +1,105 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger と ScalarDL Auditor を Amazon Elastic Kubernetes Service (EKS) にデプロイする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDL Ledger と ScalarDL Auditor を Amazon Elastic Kubernetes Service (EKS) にデプロイする方法について説明します。 + +このガイドでは、AWS 環境に次の3つの環境のいずれかを作成します。ビザンチン障害検出を適切に機能させるには、ScalarDL Ledger と ScalarDL Auditor を異なる管理ドメイン (つまり、別の環境) に展開することをお勧めします。 + +* 別の AWS アカウントを使用する (最も推奨される方法) + + ![image](./images/png/EKS_ScalarDL_Auditor_Multi_Account.drawio.png) + +* 異なる Amazon Virtual Private Cloud (VPC) を使用する (2番目に推奨される方法) + + ![image](./images/png/EKS_ScalarDL_Auditor_Multi_VPC.drawio.png) + +* 異なる名前空間を使用する (3番目に推奨される方法) + + ![image](./images/png/EKS_ScalarDL_Auditor_Multi_Namespace.drawio.png) + +**注記:** このガイドは、2番目に推奨される方法「別の VPC を使用する」に従います。 + +## ステップ1. AWS Marketplace で ScalarDL Ledger と ScalarDL Auditor を購読する + +[AWS Marketplace](https://aws.amazon.com/marketplace/seller-profile?id=bd4cd7de-49cd-433f-97ba-5cf71d76ec7b) から ScalarDL Ledger および ScalarDL Auditor コンテナイメージを取得し、ScalarDL Ledger および ScalarDL Auditor をサブスクライブする必要があります。AWS Marketplace で ScalarDL Ledger および ScalarDL Auditor を購読する方法の詳細については、[AWS Marketplace から Scalar 製品を購読する](AwsMarketplaceGuide.mdx#aws-marketplace-から-scalar-製品を購読する)を参照してください。 + +## ステップ2. ScalarDL Ledger の EKS クラスターを作成する + +ScalarDL Ledger デプロイメント用の EKS クラスターを作成する必要があります。詳細については、[Scalar 製品用の Amazon EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarProducts.mdx)を参照してください。 + +## ステップ3. ScalarDL Auditor 用の EKS クラスターを作成する + +ScalarDL Auditor デプロイメント用の EKS クラスターも作成する必要があります。詳細については、[Scalar 製品用の Amazon EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarProducts.mdx)を参照してください。 + +## ステップ4. ScalarDL Ledger のデータベースをセットアップする + +ScalarDL Ledger を展開する前にデータベースを準備する必要があります。ScalarDL Ledger は内部で ScalarDB を使用してデータベースにアクセスするため、ScalarDB がサポートするデータベースの種類を確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[AWS での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAWS.mdx)を参照してください。 + +## ステップ5. ScalarDL Auditor のデータベースをセットアップする + +ScalarDL Auditor を展開する前にデータベースを準備する必要もあります。ScalarDL Auditor は内部で ScalarDB を使用してデータベースにアクセスするため、ScalarDB がサポートするデータベースの種類を確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[AWS での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAWS.mdx)を参照してください。 + +## ステップ6. ScalarDL Ledger の踏み台サーバーを作成する + +EKS 上で ScalarDL Ledger をデプロイおよび管理するためのいくつかのツールを実行するには、**ステップ2**で作成した EKS クラスターの同じ VPC 内に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ7. ScalarDL Auditor の踏み台サーバーを作成する + +EKS 上で ScalarDL Auditor をデプロイおよび管理するためのいくつかのツールを実行するには、**ステップ3**で作成した EKS クラスターの同じ VPC 内に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ8. 2つの EKS クラスター間のネットワークピアリングを作成する + +ScalarDL を適切に動作させるには、ScalarDL Ledger と ScalarDL Auditor が相互に接続する必要があります。[VPC peering](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html) を使用して2つの VPC を接続する必要があります。詳細については、[ScalarDL Auditor モードのネットワークピアリングの構成](NetworkPeeringForScalarDLAuditor.mdx)を参照してください。 + +## ステップ9. ScalarDL Ledger および ScalarDL Schema Loader の Scalar Helm Chart のカスタム値ファイルを準備する + +**ステップ4**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDL Ledger および ScalarDL Schema Loader (Ledger 用) の Scalar Helm Chart のカスタム値ファイルを構成する必要があります。詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + +## ステップ10. Scalar Helm Chart を使用して ScalarDL Ledger をデプロイする + +ScalarDL Ledger の Helm Chart を使用して、ScalarDL Ledger を EKS クラスターにデプロイします。詳細については、[Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注記:** `kubectl create ns scalardl-ledger` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardl-ledger` オプションを使用して名前空間に ScalarDL Ledger をデプロイすることをお勧めします。 + +## ステップ11. ScalarDL Auditor と ScalarDL Schema Loader の両方の Scalar Helm Chart のカスタム値ファイルを準備する + +**ステップ5**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDL Auditor と ScalarDL Schema Loader (Auditor 用) の両方の Scalar Helm Chart のカスタム値ファイルを構成する必要があります。詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + +## ステップ12. Scalar Helm Chart を使用して ScalarDL Auditor をデプロイする + +ScalarDL Auditor の Helm Chart を使用して、ScalarDL Auditor を EKS クラスターにデプロイします。詳細については、[Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注記:** `kubectl create ns scalardl-auditor` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardl-auditor` オプションを使用して名前空間に ScalarDL Auditor をデプロイすることをお勧めします。 + +## ステップ13. ScalarDL Ledger 導入のステータスを確認する + +EKS クラスターに ScalarDL Ledger をデプロイした後、各コンポーネントのステータスを確認する必要があります。詳細については、[Kubernetes環境で実行する場合に定期的に確認するコンポーネント](RegularCheck.mdx)を参照してください。 + +## ステップ14. ScalarDL Auditor デプロイメントのステータスを確認する + +EKS クラスターに ScalarDL Auditor をデプロイした後、各コンポーネントのステータスを確認する必要があります。詳細については、[Kubernetes 環境で実行するときに定期的に確認するコンポーネント](RegularCheck.mdx)を参照してください。 + +## ステップ15. ScalarDL Ledger の展開を監視する + +EKS クラスターに ScalarDL Ledger をデプロイした後、特に本番環境では、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## ステップ16. ScalarDL Auditor の展開を監視する + +EKS クラスターに ScalarDL Auditor をデプロイした後、特に運用環境で、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## EKS から ScalarDL Ledger と ScalarDL Auditor を削除 + +作成した環境を削除する場合は、作成時とは逆の順序ですべてのリソースを削除してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnAKS.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnAKS.mdx new file mode 100644 index 00000000..c9dab5a1 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnAKS.mdx @@ -0,0 +1,57 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# Azure Kubernetes Service (AKS) に ScalarDL Ledger をデプロイする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、**ScalarDL Ledger** を Azure Kubernetes Service (AKS) にデプロイする方法について説明します。 + +このガイドでは、Azure 環境に次の環境を作成します。 + +![image](./images/png/AKS_ScalarDL_Ledger.drawio.png) + +## ステップ1. ScalarDL Ledger コンテナーイメージを取得する + +ScalarDL Ledger コンテナーイメージを取得する必要があります。Scalar 製品のコンテナリポジトリの詳細については、[Scalar 製品のコンテナイメージを取得する方法](HowToGetContainerImages.mdx)を参照してください。 + +## ステップ2. AKS クラスターを作成する + +ScalarDL Ledger デプロイ用の AKS クラスターを作成する必要があります。詳細については、[Scalar 製品用の AKS クラスターを作成するためのガイドライン](CreateAKSClusterForScalarProducts.mdx)を参照してください。 + +## ステップ3. ScalarDL Ledger のデータベースをセットアップする + +ScalarDL Ledger を展開する前にデータベースを準備する必要があります。ScalarDL Ledger は内部で ScalarDB を使用してデータベースにアクセスするため、ScalarDB がサポートするデータベースの種類を確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[Azure での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAzure.mdx) を参照してください。 + +## ステップ4. 踏み台サーバーを作成する + +AKS で ScalarDL Ledger をデプロイおよび管理するためのいくつかのツールを実行するには、**手順2**で作成した AKS クラスターの同じ Azure Virtual Network (VNet) 内に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ5. ScalarDL Ledger と ScalarDL Schema Loader の両方の Scalar Helm Chart のカスタム値ファイルを準備する + +**ステップ3**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDL Ledger と ScalarDL Schema Loader (Ledger 用) の両方の Scalar Helm Chart のカスタム値ファイルを構成する必要があります。詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + +## ステップ6. Scalar Helm Chart を使用して ScalarDL Ledger をデプロイする + +ScalarDL Ledger の Helm Chart を使用して、AKS クラスターに ScalarDL Ledger をデプロイします。詳細については、[Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注記:** `kubectl create ns scalardl-ledger` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardl-ledger` オプションを使用して名前空間に ScalarDL Ledger をデプロイすることをお勧めします。 + +## ステップ7. ScalarDL Ledger 導入のステータスを確認する + +ScalarDL Ledger を AKS クラスターにデプロイした後、各コンポーネントの状態を確認する必要があります。詳細については、[Kubernetes環境で実行する場合に定期的に確認するコンポーネント](RegularCheck.mdx)を参照してください。 + +## ステップ8. ScalarDL Ledger の展開を監視する + +AKS クラスターに ScalarDL Ledger をデプロイした後、特に運用環境では、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## ScalarDL Ledger を AKS から削除する + +作成した環境を削除する場合は、作成時とは逆の順序ですべてのリソースを削除してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnEKS.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnEKS.mdx new file mode 100644 index 00000000..4b3f8747 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnEKS.mdx @@ -0,0 +1,57 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledger を Amazon Elastic Kubernetes Service (EKS) にデプロイする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、**ScalarDL Ledger** を Amazon Elastic Kubernetes Service (EKS) にデプロイする方法について説明します。 + +このガイドでは、AWS 環境アカウントに次の環境を作成します。 + +![image](./images/png/EKS_ScalarDL_Ledger.drawio.png) + +## ステップ1. AWS Marketplace で ScalarDL Ledger を購読する + +[AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-3jdwfmqonx7a2) から ScalarDL Ledger コンテナイメージを取得し、ScalarDL にサブスクライブする必要があります。AWS Marketplace で ScalarDL Ledger を購読する方法の詳細については、[AWS Marketplace から Scalar 製品を購読する](AwsMarketplaceGuide.mdx#aws-marketplace-から-scalar-製品を購読する)を参照してください。 + +## ステップ2. EKS クラスターを作成する + +ScalarDL Ledger デプロイメント用の EKS クラスターを作成する必要があります。詳細については、[Scalar 製品用の Amazon EKS クラスターを作成するためのガイドライン](CreateEKSClusterForScalarProducts.mdx)を参照してください。 + +## ステップ3. ScalarDL Ledger のデータベースをセットアップする + +ScalarDL Ledger を展開する前にデータベースを準備する必要があります。ScalarDL Ledger は内部で ScalarDB を使用してデータベースにアクセスするため、ScalarDB がサポートするデータベースの種類を確認するには、[ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) を参照してください。 + +データベースのセットアップの詳細については、[AWS での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ](SetupDatabaseForAWS.mdx)を参照してください。 + +## ステップ4. 踏み台サーバーを作成する + +EKS で ScalarDL Ledger をデプロイおよび管理するためのいくつかのツールを実行するには、**ステップ2**で作成した EKS クラスターの同じ Amazon Virtual Private Cloud (VPC) 内に踏み台サーバーを準備する必要があります。詳細については、[踏み台サーバーの作成](CreateBastionServer.mdx)を参照してください。 + +## ステップ5. ScalarDL Ledger と ScalarDL Schema Loader の両方の Scalar Helm Chart のカスタム値ファイルを準備する + +**ステップ3**で作成したデータベース内の情報へのアクセスなどのタスクを実行するには、環境に基づいて ScalarDL Ledger と ScalarDL Schema Loader (Ledger 用) の両方の Scalar Helm Chart のカスタム値ファイルを構成する必要があります。詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + +## ステップ6. Scalar Helm Chart を使用して ScalarDL Ledger をデプロイする + +ScalarDL Ledger の Helm Chart を使用して、ScalarDL Ledger を EKS クラスターにデプロイします。詳細については、[Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) を参照してください。 + +**注記:** `kubectl create ns scalardl-ledger` コマンドを使用して専用の名前空間を作成し、`helm install` コマンドで `-n scalardl-ledger` オプションを使用して名前空間に ScalarDL Ledger をデプロイすることをお勧めします。 + +## ステップ7. ScalarDL Ledger 導入のステータスを確認する + +EKS クラスターに ScalarDL Ledger をデプロイした後、各コンポーネントのステータスを確認する必要があります。詳細については、[Kubernetes環境で実行する場合に定期的に確認するコンポーネント](RegularCheck.mdx)を参照してください。 + +## ステップ8. ScalarDL Ledger の展開を監視する + +EKS クラスターに ScalarDL Ledger をデプロイした後、特に本番環境では、デプロイされたコンポーネントを監視し、そのログを収集することをお勧めします。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +## EKS から ScalarDL Ledger を削除 + +作成した環境を削除する場合は、作成時とは逆の順序ですべてのリソースを削除してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/NetworkPeeringForScalarDLAuditor.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/NetworkPeeringForScalarDLAuditor.mdx new file mode 100644 index 00000000..239981ca --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/NetworkPeeringForScalarDLAuditor.mdx @@ -0,0 +1,61 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Auditor モード用にネットワークピアリングを構成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDL Auditor モードで複数のプライベートネットワークを接続し、ネットワークピアリングを実行する方法について説明します。ScalarDL Auditor モードが正しく動作するには、ScalarDL Ledger を ScalarDL Auditor に接続する必要があります。 + +## 接続する必要があるネットワーク + +ScalarDL Auditor モード (ビザンチン障害検出) を正しく機能させるには、3つのプライベートネットワークを接続する必要があります。 + +* [ScalarDL Ledger ネットワーク] ↔ [ScalarDL Auditor ネットワーク] +* [ScalarDL Ledger ネットワーク] ↔ [アプリケーション(クライアント)ネットワーク] +* [ScalarDL Auditor ネットワーク] ↔ [アプリケーション (クライアント) ネットワーク] + +## ネットワーク要件 + +### IP アドレス範囲 + +プライベートネットワーク間で IP アドレスが競合しないようにするには、異なる IP アドレス範囲を持つプライベートネットワークが必要です。例えば: + +* **ScalarDL Ledger のプライベートネットワーク:** 10.1.0.0/16 +* **ScalarDL Auditor のプライベートネットワーク:** 10.2.0.0/16 +* **アプリケーション (クライアント) のプライベートネットワーク:** 10.3.0.0/16 + +### 接続 + +ScalarDL Ledger、ScalarDL Auditor、およびアプリケーション (クライアント) を接続するためのデフォルトのネットワークポートは、デフォルトでは次のとおりです。各プライベートネットワーク間でこれらの接続を許可する必要があります。 + +* **ScalarDL Ledger** + * **50051/TCP:** アプリケーション (クライアント) および Scalar Envoy 経由の ScalarDL Auditor からのリクエストを受け入れます。 + * **50052/TCP:** アプリケーション (クライアント) および Scalar Envoy 経由の ScalarDL Auditor からの特権リクエストを受け入れます。 +* **ScalarDL Auditor** + * **40051/TCP:** Scalar Envoy を介してアプリケーション (クライアント) および ScalarDL Ledger からのリクエストを受け入れます。 + * **40052/TCP:** アプリケーション (クライアント) および Scalar Envoy 経由の ScalarDL Ledger からの特権リクエストを受け入れます。 +* **Scalar Envoy** (ScalarDL Ledger および ScalarDL Auditor とともに使用) + * **50051/TCP:** アプリケーション (クライアント) および ScalarDL Auditor からの ScalarDL Ledger に対するリクエストを受け入れます。 + * **50052/TCP:** アプリケーション (クライアント) および ScalarDL Auditor からの ScalarDL Ledger に対する特権リクエストを受け入れます。 + * **40051/TCP:** アプリケーション (クライアント) および ScalarDL Ledger からの ScalarDL Auditor のリクエストを受け入れます。 + * **40052/TCP:** アプリケーション (クライアント) および ScalarDL Ledger からの ScalarDL Auditor に対する特権リクエストを受け入れます。 + +構成ファイル (ledger.properties または auditor.properties) で ScalarDL のリスニングポートをデフォルトから変更する場合は、構成したポートを使用して接続を許可する必要があることに注意してください。 + +## プライベートネットワークピアリング + +各クラウドのプライベートネットワークの接続方法については公式ドキュメントを参照してください。 + +### Amazon VPC ピアリング + +アマゾンウェブサービス (AWS) 環境で Virtual Private Cloud (VPC) をピアリングする方法の詳細については、Amazon の公式ドキュメント [Create a VPC peering connection](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html) を参照してください。 + +### Azure VNet ピアリング + +Azure 環境で仮想ネットワークをピアリングする方法の詳細については、Microsoft の公式ドキュメント [Virtual network peering](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview) を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDBCluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDBCluster.mdx new file mode 100644 index 00000000..a1eed1be --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDBCluster.mdx @@ -0,0 +1,157 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster の制作チェックリスト + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチェックリストは、実稼働環境に ScalarDB Cluster をデプロイする際の推奨事項を提供します。 + +## あなたが始める前に + +このチェックリストでは、推奨される管理対象 Kubernetes クラスターに ScalarDB Cluster をデプロイしていることを前提としています。 + +## 実稼働チェックリスト: ScalarDB Cluster + +以下は、運用環境で ScalarDB Cluster をセットアップする際の推奨事項のチェックリストです。 + +### ポッドと Kubernetes ワーカーノードの数 + +Kubernetes クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つのポッドをワーカーノードに分散させるための `podAntiAffinity` の[サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardb-cluster-custom-values-indirect-mode.yaml)を参照できます。 + +:::note + +ワーカーノードを異なるアベイラビリティゾーン (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### ワーカーノードの仕様 + +商用ライセンスの観点から、ScalarDB Cluster を実行する1つのポッドのリソースは 2vCPU / 4GB メモリに制限されます。また、ScalarDB Cluster ポッド以外の一部のポッドがワーカーノード上に存在します。 + +つまり、次のコンポーネントは1つのワーカーノード上で実行できます。 + +* ScalarDB Cluster ポッド (2vCPU / 4GB) +* Envoy プロキシ (`indirect` クライアントモードを使用する場合、または Java 以外のプログラミング言語を使用する場合) +* アプリケーションポッド (同じワーカーノード上でアプリケーションのポッドを実行することを選択した場合) +* 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) +* Kubernetes コンポーネント + +:::note + +`direct-kubernetes` モードを使用する場合は、Envoy ポッドをデプロイする必要はありません。 + +::: + +これを念頭に置いて、[ポッドと Kubernetes ワーカーノードの数](ProductionChecklistForScalarDBCluster.mdx#ポッドと-kubernetes-ワーカーノードの数)で説明されているように、少なくとも 4vCPU / 8GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。 + +ただし、実稼働環境では、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが最小限です。システムのワークロードに応じて、Kubernetes クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDB Cluster ポッド、アプリケーションのポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングすることを計画している場合は、ワーカーノード上のポッドの最大数を考慮してワーカーノードのリソースを決定する必要があります。 + +#### 通信網 + +ScalarDB Cluster はインターネットアクセス経由でユーザーに直接サービスを提供しないため、Kubernetes クラスターはプライベートネットワーク上に作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDB Cluster にアクセスすることをお勧めします。 + +### 監視とログ記録 + +デプロイされたコンポーネントを監視し、そのログを収集する必要があります。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および `Kubernetes クラスター上の Scalar 製品からのログの収集](./K8sLogCollectionGuide.mdx)を参照してください。 + +### バックアップと復元 + +バックエンドデータベースで自動バックアップ機能とポイントインタイムリカバリ (PITR) 機能を有効にする必要があります。詳細については、[ScalarDB/ScalarDL 導入用のデータベースのセットアップ](SetupDatabase.mdx)を参照してください。 + +## 運用チェックリスト: ScalarDB Cluster にアクセスするクライアントアプリケーション + +以下は、実稼働環境で ScalarDB Cluster にアクセスするクライアントアプリケーションをセットアップする際の推奨事項のチェックリストです。 + +### クライアントモード (Java クライアントライブラリのみ) + +アプリケーションに Java を使用する場合、公式の Java クライアントライブラリを使用できます。この場合、[`direct-kubernetes mode`](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#direct-kubernetes-client-mode) または [`indirect mode`](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#indirect-client-mode) の2つのクライアントモードのいずれかを選択できます。 + +パフォーマンスの観点から、`direct-kubernetes` モードの使用をお勧めします。`direct-kubernetes` モードを使用するには、アプリケーションポッドを ScalarDB Cluster ポッドと同じ Kubernetes クラスターにデプロイする必要があります。この場合、Envoy ポッドをデプロイする必要はありません。 + +何らかの理由で Java アプリケーションポッドを ScalarDB Cluster ポッドと同じ Kubernetes クラスターにデプロイできない場合は、`indirect` モードを使用する必要があります。この場合、Envoy ポッドをデプロイする必要があります。 + +:::note + +クライアントモード設定は Java クライアントライブラリ専用です。アプリケーションに Java 以外のプログラミング言語を使用する場合 (基本的に、[gRPC API](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-grpc-api-guide) または [gRPC SQL API](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide) をプログラミング言語から直接使用する場合)、そのような構成は存在しません。この場合、Envoy ポッドをデプロイする必要があります。 + +::: + +### トランザクションマネージャーの構成 (Java クライアントライブラリのみ) + +クライアントアプリケーションは、常に ScalarDB Cluster を通じてデータベースにアクセスする必要があります。リクエストが適切に実行されていることを確認するには、クライアントアプリケーションのプロパティファイルをチェックし、CRUD API の使用時に `scalar.db.transaction_manager=cluster` が設定されていることを確認します。 + +#### 実稼働環境に推奨 + +```mermaid +flowchart LR + app["アプリ
gRPC を使用した ScalarDB Cluster ライブラリ"] + server["ScalarDB Cluster
Consensus Commit を備えた
ScalarDBライブラリ"] + db[(基盤となるストレージまたはデータベース)] + app --> server --> db +``` + +#### 本番環境では推奨されません (テスト目的のみ) + +```mermaid +flowchart LR + app["アプリ
Consensus Commit を備えた
ScalarDB Cluster ライブラリ"] + db[(基盤となるストレージまたはデータベース)] + app --> db +``` + +### SQL 接続構成 (Java クライアントライブラリのみ) + +クライアントアプリケーションは、常に ScalarDB Cluster を通じてデータベースにアクセスする必要があります。リクエストが適切に実行されていることを確認するには、クライアントアプリケーションのプロパティファイルをチェックし、SQL API を使用するときに `scalar.db.sql.connection_mode=cluster` が設定されていることを確認します。 + +#### 実稼働環境に推奨 + +```mermaid +flowchart LR + app["アプリ
ScalarDB SQL ライブラリ (クラスターモード)"] + server["ScalarDB Cluster
Consensus Commit を備えた
ScalarDB ライブラリ"] + db[(基盤となるストレージまたはデータベース)] + app --> server --> db +``` + +#### 運用環境では推奨されません (テスト目的のみ) + +```mermaid +flowchart LR + app["アプリ
ScalarDB SQL ライブラリ (ダイレクトモード)"] + db[(基盤となるストレージまたはデータベース)] + app --> db +``` + +### `direct-kubernetes` クライアントモードを使用する場合のクライアントアプリケーションのデプロイメント (Java クライアントライブラリのみ) + +[`direct-kubernetes` client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#direct-kubernetes-client-mode) を使用する場合は、クライアントアプリケーションを ScalarDB Cluster デプロイメントと同じ Kubernetes クラスターにデプロイする必要があります。 + +また、`direct-kubernetes` クライアントモードを使用する場合は、クライアントアプリケーションが適切に動作するように追加の Kubernetes リソースをデプロイする必要があります。詳細については、[Deploy your client application on Kubernetes with `direct-kubernetes` mode](../helm-charts/how-to-deploy-scalardb-cluster.mdx#direct-kubernetes-モードを使用してクライアント-アプリケーションを-kubernetes-にデプロイします) を参照してください。 + +### トランザクション処理 (Java クライアントライブラリと gRPC API) + +トランザクションを [`begin()`](https://scalardb.scalar-labs.com/docs/latest/api-guide#begin-or-start-a-transaction) した後、アプリケーションが常に [`commit()`](https://scalardb.scalar-labs.com/docs/latest/api-guide#commit-a-transaction) または [`rollback()`](https://scalardb.scalar-labs.com/docs/latest/api-guide#roll-back-or-abort-a-transaction) を実行するようにする必要があります。アプリケーションが `commit()` または `rollback()` を実行しない場合、アプリケーションで予期しない問題が発生したり、バックエンドデータベースから一貫性のないデータが読み取られる可能性があります。 + +:::note + +[gRPC API](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-grpc-api-guide) または [SQL gRPC API](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide) を使用する場合、アプリケーションは、`Begin` サービスを呼び出してトランザクションを開始した後、`Commit` サービスまたは `Rollback` サービスを呼び出す必要があります。 + +::: + +### 例外処理 (Java クライアントライブラリと gRPC API) + +アプリケーションがトランザクション例外を処理することを確認する必要があります。詳細については、使用している API のドキュメントを参照してください。 + +* [Handle exceptions (Transactional API)](https://scalardb.scalar-labs.com/docs/latest/api-guide#handle-exceptions). +* [Handle exceptions (two-phase commit transactions API)](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions#handle-exceptions) +* [Execute transactions (ScalarDB SQL API)](https://scalardb.scalar-labs.com/docs/latest/scalardb-sql/sql-api-guide#execute-transactions) +* [Handle SQLException (ScalarDB JDBC)](https://scalardb.scalar-labs.com/docs/latest/scalardb-sql/jdbc-guide#handle-sqlexception) +* [Error handling (ScalarDB Cluster gRPC API)](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-grpc-api-guide#error-handling-1) +* [Error handling (ScalarDB Cluster SQL gRPC API)](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide#error-handling-1) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLAuditor.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLAuditor.mdx new file mode 100644 index 00000000..56e5c658 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLAuditor.mdx @@ -0,0 +1,176 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Auditor の制作チェックリスト + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチェックリストは、ScalarDL Auditor を運用環境に展開する際の推奨事項を提供します。 + +## あなたが始める前に + +このチェックリストでは、推奨される管理対象 Kubernetes クラスターに ScalarDL Auditor をデプロイしていることを前提としています。 + +## プロダクションチェックリスト: ScalarDL Auditor + +以下は、運用環境で ScalarDL Auditor をセットアップする際の推奨事項のチェックリストです。 + +### ScalarDL の可用性 + +Kubernetes クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つのポッドをワーカーノードに分散させるための `podAntiAffinity` の[サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-audit-custom-values.yaml)を参照できます。 + +:::note + +ワーカーノードを異なるアベイラビリティゾーン (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### リソース + +商用ライセンスの観点から、ScalarDL Auditor を実行する1つのポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDL Auditor ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDL Auditor ポッド (2vCPU / 4GB) +* Envoy プロキシ +* 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) +* Kubernetes コンポーネント + +これを念頭に置いて、[ScalarDL の可用性](#scalardl-availability)で説明されているように、少なくとも 4vCPU / 8GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。 + +ただし、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが運用環境の最小環境となります。システムのワークロードに応じて、Kubernetes クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDL Auditor ポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、ワーカーノードのリソースを決定するときにワーカーノード上の最大ポッド数を考慮する必要があります。 + +### 通信網 + +ScalarDL Auditor はインターネットアクセス経由でユーザーにサービスを直接提供しないため、Kubernetes クラスターはプライベートネットワーク上に作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDL Auditor にアクセスすることをお勧めします。 + +### 監視とログ記録 + +デプロイされたコンポーネントを監視し、そのログを収集する必要があります。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +### バックアップと復元 + +バックエンドデータベースで自動バックアップ機能とポイントインタイムリカバリ (PITR) 機能を有効にする必要があります。詳細については、[ScalarDB/ScalarDL 導入用のデータベースのセットアップ](SetupDatabase.mdx)を参照してください。 + +### ScalarDL Auditor の展開 + +ScalarDL でのビザンチン障害検出が適切に機能するには、ScalarDL Ledger デプロイメントと同じ Kubernetes クラスターに ScalarDL Auditor ポッドをデプロイしないでください。代わりに、ScalarDL Ledger デプロイメントの管理ドメイン以外の環境 (Kubernetes クラスター以外) に ScalarDL Auditor ポッドをデプロイする必要があります。 + +#### 実稼働環境に必要 + +```mermaid +graph LR + subgraph "ScalarDL" + subgraph "管理ドメイン 1" + subgraph "Ledger 用の Kubernetes クラスター" + B-1[ScalarDL Ledger] + end + end + subgraph "管理ドメイン 2" + subgraph "Auditor 用の Kubernetes クラスター" + C-1[ScalarDL Auditor] + end + end + end +``` + +#### 運用環境では推奨されません (テスト目的のみ) + +```mermaid +graph LR + subgraph "Kubernetes クラスター" + direction LR + A-1[ScalarDL Ledger] + A-2[ScalarDL Auditor] + end +``` + +### ScalarDL Ledger と ScalarDL Auditor 間の接続 + +ScalarDL Auditor モードが正しく動作するには、ScalarDL Ledger と ScalarDL Auditor 間の接続を許可する必要があります。 + +```mermaid +graph LR + subgraph "Ledger 用の Kubernetes クラスター" + A-1[ScalarDL Ledger] + end + subgraph "Auditor 用の Kubernetes クラスター" + B-1[ScalarDL Auditor] + end + A-1 --- B-1 +``` + +ScalarDL は、ScalarDL Ledger と ScalarDL Auditor 間の接続に次のポートを使用します。ScalarDL Ledger と ScalarDL Auditor の間で次の接続を許可する必要があります。 + +* ScalarDL Ledger + * 50051/TCP + * 50052/TCP +* ScalarDL Auditor + * 40051/TCP + * 40052/TCP + +### 秘密鍵と証明書 + +認証に PKI を使用する場合は、ScalarDL Ledger および ScalaDL Auditor に登録する秘密鍵と証明書が次の要件を満たしていることを確認する必要があります。 + +```console +Algorithm : ECDSA +Hash function : SHA256 +Curve parameter : P-256 +``` + +詳しくは [How to get a certificate](https://scalardl.scalar-labs.com/ja-jp/docs/latest/ca/caclient-getting-started) をご覧ください。 + +## 実稼働チェックリスト: ScalarDL Auditor にアクセスするクライアントアプリケーション + +以下は、運用環境で ScalarDL Auditor にアクセスするクライアントアプリケーションをセットアップする際の推奨事項のチェックリストです。 + +### クライアントアプリケーションのデプロイメント + +ScalarDL でのビザンチン障害検出が適切に機能するには、ScalarDL デプロイメントと同じ Kubernetes クラスターにアプリケーションポッドをデプロイしないでください。代わりに、ScalarDL デプロイメントの管理ドメイン以外の環境 (Kubernetes クラスター以外) にアプリケーションをデプロイする必要があります。 + +#### 実稼働環境に必要 + +```mermaid +graph LR + subgraph "管理ドメイン 1" + subgraph "別の環境" + A-1[ユーザーアプリケーション] + end + end + subgraph "ScalarDL" + subgraph "管理ドメイン 2" + subgraph "Ledger 用の Kubernetes クラスター" + B-1[ScalarDL Ledger] + end + end + subgraph "管理ドメイン 3" + subgraph "Auditor 用の Kubernetes クラスター" + C-1[ScalarDL Auditor] + end + end + end + A-1 --> B-1 + A-1 --> C-1 +``` + +#### 運用環境では推奨されません (テスト目的のみ) + +```mermaid +graph LR + subgraph "Kubernetes クラスター" + direction LR + A-1[ユーザーアプリケーション] + A-2[ScalarDL Ledger] + A-3[ScalarDL Auditor] + end + A-1 --> A-2 + A-1 --> A-3 +``` + +### クライアントアプリケーションのチェックリスト + +また、[運用チェックリスト: ScalarDL Ledger にアクセスするクライアントアプリケーション](ProductionChecklistForScalarDLLedger.mdx#運用チェックリスト-scalardl-ledger-にアクセスするクライアントアプリケーション)を満たしていることも確認する必要があります。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLLedger.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLLedger.mdx new file mode 100644 index 00000000..d62e4781 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLLedger.mdx @@ -0,0 +1,162 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# ScalarDL Ledgerの制作チェックリスト + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチェックリストは、実稼働環境に ScalarDL Ledger を展開する際の推奨事項を提供します。 + +## あなたが始める前に + +このチェックリストでは、推奨される管理対象 Kubernetes クラスターに ScalarDL Ledger をデプロイしていることを前提としています。 + +## プロダクションチェックリスト: ScalarDL Ledger + +以下は、運用環境で ScalarDL Ledger をセットアップする際の推奨事項のチェックリストです。 + +### ScalarDL の可用性 + +Kubernetes クラスターの高可用性を確保するには、少なくとも3つのワーカーノードを使用し、ワーカーノード全体に少なくとも3つのポッドをデプロイする必要があります。3つのポッドをワーカーノードに分散させるための `podAntiAffinity` の[サンプル構成](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml)を参照できます。 + +:::note + +ワーカーノードを異なるアベイラビリティゾーン (AZ) に配置すると、AZ の障害に耐えることができます。 + +::: + +### リソース + +商用ライセンスの観点から、ScalarDL Ledger を実行する1つのポッドのリソースは 2vCPU / 4GB メモリに制限されます。ScalarDL Ledger ポッドに加えて、Kubernetes は次のコンポーネントの一部を各ワーカーノードにデプロイできます。 + +* ScalarDL Ledger ポッド (2vCPU / 4GB) +* Envoy プロキシ +* 監視コンポーネント (`kube-prometheus-stack` などの監視コンポーネントをデプロイする場合) +* Kubernetes コンポーネント + +これを念頭に置いて、[ScalarDL の可用性](#scalardl-availability) で説明されているように、少なくとも 4vCPU / 8GB のメモリリソースを持つワーカーノードを使用し、可用性のために少なくとも3つのワーカーノードを使用する必要があります。 + +ただし、ノードあたり少なくとも 4vCPU / 8GB のメモリリソースを備えた3つのノードが運用環境の最小環境となります。システムのワークロードに応じて、Kubernetes クラスターのリソース (ワーカーノードの数、ノードあたりの vCPU、ノードあたりのメモリ、ScalarDL Ledger ポッドなど) も考慮する必要があります。また、[Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) などの機能を使用してポッドを自動的にスケーリングする予定の場合は、ワーカーノードのリソースを決定するときにワーカーノード上の最大ポッド数を考慮する必要があります。 + +### 通信網 + +ScalarDL Ledger はインターネットアクセス経由でユーザーにサービスを直接提供しないため、Kubernetes クラスターはプライベートネットワーク上に作成する必要があります。アプリケーションからプライベートネットワーク経由で ScalarDL Ledger にアクセスすることをお勧めします。 + +### 監視とログ記録 + +デプロイされたコンポーネントを監視し、そのログを収集する必要があります。詳細については、[Kubernetes クラスター上の Scalar 製品の監視](K8sMonitorGuide.mdx)および [Kubernetes クラスター上の Scalar 製品からのログの収集](K8sLogCollectionGuide.mdx)を参照してください。 + +### バックアップと復元 + +バックエンドデータベースで自動バックアップ機能とポイントインタイムリカバリ (PITR) 機能を有効にする必要があります。詳細については、[ScalarDB/ScalarDL 導入用のデータベースのセットアップ](SetupDatabase.mdx) を参照してください。 + +## 運用チェックリスト: ScalarDL Ledger にアクセスするクライアントアプリケーション + +以下は、運用環境で ScalarDL Ledger にアクセスするクライアントアプリケーションをセットアップする際の推奨事項のチェックリストです。 + +### クライアントアプリケーションのデプロイメント + +ScalarDL でのビザンチン障害検出が適切に機能するには、アプリケーションポッドを ScalarDL Ledger デプロイメントと同じ Kubernetes クラスターにデプロイしないでください。代わりに、ScalarDL Ledger デプロイメントの管理ドメイン以外の環境 (Kubernetes クラスター以外) にアプリケーションをデプロイする必要があります。 + +#### 実稼働環境に必要 + +```mermaid +graph LR + subgraph "管理ドメイン 1" + subgraph "別の環境" + A-1[ユーザーアプリケーション] + end + end + subgraph "管理ドメイン 2" + subgraph "Kubernetes クラスター" + B-1[ScalarDL Ledger] + end + end + A-1 --> B-1 +``` + +#### 運用環境では推奨されません (テスト目的のみ) + +```mermaid +graph LR + subgraph "Kubernetes クラスター" + direction LR + A-1[ユーザーアプリケーション] --> A-2[ScalarDL Ledger] + end +``` + +### コントラクトと機能 + +コントラクトと機能がガイドラインに従っているかどうかを確認するには、次を参照してください。 + +* [A Guide on How to Write a Good Contract for ScalarDL](https://scalardl.scalar-labs.com/ja-jp/docs/latest/how-to-write-contract) +* [A Guide on How to Write Function for ScalarDL](https://scalardl.scalar-labs.com/ja-jp/docs/latest/how-to-write-function) + +### コントラクトのバージョン管理 + +コントラクトを登録した後は、既存のコントラクトを上書きすることはできません。したがって、コントラクトのバージョン管理を検討する必要があります。次の2つの方法のいずれかを推奨します。 + +#### `クラス名` を使用したバージョニング + +```console +Contract ID : FooV1 +Binary Name : com.example.contract.FooV1 +Class file (Class Name) : src/main/java/com/example/contract/FooV1.class +--- +Contract ID : FooV2 +Binary Name : com.example.contract.FooV2 +Class file (Class Name) : src/main/java/com/example/contract/FooV2.class +``` + +#### `Package Name` を使用したバージョニング + +```console +Contract ID : FooV3 +Binary Name : com.example.contract.v3.Foo +Class file (Class Name) : src/main/java/com/example/contract/v3/Foo.class +--- +Contract ID : FooV4 +Binary Name : com.example.contract.v4.Foo +Class file (Class Name) : src/main/java/com/example/contract/v4/Foo.class +``` + +### コントラクト上の制限 + +コントラクト登録時にバイナリ名、パッケージ名、クラス名が異なる場合、登録後にそのコントラクトを実行することはできません。 + +#### バイナリ名とクラス名が異なります (このコントラクトは実行できません) + +```console +Contract ID : FooV5 +Binary Name : com.example.contract.FooV5 +Class file (Class Name) : src/main/java/com/example/contract/FooV6.class +``` + +#### バイナリ名とパッケージ名が異なります (本コントラクトは実行できません) + +```console +Contract ID : FooV7 +Binary Name : com.example.contract.v7.Foo +Class file (Class Name) : src/main/java/com/example/contract/v8/Foo.class +``` + +### 秘密鍵と証明書 + +認証に PKI を使用する場合、ScalarDL Ledger に登録する秘密鍵と証明書が次の要件を満たしていることを確認する必要があります。 + +```console +Algorithm : ECDSA +Hash function : SHA256 +Curve parameter : P-256 +``` + +詳しくは [How to get a certificate](https://scalardl.scalar-labs.com/ja-jp/docs/latest/ca/caclient-getting-started) をご覧ください。 + +### 例外処理 + +アプリケーションが例外を処理することを確認する必要があります。詳細については、[A Guide on How to Handle Errors in ScalarDL](https://scalardl.scalar-labs.com/ja-jp/docs/latest/how-to-write-applications#エラーの処理) を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarProducts.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarProducts.mdx new file mode 100644 index 00000000..ccdb9a9a --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarProducts.mdx @@ -0,0 +1,18 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar 製品の制作チェックリスト + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +デプロイメントを本番環境に向けて準備するには、次を参照してください。 + +* [ScalarDB Cluster の制作チェックリスト](ProductionChecklistForScalarDBCluster.mdx) +* [ScalarDL Ledger の制作チェックリスト](ProductionChecklistForScalarDLLedger.mdx) +* [ScalarDL Auditor の制作チェックリスト](ProductionChecklistForScalarDLAuditor.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/RegularCheck.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/RegularCheck.mdx new file mode 100644 index 00000000..1e6a40c1 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/RegularCheck.mdx @@ -0,0 +1,99 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes 環境で実行するときに定期的にチェックするコンポーネント + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +手動デプロイメントガイドによってデプロイされたコンポーネントのほとんどは、マネージド Kubernetes サービスと Kubernetes 自己修復機能の助けを借りて自己修復されます。予期しない動作が発生したときに発生するアラートも設定されています。したがって、マネージド Kubernetes クラスターに Scalar 製品をデプロイするために毎日行うべきことはそれほど多くありません。ただし、システムのステータスを定期的にチェックして、すべてが正常に動作しているかどうかを確認することをお勧めします。ここでは、定期的に実行しておきたいことのリストを示します。 + +## Kubernetes リソース + +### ポッドがすべて正常なスタチューであるかどうかを確認する + +Kubernetes 名前空間を確認してください。 + +* Scalar 製品デプロイメントの `default` (または Scalar 製品をデプロイするときに指定された名前空間) +* Prometheus Operator と Loki の `monitoring` + +確認すべき内容: + +* `STATUS` はすべて `Running` です。 +* ポッドはさまざまなノードに均等に分散されます。 + +```console +kubectl get pod -o wide -n +``` + +次のような結果が表示されます: + +```console +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +scalardb-7876f595bd-2jb28 1/1 Running 0 2m35s 10.244.2.6 k8s-worker2 +scalardb-7876f595bd-rfvk6 1/1 Running 0 2m35s 10.244.1.8 k8s-worker +scalardb-7876f595bd-xfkv4 1/1 Running 0 2m35s 10.244.3.8 k8s-worker3 +scalardb-envoy-84c475f77b-cflkn 1/1 Running 0 2m35s 10.244.1.7 k8s-worker +scalardb-envoy-84c475f77b-tzmc9 1/1 Running 0 2m35s 10.244.3.7 k8s-worker3 +scalardb-envoy-84c475f77b-vztqr 1/1 Running 0 2m35s 10.244.2.5 k8s-worker2 +``` + +```console +kubectl get pod -n monitoring -o wide +``` + +次のような結果が表示されます: + +```console +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +alertmanager-scalar-monitoring-kube-pro-alertmanager-0 2/2 Running 1 (11m ago) 12m 10.244.2.4 k8s-worker2 +prometheus-scalar-monitoring-kube-pro-prometheus-0 2/2 Running 0 12m 10.244.1.5 k8s-worker +scalar-logging-loki-0 1/1 Running 0 13m 10.244.2.2 k8s-worker2 +scalar-logging-loki-promtail-2c4k9 0/1 Running 0 13m 10.244.0.5 k8s-control-plane +scalar-logging-loki-promtail-8r48b 1/1 Running 0 13m 10.244.3.2 k8s-worker3 +scalar-logging-loki-promtail-b26c6 1/1 Running 0 13m 10.244.2.3 k8s-worker2 +scalar-logging-loki-promtail-sks56 1/1 Running 0 13m 10.244.1.2 k8s-worker +scalar-monitoring-grafana-77c4dbdd85-4mrn7 3/3 Running 0 12m 10.244.3.4 k8s-worker3 +scalar-monitoring-kube-pro-operator-7575dd8bbd-bxhrc 1/1 Running 0 12m 10.244.1.3 k8s-worker +``` + +### ノードがすべて正常なステータスであるかどうかを確認します + +確認すべき内容: + +* `STATUS` はすべて `Ready` です。 + +```console +kubectl get nodes +``` + +次のような結果が表示されます: + +```console +NAME STATUS ROLES AGE VERSION +k8s-control-plane Ready control-plane 16m v1.25.3 +k8s-worker Ready 15m v1.25.3 +k8s-worker2 Ready 15m v1.25.3 +k8s-worker3 Ready 15m v1.25.3 +``` + +## Prometheus ダッシュボード (Scalar 製品のアラート) + +ドキュメント [Kubernetes クラスター上の Scalar 製品のモニタリング](K8sMonitorGuide.mdx)に従って、Prometheus ダッシュボードにアクセスします。[**アラート**] タブで、アラートのステータスを確認できます。 + +確認すべき内容: + +* すべてのアラートは **緑色 (非アクティブ)** + +何らかの問題が発生している場合は、**赤色 (起動中)** のステータスが表示されます。 + +## Grafana ダッシュボード (Scalar 製品のメトリクス) + +ドキュメント [Kubernetes クラスター上の Scalar 製品のモニタリング](K8sMonitorGuide.mdx)に従って、Grafana ダッシュボードにアクセスします。[**ダッシュボード**] タブには、Scalar 製品のダッシュボードが表示されます。これらのダッシュボードでは、Scalar 製品のいくつかのメトリクスを確認できます。 + +これらのダッシュボードは問題に直接対処することはできませんが、通常からの変化 (トランザクションエラーの増加など) を確認して、問題を調査するためのヒントを得ることができます。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/RestoreDatabase.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/RestoreDatabase.mdx new file mode 100644 index 00000000..3e299a9a --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/RestoreDatabase.mdx @@ -0,0 +1,164 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Kubernetes 環境でデータベースを復元する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB または ScalarDL が Kubernetes 環境で使用するデータベースを復元する方法について説明します。このガイドは、クラウドサービスプロバイダーのマネージドデータベースを ScalarDB または ScalarDL のバックエンドデータベースとして使用していることを前提としていることに注意してください。 + +## データベースをリストアする手順 + +1. ScalarDB または ScalarDL ポッドを**0**にスケールインして、バックエンドデータベースへのリクエストを停止します。Helm コマンドで `--set *.replicaCount=0` フラグを使用すると、ポッドを**0**にスケールインできます。 + * ScalarDB Server + ```console + helm upgrade scalar-labs/scalardb -n -f /path/to/ --set scalardb.replicaCount=0 + ``` + * ScalarDL Ledger + ```console + helm upgrade scalar-labs/scalardl -n -f /path/to/ --set ledger.replicaCount=0 + ``` + * ScalarDL Auditor + ```console + helm upgrade scalar-labs/scalardl-audit -n -f /path/to/ --set auditor.replicaCount=0 + ``` +2. ポイントインタイムリカバリ (PITR) 機能を使用してデータベースを復元します。 + + 管理データベースに基づいてデータベースを復元する方法の詳細については、このガイドの[管理されたデータベースに基づいてデータを復元するための補足手順](RestoreDatabase.mdx#管理されたデータベースに基づいてデータを復元するための補足手順)セクションを参照してください。 + + NoSQL または複数のデータベースを使用している場合は、[Kubernetes 環境での NoSQL データベースのバックアップ](BackupNoSQL.mdx)のバックアップ手順に従うときに作成した一時停止期間の中間点を指定する必要があります。 +3. 新しく復元されたデータベースに基づいて **database.properties**、**ledger.properties**、または **auditor.properties** を更新します。 + + PITR 機能はデータベースを別のインスタンスとして復元するため、新しく復元されたデータベースにアクセスするには、ScalarDB または ScalarDL のカスタム値ファイル内のエンドポイント情報を更新する必要があります。カスタム値ファイルの設定方法の詳細については、[Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx) を参照してください。 + + Amazon DynamoDB を使用している場合、データは別のインスタンスではなく別のテーブル名で復元されることに注意してください。つまり、データの復元後にエンドポイントは変更されません。代わりに、Amazon DynamoDB 内のテーブルの名前を変更してデータを復元する必要があります。同じテーブル名でデータを復元する方法の詳細については、このガイドの [Amazon DynamoDB](RestoreDatabase.mdx#amazon-dynamodb) セクションを参照してください。 +4. Helm コマンドの `--set *.replicaCount=N` フラグを使用して、ScalarDB または ScalarDL ポッドを**1**以上にスケールアウトし、クライアントからのリクエストの受け入れを開始します。 + * ScalarDB Server + ```console + helm upgrade scalar-labs/scalardb -n -f /path/to/ --set scalardb.replicaCount=3 + ``` + * ScalarDL Ledger + ```console + helm upgrade scalar-labs/scalardl -n -f /path/to/ --set ledger.replicaCount=3 + ``` + * ScalarDL Auditor + ```console + helm upgrade scalar-labs/scalardl-audit -n -f /path/to/ --set auditor.replicaCount=3 + ``` + +## 管理されたデータベースに基づいてデータを復元するための補足手順 + +### Amazon DynamoDB + +PITR 機能を使用すると、Amazon DynamoDB は別のテーブル名でデータを復元します。したがって、同じテーブル名でデータを復元するには、追加の手順に従う必要があります。 + +#### ステップ + +1. バックアップを作成します。 + 1. 一時停止期間の中間点を復元ポイントとして選択します。 + 2. PITR を使用してテーブル A をテーブル B に復元します。 + 3. 復元されたテーブル B のバックアップを実行します。次に、バックアップの名前がバックアップ B に適切であることを確認します。 + 4. テーブル B を取り外します。 + + PITR を使用して DynamoDB テーブルを復元する方法、および DynamoDB テーブルのバックアップを手動で実行する方法の詳細については、Amazon の次の公式ドキュメントを参照してください。 + + * [Restoring a DynamoDB table to a point in time](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/PointInTimeRecovery.Tutorial.html) + * [Backing up a DynamoDB table](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Backup.Tutorial.html) + + この **バックアップの作成** ステップは、[Kubernetes 環境で NoSQL データベースをバックアップする](BackupNoSQL.mdx#データを復元する期間を作成しバックアップを実行します) のバックアップ操作の一部として実行できます。 + +2. バックアップから復元します。 + 1. テーブル A を取り外します。 + 2. バックアップ B を使用して、A という名前のテーブルを作成します。 + +3. 環境に応じて、必要に応じてテーブル構成を更新します。 + + 自動スケーリングポリシーなどの一部の構成は復元後に設定されないため、必要に応じてこれらの構成を手動で設定する必要がある場合があります。詳細については、Amazon の公式ドキュメント[Backing up and restoring DynamoDB tables with DynamoDB: How it works](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CreateBackup.html) を参照してください。 + + たとえば、ScalarDB Schema Loader または ScalarDL Schema Loader を使用してテーブルを作成している場合、自動スケーリングはデフォルトで有効になります。したがって、DynamoDB で復元されたテーブルの自動スケーリングを手動で有効にする必要があります。DynamoDB で自動スケーリングを有効にする方法の詳細については、Amazon の公式ドキュメント [Enabling DynamoDB auto scaling on existing tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/AutoScaling.Console.html#AutoScaling.Console.ExistingTable) を参照してください。 + + さらに、データベースを復元した後は、PITR 機能が無効になり、読み取り/書き込み容量モードがデフォルト値にリセットされます。環境に応じて、必要に応じてこれらの構成を手動で設定する必要があります。復元されたテーブルの一部の構成については、[AWS (Amazon DynamoDB) での ScalarDB/ScalarDL デプロイメント用のデータベースのセットアップ](SetupDatabaseForAWS.mdx#amazon-dynamodb)を参照してください。 + +### NoSQL 用 Azure Cosmos DB + +PITR 機能を使用する場合、Azure Cosmos DB は別のアカウントを使用してデータを復元します。したがって、カスタム値ファイル内のエンドポイント構成を更新する必要があります。 + +#### ステップ + +1. アカウントを復元します。PITR を使用して Azure Cosmos DB アカウントを復元する方法の詳細については、[Restore an Azure Cosmos DB account that uses continuous backup mode](https://learn.microsoft.com/en-us/azure/cosmos-db/restore-account-continuous-backup) を参照してください。 + +2. 復元されたアカウントの **デフォルトの整合性レベル** をデフォルト値から **Strong** に変更します。この値の変更方法の詳細については、Microsoft の公式ドキュメント [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level) を参照してください。 + +3. 新しく復元されたアカウントに基づいて、ScalarDB Schema Loader または ScalarDL Schema Loader の **database.properties** を更新します。 + + ScalarDB は、ScalarDB Schema Loader または ScalarDL Schema Loader を使用してスキーマを作成するときにインストールされるストアドプロシージャを使用して Cosmos DB アダプターを実装します。ただし、Cosmos DB の PITR 機能はストアドプロシージャを復元しないため、復元後にすべてのテーブルに必要なストアドプロシージャを再インストールする必要があります。ScalarDB Schema Loader または ScalarDL Schema Loader の `--repair-all` オプションを使用して、必要なストアドプロシージャを再インストールできます。 + * **ScalarDB テーブル:** ScalarDB Schema Loader の **database.properties** を構成する方法の詳細については、[Configure ScalarDB for Cosmos DB for NoSQL](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) を参照してください。 + + * **ScalarDL テーブル:** ScalarDL Schema Loader のカスタム値ファイルの設定方法の詳細については、[Configure a custom values file for ScalarDL Schema Loader](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx) を参照してください。 + +4. 次のように、ScalarDB Schema Loader または ScalarDL Schema Loader で `--repair-all` フラグを使用してストアドプロシージャを再作成します。 + + * ScalarDB テーブル + ```console + java -jar scalardb-schema-loader-.jar --config /path/to/ -f /path/to/ [--coordinator] --repair-all + ``` + * ScalarDL Ledger テーブル + ```console + helm install repair-schema-ledger scalar-labs/schema-loading -n -f /path/to/ --set "schemaLoading.commandArgs={--repair-all}" + ``` + * ScalarDL Auditor テーブル + ```console + helm install repair-schema-auditor scalar-labs/schema-loading -n -f /path/to/ --set "schemaLoading.commandArgs={--repair-all}" + ``` + + ScalarDB Schema Loader でのテーブルの修復の詳細については、[Repair tables](https://scalardb.scalar-labs.com/docs/latest/schema-loader#repair-tables) を参照してください。 + +5. 環境に応じて、必要に応じてテーブル構成を更新します。復元されたアカウントの構成については、[Azure での ScalarDB/ScalarDL デプロイ用のデータベースのセットアップ (Azure Cosmos DB for NoSQL)](SetupDatabaseForAzure.mdx#azure-cosmos-db-for-nosql) を参照してください。 + +### Amazon RDS + +PITR 機能を使用する場合、Amazon RDS は別のデータベースインスタンスを使用してデータを復元します。したがって、カスタム値ファイル内のエンドポイント構成を更新する必要があります。 + +#### ステップ + +1. データベースインスタンスを復元します。PITR を使用して Amazon RDS インスタンスを復元する方法の詳細については、Amazon の次の公式ドキュメントを参照してください。 + * [Restoring a DB instance to a specified time](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIT.html) + * [Restoring a Multi-AZ DB cluster to a specified time](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIT.MultiAZDBCluster.html) + +2. 環境に応じて、必要に応じてテーブル構成を更新します。復元されたデータベースインスタンスの構成については、[AWS での ScalarDB/ScalarDL デプロイメント用のデータベースのセットアップ (Amazon RDS for MySQL、PostgreSQL、Oracle、および SQL Server)](SetupDatabaseForAWS.mdx#mysqlpostgresqloraclesql-server-用の-amazon-rds) を参照してください。 + +### Amazon Aurora + +PITR 機能を使用する場合、Amazon Aurora は別のデータベースクラスターを使用してデータを復元します。したがって、カスタム値ファイル内のエンドポイント構成を更新する必要があります。 + +#### ステップ + +1. データベースクラスターを復元します。PITR を使用して Amazon Aurora クラスターを復元する方法の詳細については。Amazon の公式ドキュメント [Restoring a DB cluster to a specified time](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-pitr.html) を参照してください。 + +2. 環境に応じて、必要に応じてレプリカ (リーダー) を追加してデータベースクラスターをマルチ AZ クラスターにします。 + + Amazon Aurora の PITR 機能は、マルチ AZ 構成を使用してデータベースクラスターを復元できません。データベースクラスターをマルチ AZ クラスターとして復元する場合は、データベースクラスターの復元後にリーダーを追加する必要があります。リーダーの追加方法の詳細については、Amazon の公式ドキュメント [Adding Aurora Replicas to a DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-replicas-adding.html) を参照してください。 + +3. 環境に応じて、必要に応じてテーブル構成を更新します。復元されたデータベースクラスターの構成については、[AWS での ScalarDB/ScalarDL デプロイメント用のデータベースのセットアップ (Amazon Aurora MySQL および Amazon Aurora PostgreSQL)](SetupDatabaseForAWS.mdx#amazon-aurora-mysql-と-amazon-aurora-postgresql) を参照してください。 + +### Azure Database for MySQL/PostgreSQL + +PITR 機能を使用する場合、Azure Database for MySQL/PostgreSQL は別のサーバーを使用してデータを復元します。したがって、カスタム値ファイル内のエンドポイント構成を更新する必要があります。 + +#### ステップ + +1. データベースサーバーを復元します。PITR を使用して Azure Database for MySQL/PostgreSQL サーバーを復元する方法の詳細については、次を参照してください。 + + * [Point-in-time restore of a Azure Database for MySQL Flexible Server using Azure portal](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/how-to-restore-server-portal) + * [Backup and restore in Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-backup-restore) + +2. 環境に応じて、必要に応じてテーブル構成を更新します。復元されたデータベースサーバーの構成については、次を参照してください。 + + * [Azure 上で ScalarDB/ScalarDL デプロイ用のデータベースをセットアップする (Azure Database for MySQL)](SetupDatabaseForAzure.mdx#azure-database-for-mysql) + * [Azure 上で ScalarDB/ScalarDL デプロイ用のデータベースをセットアップする (Azure Database for PostgreSQL)](SetupDatabaseForAzure.mdx#azure-database-for-postgresql) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabase.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabase.mdx new file mode 100644 index 00000000..4d778c82 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabase.mdx @@ -0,0 +1,17 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB/ScalarDL デプロイメント用のデータベースをセットアップする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、クラウドサービス上で ScalarDB/ScalarDL を展開するためのデータベースをセットアップする方法について説明します。 + +* [AWS での ScalarDB/ScalarDL デプロイメント用のデータベースのセットアップ](SetupDatabaseForAWS.mdx) +* [Azure 上で ScalarDB/ScalarDL デプロイメント用のデータベースをセットアップする](SetupDatabaseForAzure.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabaseForAWS.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabaseForAWS.mdx new file mode 100644 index 00000000..886bc251 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabaseForAWS.mdx @@ -0,0 +1,186 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# AWS で ScalarDB/ScalarDL デプロイメント用のデータベースをセットアップする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、AWS で ScalarDB/ScalarDL をデプロイするためのデータベースをセットアップする方法について説明します。 + +## Amazon DynamoDB + +### 認証方法 + +DynamoDB を使用する場合、ScalarDB/ScalarDL プロパティファイルに `REGION`、`ACCESS_KEY_ID`、および `SECRET_ACCESS_KEY` を次のように設定する必要があります。 + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=dynamo +``` + +DynamoDB のプロパティの詳細については、次のドキュメントを参照してください。 + +* [Configure ScalarDB for DynamoDB](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### 必要な構成/手順 + +DynamoDB はデフォルトで AWS で使用できます。使用するために手動で何かを設定する必要はありません。 + +### オプションの構成/手順 + +#### ポイントインタイムリカバリを有効にする (運用環境で推奨) + +DynamoDB のバックアップ/復元方法として PITR を有効にすることができます。[ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader) を使用してスキーマを作成すると、デフォルトでテーブルの PITR 機能が有効になります。詳細については公式ドキュメントを参照してください。 + +* [Point-in-time recovery for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/PointInTimeRecovery.html) + +ポイントインタイムリカバリ機能により自動的かつ継続的にバックアップが作成されるため、バックアップ操作のダウンタイム (一時停止期間) を短縮できるため、この機能をお勧めします。Scalar 製品データのバックアップ/復元方法の詳細については、次のドキュメントを参照してください。 + +* [Scalar 製品のバックアップ復元ガイド](BackupRestoreGuide.mdx) + +#### 監視を構成する (運用環境で推奨) + +DynamoDB のネイティブ機能を使用して、DynamoDB のモニタリングとロギングを設定できます。詳細については公式ドキュメントを参照してください。 + +* [Monitoring and logging](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/monitoring.html) + +メトリクスとログは、運用環境で問題が発生したときにそれを調査するのに役立つため、これをお勧めします。 + +#### VPC エンドポイントを使用する (本番環境で推奨) + +// この機能は Scalar 製品ではまだテストされていないことに注意してください。 +// TODO: この機能を Scalar 製品でテストする必要があります。 + +* [Using Amazon VPC endpoints to access DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/vpc-endpoints-dynamodb.html) + +WAN 経由ではないプライベート内部接続によりシステムの安全性が高まるため、これをお勧めします。 + +#### 読み取り/書き込み容量の構成 (環境に応じてオプション) + +要件に基づいて、DynamoDB テーブルの **読み取り/書き込み容量** を構成できます。読み取り/書き込み容量の詳細については、公式ドキュメントを参照してください。 + +* [Read/write capacity mode](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html) + +テーブルの作成時に、ScalarDB/DL Schema Loader を使用して読み取り/書き込み容量を構成できます。ScalarDB/DL Schema Loader を使用して読み取り/書き込み容量 (RU) を構成する方法の詳細については、次のドキュメントを参照してください。 + +* [ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader) + +## MySQL、PostgreSQL、Oracle、SQL Server 用の Amazon RDS + +### 認証方法 + +RDS を使用する場合、ScalarDB/ScalarDL プロパティファイルに `JDBC_URL`、`USERNAME`、および `PASSWORD` を次のように設定する必要があります。 + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=jdbc +``` + +RDS (JDBCデータベース) のプロパティの詳細については、以下のドキュメントを参照してください。 + +* [Configure ScalarDB for JDBC databases](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### 必要な構成/手順 + +#### RDS データベースインスタンスを作成する + +RDS データベースインスタンスを作成する必要があります。詳細については公式ドキュメントを参照してください。 + +* [Configuring an Amazon RDS DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_RDS_Configuring.html) + +### オプションの構成/手順 + +#### 自動バックアップを有効にする (運用環境で推奨) + +自動バックアップを有効にすることができます。詳細については公式ドキュメントを参照してください。 + +* [Working with backups](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html) + +自動バックアップ機能によりポイントインタイムリカバリ機能が有効になるため、これをお勧めします。データを特定の時点まで復元できます。Scalar 製品で複数のデータベースを使用する場合、バックアップ操作のダウンタイム (一時停止時間) を短縮できます。Scalar 製品データのバックアップ/復元方法の詳細については、次のドキュメントを参照してください。 + +* [Scalar 製品のバックアップ復元ガイド](BackupRestoreGuide.mdx) + +#### 監視を構成する (運用環境で推奨) + +RDS のネイティブ機能を使用して、RDS の監視とログ記録を構成できます。詳細については公式ドキュメントを参照してください。 + +* [Monitoring metrics in an Amazon RDS instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Monitoring.html) +* [Monitoring events, logs, and streams in an Amazon RDS DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Monitor_Logs_Events.html) + +メトリクスとログは、運用環境で問題が発生したときにそれを調査するのに役立つため、これをお勧めします。 + +#### パブリックアクセスを無効にする (運用環境で推奨) + +パブリックアクセスはデフォルトでは無効になっています。次のように、EKS クラスター上の Scalar 製品ポッドから RDS データベースインスタンスにアクセスできます。 + +* EKS クラスターと同じ VPC 上に RDS データベースインスタンスを作成します。 +* [VPC peering](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html) を使用して、Scalar 製品デプロイの RDS 用 VPC と EKS クラスター用 VPC を接続します。(// TODO: この機能を Scalar 製品でテストする必要があります。) + +WAN 経由ではないプライベート内部接続によりシステムの安全性が高まるため、これをお勧めします。 + +## Amazon Aurora MySQL と Amazon Aurora PostgreSQL + +### 認証方法 + +Amazon Aurora を使用する場合、ScalarDB/ScalarDL プロパティファイルに `JDBC_URL`、`USERNAME`、および `PASSWORD` を次のように設定する必要があります。 + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=jdbc +``` + +Amazon Aurora (JDBC データベース) のプロパティの詳細については、次のドキュメントを参照してください。 + +* [Configure ScalarDB for JDBC databases](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### 必要な構成/手順 + +#### Amazon Aurora DB クラスターを作成する + +Amazon Aurora DB クラスターを作成する必要があります。詳細については公式ドキュメントを参照してください。 + +* [Configuring your Amazon Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraSettingUp.html) + +### オプションの構成/手順 + +#### バックアップ構成を構成します (環境に応じてオプション) + +Amazon Aurora はデフォルトで自動的にバックアップを取得します。バックアップ機能を手動で有効にする必要はありません。 + +バックアップ保持期間やバックアップウィンドウなどのバックアップ構成を変更する場合は、それらを構成できます。詳細については公式ドキュメントを参照してください。 + +* [Backing up and restoring an Amazon Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/BackupRestoreAurora.html) + +Scalar 製品データのバックアップ/復元方法の詳細については、次のドキュメントを参照してください。 + +* [Scalar 製品のバックアップ復元ガイド](BackupRestoreGuide.mdx) + +#### 監視を構成する (運用環境で推奨) + +Amazon Aurora のネイティブ機能を使用して、Amazon Aurora のモニタリングとロギングを設定できます。詳細については公式ドキュメントを参照してください。 + +* [Monitoring metrics in an Amazon Aurora cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/MonitoringAurora.html) +* [Monitoring events, logs, and streams in an Amazon Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_Monitor_Logs_Events.html) + +メトリクスとログは、運用環境で問題が発生したときにそれを調査するのに役立つため、これをお勧めします。 + +#### パブリックアクセスを無効にする (運用環境で推奨) + +パブリックアクセスはデフォルトでは無効になっています。次のように、EKS クラスター上の Scalar 製品ポッドから Amazon Aurora DB クラスターにアクセスできます。 + +* EKS クラスターと同じ VPC 上に Amazon Aurora DB クラスターを作成します。 +* [VPC peering](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html) を使用して、Scalar 製品デプロイメント用の Amazon Aurora DB クラスターの VPC と EKS クラスターの VPC を接続します。(// TODO: この機能を Scalar 製品でテストする必要があります。) + +WAN 経由ではないプライベート内部接続によりシステムの安全性が高まるため、これをお勧めします。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabaseForAzure.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabaseForAzure.mdx new file mode 100644 index 00000000..26b7bfe7 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/SetupDatabaseForAzure.mdx @@ -0,0 +1,210 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Azure で ScalarDB/ScalarDL デプロイ用のデータベースをセットアップする + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、Azure 上で ScalarDB/ScalarDL デプロイ用のデータベースをセットアップする方法について説明します。 + +## Azure Cosmos DB for NoSQL + +### 認証方法 + +Cosmos DB for NoSQL を使用する場合は、ScalarDB/ScalarDL プロパティファイルで `COSMOS_DB_URI` と `COSMOS_DB_KEY` を次のように設定する必要があります。 + +```properties +scalar.db.contact_points= +scalar.db.password= +scalar.db.storage=cosmos +``` + +Cosmos DB for NoSQL のプロパティの詳細については、次のドキュメントを参照してください。 + +* [Configure ScalarDB for Cosmos DB for NoSQL](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### 必要な構成/手順 + +#### Azure Cosmos DB アカウントを作成する + +NoSQL (コア) API を使用して Azure Cosmos DB アカウントを作成する必要があります。**Capacity mode**を作成するときは、**Provisioned throughput**として設定する必要があります。詳細については公式ドキュメントを参照してください。 + +* [Quickstart: Create an Azure Cosmos DB account, database, container, and items from the Azure portal](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal) + +#### デフォルトの整合性構成を構成する + +**Default consistency level**を**Strong**に設定する必要があります。詳細については公式ドキュメントを参照してください。 + +* [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#config/ure-the-default-consistency-level) + +### オプションの構成/手順 + +#### バックアップ構成を構成する (実稼働環境で推奨) + +PITR の **Backup modes**を **Continuous backup mode**として構成できます。詳細については公式ドキュメントを参照してください。 + +* [Backup modes](https://learn.microsoft.com/en-us/azure/cosmos-db/online-backup-and-restore#backup-modes) + +継続バックアップモードでは自動的かつ継続的にバックアップが取得されるため、バックアップ操作のダウンタイム (一時停止期間) を短縮できるため、このモードをお勧めします。Scalar 製品データのバックアップ/復元方法の詳細については、次のドキュメントを参照してください。 + +* [Scalar 製品のバックアップ復元ガイド](BackupRestoreGuide.mdx) + +#### 監視を構成する (運用環境で推奨) + +Cosmos DB の監視は、ネイティブ機能を使用して構成できます。詳細については、公式ドキュメントを参照してください。 + +* [Azure Cosmos DB を監視する](https://learn.microsoft.com/en-us/azure/cosmos-db/monitor) + +メトリックとログは、運用環境で問題が発生したときに調査するのに役立つため、推奨されます。 + +#### サービスエンドポイントを有効にする (運用環境で推奨) + +仮想ネットワーク (VNet) の特定のサブネットからのアクセスのみを許可するように Azure Cosmos DB アカウントを構成できます。詳細については公式ドキュメントを参照してください。 + +* [Configure access to Azure Cosmos DB from virtual networks (VNet)](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-configure-vnet-service-endpoint) + +WAN 経由ではないプライベート内部接続によりシステムの安全性が高まるため、これをお勧めします。 + +#### リクエストユニットを構成します (環境に応じてオプション) + +要件に基づいて Cosmos DB の **Request Units** を構成できます。リクエスト単位の詳細については公式ドキュメントを参照してください。 + +* [Request Units in Azure Cosmos DB](https://learn.microsoft.com/en-us/azure/cosmos-db/request-units) + +テーブルの作成時に、ScalarDB/DL Schema Loader を使用してリクエストユニットを構成できます。ScalarDB/DL Schema Loader を使用してリクエストユニット (RU) を構成する方法の詳細については、次のドキュメントを参照してください。 + +* [ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader) + +## Azure Database for MySQL + +### 認証方法 + +Azure Database for MySQL を使用する場合は、ScalarDB/ScalarDL プロパティファイルで `JDBC_URL`、`USERNAME`、および `PASSWORD` を次のように設定する必要があります。 + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=jdbc +``` + +Azure Database for MySQL (JDBC データベース) のプロパティの詳細については、次のドキュメントを参照してください。 + +* [Configure ScalarDB for JDBC databases](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### 必要な構成/手順 + +#### データベースサーバーを作成する + +データベースサーバーを作成する必要があります。詳細については公式ドキュメントを参照してください。 + +* [Quickstart: Use the Azure portal to create an Azure Database for MySQL Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/quickstart-create-server-portal) + +導入には **Single Server** または **Flexible Server** を選択できます。ただし、Azure では Flexible Server が推奨されます。このドキュメントは、Flexible Server の使用を前提としています。導入モデルの詳細については、公式ドキュメントを参照してください。 + +* [What is Azure Database for MySQL?](https://learn.microsoft.com/en-us/azure/mysql/single-server/overview#deployment-models) + +### オプションの構成/手順 + +#### バックアップ構成を構成します (環境に応じてオプション) + +Azure Database for MySQL は、既定でバックアップを取得します。バックアップ機能を手動で有効にする必要はありません。 + +バックアップの保持期間など、一部のバックアップ構成を変更する場合は、それを構成できます。詳細については公式ドキュメントを参照してください。 + +* [Backup and restore in Azure Database for MySQL Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/concepts-backup-restore) + +Scalar 製品データのバックアップ/復元方法の詳細については、次のドキュメントを参照してください。 + +* [Scalar 製品のバックアップ復元ガイド](BackupRestoreGuide.mdx) + +#### 監視を構成する (運用環境で推奨) + +Azure Database for MySQL のネイティブ機能を使用して、その監視を構成できます。詳細については公式ドキュメントを参照してください。 + +* [Monitor Azure Database for MySQL Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/concepts-monitoring) + +メトリクスとログは、運用環境で問題が発生したときにそれを調査するのに役立つため、これをお勧めします。 + +#### パブリックアクセスを無効にする (運用環境で推奨) + +**Private access (VNet Integration)** を **Connectivity method** として構成できます。詳細については公式ドキュメントを参照してください。 + +* [Connectivity and networking concepts for Azure Database for MySQL - Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/concepts-networking) + +次のように、AKS クラスター上の Scalar 製品ポッドからデータベースサーバーにアクセスできます。 + +* AKS クラスターと同じ VNet 上にデータベースサーバーを作成します。 +* [Virtual network peering](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview) を使用して、Scalar 製品デプロイのデータベースサーバー用の VNet と AKS クラスター用の VNet を接続します。(// TODO: この機能を Scalar 製品でテストする必要があります。) + +WAN 経由ではないプライベート内部接続によりシステムの安全性が高まるため、これをお勧めします。 + +## Azure Database for PostgreSQL + +### 認証方法 + +Azure Database for PostgreSQL を使用する場合は、ScalarDB/ScalarDL プロパティファイルで `JDBC_URL`、`USERNAME`、および `PASSWORD` を次のように設定する必要があります。 + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=jdbc +``` + +Azure Database for PostgreSQL (JDBC データベース) のプロパティの詳細については、次のドキュメントを参照してください。 + +* [Configure ScalarDB for JDBC databases](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### 必要な構成/手順 + +#### データベースサーバーを作成する + +データベースサーバーを作成する必要があります。詳細については公式ドキュメントを参照してください。 + +* [Quickstart: Create an Azure Database for PostgreSQL - Flexible Server in the Azure portal](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/quickstart-create-server-portal) + +導入には **Single Server** または **Flexible Server** を選択できます。ただし、Azure では Flexible Server が推奨されます。このドキュメントは、Flexible Server の使用を前提としています。導入モデルの詳細については、公式ドキュメントを参照してください。 + +* [What is Azure Database for PostgreSQL?](https://learn.microsoft.com/en-us/azure/postgresql/single-server/overview#deployment-models) + +### オプションの構成/手順 + +#### バックアップ構成を構成します (環境に応じてオプション) + +Azure Database for PostgreSQL は、既定でバックアップを取得します。バックアップ機能を手動で有効にする必要はありません。 + +バックアップの保持期間など、一部のバックアップ構成を変更する場合は、それを構成できます。詳細については公式ドキュメントを参照してください。 + +* [Backup and restore in Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-backup-restore) + +Scalar 製品データのバックアップ/復元方法の詳細については、次のドキュメントを参照してください。 + +* [Scalar 製品のバックアップ復元ガイド](BackupRestoreGuide.mdx) + +#### 監視を構成する (運用環境で推奨) + +Azure Database for PostgreSQL のネイティブ機能を使用して、その監視を構成できます。詳細については公式ドキュメントを参照してください。 + +* [Monitor metrics on Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-monitoring) + +メトリクスとログは、運用環境で問題が発生したときにそれを調査するのに役立つため、これをお勧めします。 + +#### パブリックアクセスを無効にする (運用環境で推奨) + +**Private access (VNet Integration)** を **Connectivity method** として構成できます。詳細については公式ドキュメントを参照してください。 + +* [Networking overview for Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-networking) + +次のように、AKS クラスター上の Scalar 製品ポッドからデータベースサーバーにアクセスできます。 + +* AKS クラスターと同じ VNet 上にデータベースサーバーを作成します。 +* [Virtual network peering](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview) を使用して、Scalar 製品デプロイのデータベースサーバー用の VNet と AKS クラスター用の VNet を接続します。(// TODO: この機能を Scalar 製品でテストする必要があります。) + +WAN 経由ではないプライベート内部接続によりシステムの安全性が高まるため、これをお勧めします。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/Envoy.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/Envoy.mdx new file mode 100644 index 00000000..4804ac8b --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/Envoy.mdx @@ -0,0 +1,157 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Envoy アラート + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +## EnvoyClusterDown + +これは最も重要なアラートであり、Envoy クラスターがリクエストを処理できないことを示します。このアラートは最優先で処理する必要があります。 + +### アラートの例 + +#### ファイアリング + +``` +[FIRING:1] EnvoyClusterDown - critical +Alert: Envoy cluster is down - critical + Description: Envoy cluster is down, no resquest can be process + Details: + • alertname: EnvoyClusterDown + • deployment: prod-scalardl-envoy +``` + +#### 解決済み + +``` +[RESOLVED] EnvoyClusterDown - critical +Alert: Envoy cluster is down - critical + Description: Envoy cluster is down, no resquest can be process + Details: + • alertname: EnvoyClusterDown + • deployment: prod-scalardl-envoy +``` + +### 必要なアクション + +* `kubectl get deployments. prod-scalardl-envoy` で設定されたレプリカの数を確認します。 +* `kubectl describe deployments. prod-scalardl-envoy` はデプロイメントを説明するために設定されたレプリカの数を確認します。 +* `kubectl get node -o wide` でノードのステータスを確認します。 +* ログサーバーをチェックして、モニターサーバー `/log/kubernetes//-/kube.log` 上の kubernetes ログで障害の根本原因を特定します。 +* 既知の問題があるかどうかをクラウドプロバイダーに確認してください。たとえば、Azure の彫像は[ここ](https://status.azure.com/en-us/status)で確認できます。 + +## EnvoyClusterDegraded + +このアラートは、Kubernetes クラスターが Envoy ポッドを開始できないかどうかを示します。これは、クラスターにデプロイメントを実行するための十分なリソースがない、または1つまたは複数の Kubernetes ノードが失われたことを意味します。 + +### アラートの例 + +#### ファイアリング + +``` +[FIRING:1] EnvoyClusterDegraded - warning +Alert: Envoy cluster is running in a degraded mode - warning + Description: Envoy cluster is running in a degraded mode, some of the Envoy pods are not healthy + Details: + • alertname: EnvoyClusterDegraded + • deployment: prod-scalardl-envoy +``` + +#### 解決済み + +``` +[RESOLVED] EnvoyClusterDegraded - warning +Alert: Envoy cluster is running in a degraded mode - warning + Description: Envoy cluster is running in a degraded mode, some of the Envoy pods are not healthy + Details: + • alertname: EnvoyClusterDegraded + • deployment: prod-scalardl-envoy +``` + +### 必要なアクション + +* ログサーバーをチェックして、モニターサーバー `/log/kubernetes//-/kube.log` または `kubectl logs prod-scalardl-envoy-xxxx-yyyy` 上の kubernetes ログに関する障害の根本原因を特定します。 +* `kubectl describe deployments prod-scalardl-envoy` で kubernetes のデプロイメントを確認します。 +* `kubectl get replicasets.apps` でレプリカセットを確認します。 +* `kubectl get node -o wide` でノードのステータスを確認します。 +* 既知の問題があるかどうかをクラウドプロバイダーに確認してください。たとえば、Azure の彫像は[ここ](https://status.azure.com/en-us/status)で確認できます。 + +## EnvoyPodsPending + +このアラートは、kubernetes クラスターが Envoy ポッドを開始できないかどうか、つまりクラスターに十分なリソースがないことを示します。 + +### アラートの例 + +#### ファイアリング + +``` +[FIRING:1] EnvoyPodsPending - warning +Alert: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default in pending status - warning + Description: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has been in pending status for more than 1 minute. + Details: + • alertname: EnvoyPodsPending + • deployment: prod-scalardl-envoy +``` + +#### 解決済み + +``` +[RESOLVED:1] EnvoyPodsPending - warning +Alert: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default in pending status - warning + Description: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has been in pending status for more than 1 minute. + Details: + • alertname: EnvoyPodsPending + • deployment: prod-scalardl-envoy +``` + +### 必要なアクション + +* ログ サーバーをチェックして、モニター サーバー `/log/kube//*.log` 上の kubernetes ログに関する障害の根本原因を特定します。 +* `kubectl describe pod prod-scalardl-envoy-xxxx-yyyy` で Kubernetes デプロイメントを確認します。 + +## EnvoyPodsError + +このアラートは、次のいずれかの理由で Kubernetes クラスターが Envoy ポッドを開始できないかどうかを知らせます。 + +* CrashLoopBackOff +* CreateContainerConfigError +* CreateContainerError +* ErrImagePull +* ImagePullBackOff +* InvalidImageName + +### アラートの例 + +#### ファイアリング + +``` +[FIRING:1] EnvoyPodsError - warning +Alert: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has an error status - warning + Description: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has been in pending status for more than 1 minutes. + Details: + • alertname: EnvoyPodsError + • deployment: prod-scalardl-envoy +``` + +#### 解決済み + +``` +[RESOLVED:1] EnvoyPodsError - warning +Alert: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has an error status - warning + Description: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has been in pending status for more than 1 minutes. + Details: + • alertname: EnvoyPodsError + • deployment: prod-scalardl-envoy +``` + +### 必要なアクション + +* `kubectl describe pod prod-scalardl-envoy-xxxx-yyyy` で Kubernetes デプロイメントを確認します。 +* ログ サーバーをチェックして、モニター サーバー `/log/kubernetes//-/kube.log` 上の kubernetes ログで障害の根本原因を特定します。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/Ledger.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/Ledger.mdx new file mode 100644 index 00000000..f23aac4a --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/Ledger.mdx @@ -0,0 +1,157 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsJapanese +--- + +# Ledger アラート + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +## LedgerClusterDown + +これは最も重要なアラートであり、Ledger クラスターがリクエストを処理できないことを示します。このアラートは最優先で処理する必要があります。 + +### アラートの例 + +#### ファイアリング + +``` +[FIRING:1] LedgerClusterDown - critical +Alert: Ledger cluster is down - critical + Description: Ledger cluster is down, no resquest can be process. + Details: + • alertname: LedgerClusterDown + • deployment: prod-scalardl-ledger +``` + +#### 解決済み + +``` +[RESOLVED] LedgerClusterDown - critical +Alert: Ledger cluster is down - critical + Description: Ledger cluster is down, no resquest can be process. + Details: + • alertname: LedgerClusterDown + • deployment: prod-scalardl-ledger +``` + +### 必要なアクション + +* `kubectl get deployments. prod-scalardl-ledger` で設定されたレプリカの数を確認します。 +* `kubectl describe deployments. prod-scalardl-ledger` はデプロイメントを説明するために設定されたレプリカの数を確認します。 +* `kubectl get node -o wide` でノードのステータスを確認します。 +* ログサーバーをチェックして、モニターサーバー `/log/kubernetes//-/kube.log` 上の kubernetes ログで障害の根本原因を特定します。 +* 既知の問題があるかどうかをクラウドプロバイダーに確認してください。たとえば、Azure の彫像は[ここ](https://status.azure.com/en-us/status)で確認できます。 + +## LedgerClusterDegraded + +このアラートは、Kubernetes クラスターが Ledger ポッドを開始できないかどうかを示します。これは、クラスターにデプロイメントを実行するための十分なリソースがない、または1つまたは複数の Kubernetes ノードが失われたことを意味します。 + +### アラートの例 + +#### ファイアリング + +``` +[FIRING:1] LedgerClusterDegraded - warning +Alert: Ledger cluster is running in a degraded mode - warning + Description: Ledger cluster is running in a degraded mode, some of the Ledger pods are not healthy. + Details: + • alertname: LedgerClusterDegraded + • deployment: prod-scalardl-ledger +``` + +#### 解決済み + +``` +[RESOLVED] LedgerClusterDegraded - warning +Alert: Ledger cluster is running in a degraded mode - warning + Description: Ledger cluster is running in a degraded mode, some of the Ledger pods are not healthy. + Details: + • alertname: LedgerClusterDegraded + • deployment: prod-scalardl-ledger +``` + +### 必要なアクション + +* ログサーバーをチェックして、モニターサーバー `/log/kubernetes//-/kube.log` 上の kubernetes ログに関する障害の根本原因を特定します。 +* `kubectl describe deployments prod-scalardl-ledger` で kubernetes のデプロイメントを確認します。 +* `kubectl get replicasets.apps` でレプリカセットを確認します。 +* `kubectl get node -o wide` でノードのステータスを確認します。 +* 既知の問題があるかどうかをクラウドプロバイダーに確認してください。たとえば、Azure の彫像は[ここ](https://status.azure.com/en-us/status)で確認できます。 + +## LedgerPodsPending + +このアラートは、kubernetes クラスターが Ledger ポッドを開始できないかどうか、つまりクラスターに十分なリソースがないことを示します。 + +### アラートの例 + +#### ファイアリング + +``` +[FIRING:1] LedgerPodsPending - warning +Alert: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default in pending status - warning + Description: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has been in pending status for more than 1 minute. + Details: + • alertname: LedgerPodsPending + • deployment: prod-scalardl-ledger +``` + +#### 解決済み + +``` +[RESOLVED:1] LedgerPodsPending - warning +Alert: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default in pending status - warning + Description: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has been in pending status for more than 1 minute. + Details: + • alertname: LedgerPodsPending + • deployment: prod-scalardl-ledger +``` + +### 必要なアクション + +* ログ サーバーをチェックして、モニター サーバー `/log/kubernetes//-/kube.log` 上の kubernetes ログに関する障害の根本原因を特定します。 +* `kubectl describe pod prod-scalardl-ledger-xxxx-yyyy` で Kubernetes デプロイメントを確認します。 + +## LedgerPodsError + +このアラートは、次のいずれかの理由で Kubernetes クラスターが Ledger ポッドを開始できないかどうかを知らせます。 + +* CrashLoopBackOff +* CreateContainerConfigError +* CreateContainerError +* ErrImagePull +* ImagePullBackOff +* InvalidImageName + +### アラートの例 + +#### ファイアリング + +``` +[FIRING:1] LedgerPodsError - warning +Alert: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has an error status - warning + Description: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has been in pending status for more than 1 minutes. + Details: + • alertname: LedgerPodsError + • deployment: prod-scalardl-ledger +``` + +#### 解決済み + +``` +[RESOLVED:1] LedgerPodsError - warning +Alert: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has an error status - warning + Description: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has been in pending status for more than 1 minutes. + Details: + • alertname: LedgerPodsError + • deployment: prod-scalardl-ledger +``` + +### 必要なアクション + +* `kubectl describe pod prod-scalardl-ledger-xxxx-yyyy` で Kubernetes デプロイメントを確認します。 +* ログ サーバーをチェックして、モニター サーバー +* `/log/kubernetes//-/kube.log` 上の kubernetes ログで障害の根本原因を特定します。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/README.mdx new file mode 100644 index 00000000..5f4ddb73 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/alerts/README.mdx @@ -0,0 +1,17 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Scalar アラート + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このセクションでは、アラートの種類と実行する必要があるアクションについて説明します。 + +* [Envoy アラート](Envoy.mdx) +* [Ledger アラート](Ledger.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png new file mode 100644 index 00000000..5ceef088 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Indirect_Mode.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Indirect_Mode.drawio.png new file mode 100644 index 00000000..feef0d81 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Indirect_Mode.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_In_Cluster.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_In_Cluster.drawio.png new file mode 100644 index 00000000..c6c9e06e Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_In_Cluster.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_Out_Cluster.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_Out_Cluster.drawio.png new file mode 100644 index 00000000..028fbe7c Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_Out_Cluster.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Account.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Account.drawio.png new file mode 100644 index 00000000..76e1aa16 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Account.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Namespace.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Namespace.drawio.png new file mode 100644 index 00000000..026b4a2d Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Namespace.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_VNet.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_VNet.drawio.png new file mode 100644 index 00000000..92eba96d Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_VNet.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Ledger.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Ledger.drawio.png new file mode 100644 index 00000000..9ee4fd22 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Ledger.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png new file mode 100644 index 00000000..00fef239 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Indirect_Mode.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Indirect_Mode.drawio.png new file mode 100644 index 00000000..db122e17 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Indirect_Mode.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_In_Cluster.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_In_Cluster.drawio.png new file mode 100644 index 00000000..c49fbe4f Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_In_Cluster.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_Out_Cluster.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_Out_Cluster.drawio.png new file mode 100644 index 00000000..d8dcde16 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_Out_Cluster.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Account.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Account.drawio.png new file mode 100644 index 00000000..1d9e7889 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Account.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Namespace.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Namespace.drawio.png new file mode 100644 index 00000000..bea249f3 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Namespace.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_VPC.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_VPC.drawio.png new file mode 100644 index 00000000..30d5af46 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_VPC.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Ledger.drawio.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Ledger.drawio.png new file mode 100644 index 00000000..ce5fd7b5 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Ledger.drawio.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-licensing/index.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-licensing/index.mdx new file mode 100644 index 00000000..aeb32f82 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-licensing/index.mdx @@ -0,0 +1,68 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 製品ライセンスキーの設定方法 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Scalar 製品を実行するには、`.properties` ファイルを作成し、製品のライセンスキーと証明書をそのファイルに追加する必要があります。 `.properties` ファイルで、使用している製品に基づいて次の構成のいずれかをコピーし、その内容を `.properties` ファイルに貼り付けて、`` をライセンスキーに置き換えます。 + +:::note + +ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)までご連絡ください。 + +::: + +:::warning + +試使用ライセンスを使用している場合は、ScalarDB をインターネットに接続する必要があります。試使用ライセンスが有効で期限が切れていないかどうかを確認するには、インターネット接続が必要です。 + +::: + +## ScalarDB Enterprise Edition + + + + ```properties + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem=-----BEGIN CERTIFICATE-----\nMIICKzCCAdKgAwIBAgIIBXxj3s8NU+owCgYIKoZIzj0EAwIwbDELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMSMwIQYDVQQDExplbnRlcnByaXNlLnNjYWxhci1sYWJzLmNv\nbTAeFw0yMzExMTYwNzExNTdaFw0yNDAyMTUxMzE2NTdaMGwxCzAJBgNVBAYTAkpQ\nMQ4wDAYDVQQIEwVUb2t5bzERMA8GA1UEBxMIU2hpbmp1a3UxFTATBgNVBAoTDFNj\nYWxhciwgSW5jLjEjMCEGA1UEAxMaZW50ZXJwcmlzZS5zY2FsYXItbGFicy5jb20w\nWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATJx5gvAr+GZAHcBpUvDFDsUlFo4GNw\npRfsntzwStIP8ac3dew7HT4KbGBWei0BvIthleaqpv0AEP7JT6eYAkNvo14wXDAO\nBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG\nA1UdEwEB/wQCMAAwHQYDVR0OBBYEFMIe+XuuZcnDX1c3TmUPlu3kNv/wMAoGCCqG\nSM49BAMCA0cAMEQCIGGlqKpgv+KW+Z1ZkjfMHjSGeUZKBLwfMtErVyc9aTdIAiAy\nvsZyZP6Or9o40x3l3pw/BT7wvy93Jm0T4vtVQH6Zuw==\n-----END CERTIFICATE----- + ``` + + + ```properties + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem=-----BEGIN CERTIFICATE-----\nMIICKzCCAdKgAwIBAgIIBXxj3s8NU+owCgYIKoZIzj0EAwIwbDELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMSMwIQYDVQQDExplbnRlcnByaXNlLnNjYWxhci1sYWJzLmNv\nbTAeFw0yMzExMTYwNzExNTdaFw0yNDAyMTUxMzE2NTdaMGwxCzAJBgNVBAYTAkpQ\nMQ4wDAYDVQQIEwVUb2t5bzERMA8GA1UEBxMIU2hpbmp1a3UxFTATBgNVBAoTDFNj\nYWxhciwgSW5jLjEjMCEGA1UEAxMaZW50ZXJwcmlzZS5zY2FsYXItbGFicy5jb20w\nWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATJx5gvAr+GZAHcBpUvDFDsUlFo4GNw\npRfsntzwStIP8ac3dew7HT4KbGBWei0BvIthleaqpv0AEP7JT6eYAkNvo14wXDAO\nBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG\nA1UdEwEB/wQCMAAwHQYDVR0OBBYEFMIe+XuuZcnDX1c3TmUPlu3kNv/wMAoGCCqG\nSM49BAMCA0cAMEQCIGGlqKpgv+KW+Z1ZkjfMHjSGeUZKBLwfMtErVyc9aTdIAiAy\nvsZyZP6Or9o40x3l3pw/BT7wvy93Jm0T4vtVQH6Zuw==\n-----END CERTIFICATE----- + ``` + + + ```properties + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem=-----BEGIN CERTIFICATE-----\nMIICIzCCAcigAwIBAgIIKT9LIGX1TJQwCgYIKoZIzj0EAwIwZzELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMR4wHAYDVQQDExV0cmlhbC5zY2FsYXItbGFicy5jb20wHhcN\nMjMxMTE2MDcxMDM5WhcNMjQwMjE1MTMxNTM5WjBnMQswCQYDVQQGEwJKUDEOMAwG\nA1UECBMFVG9reW8xETAPBgNVBAcTCFNoaW5qdWt1MRUwEwYDVQQKEwxTY2FsYXIs\nIEluYy4xHjAcBgNVBAMTFXRyaWFsLnNjYWxhci1sYWJzLmNvbTBZMBMGByqGSM49\nAgEGCCqGSM49AwEHA0IABBSkIYAk7r5FRDf5qRQ7dbD3ib5g3fb643h4hqCtK+lC\nwM4AUr+PPRoquAy+Ey2sWEvYrWtl2ZjiYyyiZw8slGCjXjBcMA4GA1UdDwEB/wQE\nAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIw\nADAdBgNVHQ4EFgQUbFyOWFrsjkkOvjw6vK3gGUADGOcwCgYIKoZIzj0EAwIDSQAw\nRgIhAKwigOb74z9BdX1+dUpeVG8WrzLTIqdIU0w+9jhAueXoAiEA6cniJ3qsP4j7\nsck62kHnFpH1fCUOc/b/B8ZtfeXI2Iw=\n-----END CERTIFICATE----- + ``` + + + +## ScalarDB Analytics with Spark + + + + ```apacheconf + spark.sql.catalog.scalardb_catalog.license.key + spark.sql.catalog.scalardb_catalog.license.cert_pem -----BEGIN CERTIFICATE-----\nMIICKzCCAdKgAwIBAgIIBXxj3s8NU+owCgYIKoZIzj0EAwIwbDELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMSMwIQYDVQQDExplbnRlcnByaXNlLnNjYWxhci1sYWJzLmNv\nbTAeFw0yMzExMTYwNzExNTdaFw0yNDAyMTUxMzE2NTdaMGwxCzAJBgNVBAYTAkpQ\nMQ4wDAYDVQQIEwVUb2t5bzERMA8GA1UEBxMIU2hpbmp1a3UxFTATBgNVBAoTDFNj\nYWxhciwgSW5jLjEjMCEGA1UEAxMaZW50ZXJwcmlzZS5zY2FsYXItbGFicy5jb20w\nWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATJx5gvAr+GZAHcBpUvDFDsUlFo4GNw\npRfsntzwStIP8ac3dew7HT4KbGBWei0BvIthleaqpv0AEP7JT6eYAkNvo14wXDAO\nBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG\nA1UdEwEB/wQCMAAwHQYDVR0OBBYEFMIe+XuuZcnDX1c3TmUPlu3kNv/wMAoGCCqG\nSM49BAMCA0cAMEQCIGGlqKpgv+KW+Z1ZkjfMHjSGeUZKBLwfMtErVyc9aTdIAiAy\nvsZyZP6Or9o40x3l3pw/BT7wvy93Jm0T4vtVQH6Zuw==\n-----END CERTIFICATE----- + ``` + + + ```apacheconf + spark.sql.catalog.scalardb_catalog.license.key + spark.sql.catalog.scalardb_catalog.license.cert_pem -----BEGIN CERTIFICATE-----\nMIICIzCCAcigAwIBAgIIKT9LIGX1TJQwCgYIKoZIzj0EAwIwZzELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMR4wHAYDVQQDExV0cmlhbC5zY2FsYXItbGFicy5jb20wHhcN\nMjMxMTE2MDcxMDM5WhcNMjQwMjE1MTMxNTM5WjBnMQswCQYDVQQGEwJKUDEOMAwG\nA1UECBMFVG9reW8xETAPBgNVBAcTCFNoaW5qdWt1MRUwEwYDVQQKEwxTY2FsYXIs\nIEluYy4xHjAcBgNVBAMTFXRyaWFsLnNjYWxhci1sYWJzLmNvbTBZMBMGByqGSM49\nAgEGCCqGSM49AwEHA0IABBSkIYAk7r5FRDf5qRQ7dbD3ib5g3fb643h4hqCtK+lC\nwM4AUr+PPRoquAy+Ey2sWEvYrWtl2ZjiYyyiZw8slGCjXjBcMA4GA1UdDwEB/wQE\nAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIw\nADAdBgNVHQ4EFgQUbFyOWFrsjkkOvjw6vK3gGUADGOcwCgYIKoZIzj0EAwIDSQAw\nRgIhAKwigOb74z9BdX1+dUpeVG8WrzLTIqdIU0w+9jhAueXoAiEA6cniJ3qsP4j7\nsck62kHnFpH1fCUOc/b/B8ZtfeXI2Iw=\n-----END CERTIFICATE----- + ``` + + diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/backup-and-restore-check-pauses.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/backup-and-restore-check-pauses.png new file mode 100644 index 00000000..d4f63157 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/backup-and-restore-check-pauses.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/backup-and-restore-create-pauses.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/backup-and-restore-create-pauses.png new file mode 100644 index 00000000..927f1910 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/backup-and-restore-create-pauses.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/dashboard-cluster.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/dashboard-cluster.png new file mode 100644 index 00000000..cdc5c5ab Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/dashboard-cluster.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/dashboard-pod-list.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/dashboard-pod-list.png new file mode 100644 index 00000000..ed247f0c Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/dashboard-pod-list.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/logs.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/logs.png new file mode 100644 index 00000000..1127bd71 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/logs.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/metrics.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/metrics.png new file mode 100644 index 00000000..e4f4d116 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/metrics.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/metrics2.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/metrics2.png new file mode 100644 index 00000000..6f76551b Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/images/metrics2.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/overview.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/overview.mdx new file mode 100644 index 00000000..70bb4920 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalar-manager/overview.mdx @@ -0,0 +1,58 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# Scalar Manager 概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Scalar Manager は、Kubernetes クラスタ環境内で ScalarDB の集中管理および監視ソリューションです。 +これらの製品に関連する運用タスクを、グラフィカルユーザーインターフェースに主要な機能を集約することで簡素化します。 + +## なぜ Scalar Manager なのか? + +Scalar Manager がリリースされる前は、ユーザーは ScalarDB のデプロイメントを管理および監視するために、さまざまなコマンドラインツールやサードパーティソリューションを個別に使用する必要がありました。 +例えば、ユーザーはデプロイメントのステータスを確認するために kubectl を使用し、メトリクスの監視には Prometheus スタック、ログ分析には Loki スタックを使用し、複数のデータベース間でトランザクションの一貫性を確保するために Scalar の独自の CLI ツールを使用して ScalarDB を一時停止していました。 +これらのツールの組み合わせは、習得の難易度が高く、統一されたインターフェースが欠けていたため、日常の管理タスクやトラブルシューティングの際に効率的なワークフローを提供できませんでした。 + +Scalar Manager は、これらの問題点を解消し、主要な機能を単一のユーザーフレンドリーな GUI に集約することで、管理および監視に必要な時間と労力を削減します。 +これにより、ユーザーはビジネスの開発や運用に集中できるようになります。 + +## 主な機能 + +Scalar Manager は、以下の機能をユーザーに提供します。 + +### 集中化されたクラスターの可視化 + +ユーザーは、クラスターの健康状態、pod ログ、ハードウェアの使用状況、リクエスト毎秒などのパフォーマンスメトリクス、Grafana ダッシュボードを介して可視化された詳細な時系列データについて、リアルタイムのメトリクスを迅速に取得できます。 + +![dashboard-cluster](images/dashboard-cluster.png) +![dashboard-pod-list](images/dashboard-pod-list.png) + +Pod ログとメトリクスは、リアルタイムまたは時系列で表示することができます。 + +![logs](images/logs.png) +![metrics](images/metrics2.png) + +### 簡素化されたジョブの一時停止管理 + +ユーザーは、トランザクションの一貫性を確保するために、一時停止ジョブを実行またはスケジュールし、スケジュールされたジョブを確認および管理し、直感的な GUI 内で一時停止状態を監視することができます。 + +![create-pauses](images/backup-and-restore-create-pauses.png) +![check-pauses](images/backup-and-restore-check-pauses.png) + +### ユーザー管理 + +Scalar Manager には現在、認証機能が含まれており、デプロイメントへの安全なアクセス制御が可能になっています。このシステムは、管理者が直感的なインターフェースを通じてユーザーアカウントの作成、変更、削除を行うことができるユーザー管理機能を提供しています。 + +### 認証と承認 + +ロール管理機能により、管理者はユーザーに特定の役割を定義して割り当て、Scalar Manager 環境内でのアクセス権限を制御することができます。この詳細な制御により、ユーザーは自分の責任に関連する機能にのみアクセスできるようになります。 + +### Grafana による統合認証 + +Scalar Manager は現在、Grafana インスタンスとシステムのその他のコンポーネント間でシームレスな認証統合を提供しています。このシングルサインオン機能により、複数の認証プロセスが不要になり、ユーザーエクスペリエンスが向上し、認証情報管理のオーバーヘッドを軽減することでセキュリティが強化されます。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/getting-started.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/getting-started.mdx new file mode 100644 index 00000000..f7de02b0 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/getting-started.mdx @@ -0,0 +1,102 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics with PostgreSQL をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDB Analytics with PostgreSQL の使用を開始する方法について説明します。ScalarDB Analytics with PostgreSQL がすでにインストールされており、必要なサービスがすべて実行されていることを前提としています。そのような環境がない場合は、[Docker を使用してローカル環境に ScalarDB Analytics with PostgreSQL をインストールする方法](./installation.mdx)の手順に従ってください。ScalarDB Analytics with PostgreSQL は PostgreSQL 経由でクエリを実行するため、PostgreSQL にクエリを送信するための `psql` クライアントまたは別の PostgreSQL クライアントがすでにあることも前提としています。 + +## ScalarDB Analytics with PostgreSQL とは + +ユニバーサルトランザクションマネージャーである ScalarDB は、主にトランザクションワークロードを対象としているため、リレーショナルクエリの限られたサブセットをサポートしています。 + +ScalarDB Analytics with PostgreSQL は、PostgreSQL とその外部データラッパー (FDW) 拡張機能を使用して、ScalarDB の機能を拡張し、ScalarDB が管理するデータに対する分析クエリを処理します。 + +ScalarDB Analytics with PostgreSQL は、主に PostgreSQL と Schema Importer の2つのコンポーネントで構成されています。 + +PostgreSQL はサービスとして実行され、ユーザーからのクエリを受け入れて処理します。FDW 拡張機能は、ScalarDB が管理するバックエンドストレージからデータを読み取るために使用されます。Schema Importer は、ScalarDB データベースのスキーマを PostgreSQL にインポートするツールです。これにより、ユーザーは PostgreSQL 側のテーブル (ScalarDB 側のテーブルと同一) を表示できます。 + +## ScalarDB データベースをセットアップする + +まず、ScalarDB Analytics with PostgreSQL で分析クエリを実行するには、1つ以上の ScalarDB データベースが必要です。独自の ScalarDB データベースがある場合は、このセクションをスキップして、代わりにそのデータベースを使用できます。[scalardb-samples/scalardb-analytics-postgresql-sample](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-analytics-postgresql-sample) プロジェクトを使用する場合は、プロジェクトディレクトリで次のコマンドを実行してサンプルデータベースを設定できます。 + +```console +docker compose run --rm schema-loader \ + -c /etc/scalardb.properties \ + --schema-file /etc/schema.json \ + --coordinator \ + --no-backup \ + --no-scaling +``` + +このコマンドは、DynamoDB、PostgreSQL、Cassandra で設定される [複数のストレージインスタンス](../multi-storage-transactions.mdx)を設定します。次に、これらのストレージにマップされる `dynamons`、`postgresns`、`cassandrans` の名前空間を作成し、[ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader/)を使用して `dynamons.customer`、`postgresns.orders`、`cassandrans.lineitem` のテーブルを作成します。 + +![マルチストレージの概要](./images/multi-storage-overview.png) + +次のコマンドを実行すると、作成されたテーブルにサンプルデータをロードできます。 + +```console +docker compose run --rm sample-data-loader +``` + +## PostgreSQL に ScalarDB 管理下のデータベースのスキーマをインポートする + +次に、分析クエリを処理する PostgreSQL に ScalarDB 管理下のデータベースのスキーマをインポートします。ScalarDB Analytics with PostgreSQL には、この目的のためのツールである Schema Importer が用意されています。このツールを使用すると、分析クエリを実行するために必要なすべての準備が整います。 + +```console +docker compose run --rm schema-importer \ + import \ + --config /etc/scalardb.properties \ + --host analytics \ + --port 5432 \ + --database test \ + --user postgres \ + --password postgres \ + --namespace cassandrans \ + --namespace postgresns \ + --namespace dynamons \ + --config-on-postgres-host /etc/scalardb.properties +``` + +独自の ScalarDB データベースを使用する場合は、`--config` および `--config-on-postgres-host` オプションを ScalarDB 設定ファイルに置き換え、`--namespace` オプションをインポートする ScalarDB 名前空間に置き換える必要があります。 + +これにより、ScalarDB データベース内のテーブルと同じ名前のテーブル (正確にはビュー) が作成されます。この例では、`dynamons.customer`、`postgresns.orders`、および `cassandrans.lineitem` のテーブルが作成されます。列定義も ScalarDB データベースと同一です。これらのテーブルは、FDW を使用して ScalarDB データベースの基盤となるストレージに接続された [外部テーブル](https://www.postgresql.org/docs/current/sql-createforeigntable.html)です。したがって、PostgreSQL 内のこれらのテーブルを ScalarDB データベース内のテーブルと同等と見なすことができます。 + +![インポートされたスキーマ](./images/imported-schema.png) + +## 分析クエリを実行する + +これで、ScalarDB データベース内の同じデータを読み取るすべてのテーブルが揃い、PostgreSQL でサポートされている任意の分析クエリを実行できるようになりました。クエリを実行するには、`psql` またはその他のクライアントを使用して PostgreSQL に接続してください。 + +```console +psql -U postgres -h localhost test +Password for user postgres: + +> select c_mktsegment, count(*) from dynamons.customer group by c_mktsegment; + c_mktsegment | count +--------------+------- + AUTOMOBILE | 4 + BUILDING | 2 + FURNITURE | 1 + HOUSEHOLD | 2 + MACHINERY | 1 +(5 rows) +``` + +サンプルデータと追加の実作業の詳細については、サンプルアプリケーションページを参照してください。 + +## 注意事項 + +### 分離レベル + +ScalarDB Analytics with PostgreSQL は、**Read Committed** 分離レベルを設定してデータを読み取ります。この分離レベルにより、読み取るデータが過去にコミットされていることが保証されますが、特定の時点で一貫性のあるデータを読み取ることができることは保証されません。 + +### 書き込み操作はサポートされていません + +ScalarDB Analytics with PostgreSQL は、読み取り専用クエリのみをサポートします。`INSERT`、`UPDATE`、およびその他の書き込み操作はサポートされていません。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/images/imported-schema.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/images/imported-schema.png new file mode 100644 index 00000000..1cf8fea3 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/images/imported-schema.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/images/multi-storage-overview.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/images/multi-storage-overview.png new file mode 100644 index 00000000..fc8df1cb Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/images/multi-storage-overview.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/installation.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/installation.mdx new file mode 100644 index 00000000..f2014fce --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/installation.mdx @@ -0,0 +1,65 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# Docker を使用してローカル環境に ScalarDB Analytics with PostgreSQL をインストールする方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、[Docker Compose](https://docs.docker.com/compose/) を使用して、Cassandra、PostgreSQL、および DynamoDB ローカルサーバーのマルチストレージバックエンドを使用して、ScalarDB Analytics with PostgreSQL を実行するローカル環境を設定する方法について説明します。 + +## 前提条件 + +- [Docker Engine](https://docs.docker.com/engine/) および [Docker Compose](https://docs.docker.com/compose/)。 + +プラットフォームに応じて、Docker ウェブサイトの手順に従ってください。 + +## ステップ 1. `scalardb-samples` リポジトリを複製します + +[scalardb-samples/scalardb-analytics-postgresql-sample](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-analytics-postgresql-sample) リポジトリは、ScalarDB Analytics with PostgreSQL を設定するためのサンプル設定を含むプロジェクトです。 + +scalardb-analytics-postgresql-sample アプリを実行するローカルマシン上の場所を決定します。次に、ターミナルを開き、`cd` コマンドを使用してその場所に移動し、次のコマンドを実行します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples.git +cd scalardb-samples/scalardb-analytics-postgresql-sample +``` + +## ステップ 2. ScalarDB Analytics with PostgreSQL サービスを起動する + +次のコマンドは、ScalarDB Analytics with PostgreSQL を提供する PostgreSQL インスタンスと、Docker コンテナ内の Cassandra、PostgreSQL、および DynamoDB ローカルのバックエンドサーバーを起動します。このコマンドを初めて実行すると、必要な Docker イメージが GitHub Container Registry からダウンロードされます。 + +```console +docker-compose up +``` + +コンテナをバックグラウンドで実行する場合は、`-d` (--detach) オプションを追加します。 + +```console +docker-compose up -d +``` + +すでに独自の ScalarDB データベースがあり、それをバックエンドサービスとして使用したい場合は、コンテナー内で追加のバックエンドサーバーを起動せずに、PostgreSQL インスタンスのみを起動できます。 + +```console +docker-compose up analytics +``` + +## ステップ 3. 分析クエリを実行する + +これで、必要なサービスがすべて実行されているはずです。分析クエリを実行するには、[ScalarDB Analytics with PostgreSQL をはじめよう](./getting-started.mdx)を参照してください。 + +## ステップ 4. ScalarDB Analytics with PostgreSQL サービスをシャットダウンする + +コンテナをシャットダウンするには、方法に応じて、ターミナルで次のいずれかを実行します。 + +- フォアグラウンドでコンテナを起動した場合は、`docker-compose` が実行されている場所で Ctrl+C を押します。 +- バックグラウンドでコンテナを起動した場合は、次のコマンドを実行します。 + +```console +docker-compose down +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/scalardb-fdw.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/scalardb-fdw.mdx new file mode 100644 index 00000000..d58baf21 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/scalardb-fdw.mdx @@ -0,0 +1,184 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# ScalarDB FDW + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB FDW は、[ScalarDB](https://www.scalar-labs.com/scalardb/) の外部データラッパー (FDW) を実装する PostgreSQL 拡張機能です。 + +ScalarDB FDW は、Java Native Interface を使用して、FDW 内のライブラリとして ScalarDB を直接利用し、ScalarDB のスキャン操作を介して外部データベースからデータを読み取ります。 + +## 前提条件 + +環境に次の前提条件が設定されている必要があります。 + +### JDK + +ScalarDB と互換性のあるバージョンの Java Development Kit (JDK) をインストールする必要があります。さらに、JDK インストールディレクトリを指す `JAVA_HOME` 環境変数を設定する必要があります。 + +これらの拡張機能は内部で Java Native Interface (JNI) を使用するため、ライブラリ検索パスに `libjvm.so` などの Java 仮想マシン (JVM) の動的ライブラリを含める必要があることに注意してください。 + +### PostgreSQL + +この拡張機能は PostgreSQL 13以降をサポートしています。PostgreSQL のインストール方法の詳細については、[サーバー管理](https://www.postgresql.org/docs/current/admin.html)の公式ドキュメントを参照してください。 + +## ビルドとインストール + +以下のコマンドを実行すると、この拡張機能をビルドしてインストールできます。 + +```console +make install +``` + +### 一般的なビルドエラー + +このセクションでは、発生する可能性のある一般的なビルドエラーについて説明します。 + +#### ld: -ljvm のライブラリが見つかりません + +通常、ビルドスクリプトは `libjvm.so` のパスを見つけ、それをライブラリ検索パスとして適切に設定しています。ただし、`ld: library not found for -ljvm` というエラーが発生した場合は、`libjvm.so` ファイルをデフォルトのライブラリ検索パスにコピーしてください。例: + +```console +ln -s //libjvm.so /usr/lib64/libjvm.so +``` + +## 使用方法 + +このセクションでは、ScalarDB の FDW の使用例と利用可能なオプションについて説明します。 + +### 例 + +次の例では、必要なコンポーネントをインストールして作成し、FDW 拡張機能を使用してクエリを実行する方法を示します。 + +#### 1. 拡張機能をインストールする + +拡張機能のインストール方法の詳細については、[ビルドとインストール](#ビルドとインストール)セクションを参照してください。 + +#### 2. 拡張機能を作成する + +拡張機能を作成するには、次のコマンドを実行します。 + +```sql +CREATE EXTENSION scalardb_fdw; +``` + +#### 3. 外部サーバーを作成する + +外部サーバーを作成するには、次のコマンドを実行します。 + +```sql +CREATE SERVER scalardb FOREIGN DATA WRAPPER scalardb_fdw OPTIONS ( + config_file_path '/path/to/scalardb.properties' +); +``` + +#### 4. ユーザーマッピングを作成する + +ユーザーマッピングを作成するには、次のコマンドを実行します。 + +```sql +CREATE USER MAPPING FOR PUBLIC SERVER scalardb; +``` + +#### 5. 外部テーブルを作成する + +外部テーブルを作成するには、次のコマンドを実行します。 + +```sql +CREATE FOREIGN TABLE sample_table ( + pk int, + ck1 int, + ck2 int, + boolean_col boolean, + bigint_col bigint, + float_col double precision, + double_col double precision, + text_col text, + blob_col bytea +) SERVER scalardb OPTIONS ( + namespace 'ns', + table_name 'sample_table' +); +``` + +#### 6. クエリを実行する + +クエリを実行するには、次のコマンドを実行します。 + +```sql +select * from sample_table; +``` + +### 使用可能なオプション + +ScalarDB FDW オブジェクトには次のオプションを設定できます。 + +#### `CREATE SERVER` + +ScalarDB 外部サーバーオブジェクトには次のオプションを設定できます。 + +| 名前 | 必須 | タイプ | 説明 | +| ------------------ | ------- | -------- | ------------------------------------------- | +| `config_file_path` | **はい** | `string` | ScalarDB 設定ファイルへのパス。 | +| `max_heap_size` | いいえ | `string` | JVM の最大ヒープサイズ。形式は `-Xmx` と同じです。 | + +#### `CREATE USER MAPPING` + +現在、`CREATE USER MAPPING` のオプションはありません。 + +#### `CREATE FOREIGN SERVER` + +ScalarDB 外部テーブルオブジェクトには次のオプションを設定できます。 + +| 名前 | 必須 | タイプ | 説明 | +| ------------ | ------- | -------- | -------------------------------------------- | +| `namespace` | **はい** | `string` | ScalarDB インスタンス内のテーブルの名前空間の名前。 | +| `table_name` | **はい** | `string` | ScalarDB インスタンス内のテーブルの名前。 | + +### データ型のマッピング + +| ScalarDB | PostgreSQL | +| -------- | ---------------- | +| BOOLEAN | boolean | +| INT | int | +| BIGINT | bigint | +| FLOAT | float | +| DOUBLE | double precision | +| TEXT | text | +| BLOB | bytea | + +## テスト + +このセクションでは、ScalarDB の FDW をテストする方法について説明します。 + +### テスト用の ScalarDB インスタンスの設定 + +ScalarDB の FDW をテストする前に、テストデータを含む実行中の ScalarDB インスタンスが必要です。次のコマンドを実行して、インスタンスを設定し、テストデータをロードできます。 + +```console +./test/setup.sh +``` + +インスタンスをリセットする場合は、次のコマンドを実行してから、上記のセットアップコマンドを再度実行します。 + +```console +./test/cleanup.sh +``` + +### 回帰テストを実行する + +FDW 拡張機能をインストールした後、次のコマンドを実行すると、回帰テストを実行できます。 + +```console +make installcheck +``` + +## 制限事項 + +- この拡張機能は、ScalarDB 管理データベースでの分析クエリ処理を可能にすることを目的としています。したがって、この拡張機能は ScalarDB からのデータの読み取りのみをサポートします。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/schema-importer.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/schema-importer.mdx new file mode 100644 index 00000000..76ff17e0 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-postgresql/schema-importer.mdx @@ -0,0 +1,69 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# Schema Importer + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +Schema Importer は、PostgreSQL を自動的に設定するための CLI ツールです。このツールを使用すると、PostgreSQL データベースに、ScalarDB インスタンスと同じデータベースオブジェクト (名前空間やテーブルなど) を持たせることができます。 + +Schema Importer は、ScalarDB 設定ファイルを読み取り、ScalarDB で定義されているテーブルのスキーマを取得し、対応する外部データラッパーの外部テーブルとビューをこの順序で作成します。詳細については、[ScalarDB Analytics with PostgreSQL をはじめよう](getting-started.mdx)を参照してください。 + +## Schema Importer のビルド + +[Gradle](https://gradle.org/) を使用して Schema Importer をビルドできます。Schema Importer をビルドするには、次のコマンドを実行します。 + +```console +./gradlew build +``` + +`java -jar` を使用して Schema Importer を起動できるように、Fat JAR ファイルを作成する必要があります。Fat JAR を作成するには、次のコマンドを実行します。 + + ```console + ./gradlew shadowJar + ``` + +fat JAR をビルドすると、`app/build/libs/` ディレクトリに fat JAR ファイルが作成されます。 + +## Schema Importer を実行する + +fat JAR ファイルを使用して Schema Importer を実行するには、次のコマンドを実行します。 + +```console +java -jar +``` +利用可能なオプションは次のとおりです。 + +| 名前 | 必須 | 説明 | デフォルト | +| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | ------------------------------- | +| `--config` | **はい** | ScalarDB 設定ファイルへのパス | | +| `--config-on-postgres-host` | No | PostgreSQL を実行しているホスト上の ScalarDB 設定ファイルへのパス | `--config` と同じ値が使用されます。 | +| `--namespace`, `-n` | **はい** | 分析インスタンスにインポートする名前空間。2つ以上の名前空間がある場合は、`--namespace` オプションを複数回指定できます。 | | +| `--host` | いいえ | PostgreSQL ホスト | localhost | +| `--port` | いいえ | PostgreSQL ポート | 5432 | +| `--database` | いいえ | PostgreSQL ポート | postgres | +| `--user` | いいえ | PostgreSQL ユーザー | postgres | +| `--password` | いいえ | PostgreSQL パスワード | | +| `--debug` | いいえ | デバッグモードを有効にする | | + + +## Schema Importer のテスト + +Schema Importer をテストするには、次のコマンドを実行します。 + +```console +./gradlew test +``` + +## Schema Importer の Docker イメージをビルドする + +Schema Importer の Docker イメージをビルドするには、次のコマンドを実行します。`` は、使用する Schema Importer のタグバージョンに置き換えます。 + +```console +docker build -t ghcr.io/scalar-labs/scalardb-analytics-postgresql-schema-importer: -f ./app/Dockerfile . +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics-spark/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-spark/README.mdx similarity index 100% rename from i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics-spark/README.mdx rename to i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-spark/README.mdx diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics-spark/version-compatibility.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-spark/version-compatibility.mdx similarity index 100% rename from i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics-spark/version-compatibility.mdx rename to i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics-spark/version-compatibility.mdx diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/README.mdx new file mode 100644 index 00000000..f6ff390e --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/README.mdx @@ -0,0 +1,23 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +**ScalarDB Analytics** は ScalarDB の分析コンポーネントです。ScalarDB と同様に、 PostgreSQL や MySQL などの RDBMS から Cassandra や DynamoDB などの NoSQL データベースまで、多様なデータソースを単一の論理データベースに統合します。ScalarDB は複数のデータベースにわたる強力なトランザクション一貫性を持つ運用ワークロードに焦点を当てているのに対し、ScalarDB Analytics は分析ワークロード向けに最適化されています。複雑な結合処理、集計処理、ウィンドウ関数などの幅広いクエリをサポートしています。ScalarDB Analytics は、ScalarDB で管理されているデータソースと管理されていないデータソースの両方でシームレスに動作し、様々なデータセットにわたる高度な分析クエリを可能にします。 + +現在のバージョンの ScalarDB Analytics は、実行エンジンとして **Apache Spark** を活用しています。Sparkカスタムカタログを利用することで、ScalarDB で管理されているデータソースと管理されていないデータソースの統合ビューを提供します。ScalarDB Analytics を使用すると、これらのデータソースのテーブルを Spark のテーブルとして扱うことができます。これにより、任意の Spark SQL クエリをシームレスに実行できます。例えば、Cassandra に保存されているテーブルと PostgreSQL のテーブルを結合して、簡単にクロスデータベース分析を実行することができます。 + + + +## さらに詳しく + +* サンプルデータセットとアプリケーションを使用した ScalarDB Analytics の使用方法のチュートリアルについては、[ScalarDB Analytics の使用を開始する](../scalardb-samples/scalardb-analytics-spark-sample/README.mdx)を参照してください。 +* サポートされている Spark と Scala のバージョンについては、[ScalarDB Analytics with Spark のバージョン互換性](./run-analytical-queries.mdx#version-compatibility)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/deployment.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/deployment.mdx new file mode 100644 index 00000000..d265a001 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/deployment.mdx @@ -0,0 +1,222 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# パブリッククラウド環境への ScalarDB Analytics のデプロイ + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、パブリッククラウド環境に ScalarDB Analytics をデプロイする方法について説明します。ScalarDB Analytics は現在、実行エンジンとして Apache Spark を使用しており、Amazon EMR や Databricks などのパブリッククラウドプロバイダーが提供するマネージド Spark サービスをサポートしています。 + +## サポートされているマネージド Spark サービスとそのアプリケーションタイプ + +ScalarDB Analytics は以下のマネージド Spark サービスとアプリケーションタイプをサポートしています。 + +| パブリッククラウドサービス | Spark Driver | Spark Connect | JDBC | +| -------------------------- | ------------ | ------------- | ---- | +| Amazon EMR (EMR on EC2) | ✅ | ✅ | ❌ | +| Databricks | ✅ | ❌ | ✅ | + +## 設定とデプロイ + +パブリッククラウド環境を選択し、指示に従って ScalarDB Analytics を設定およびデプロイしてください。 + + + + +

Amazon EMR の使用

+ +ScalarDB Analytics を通じて分析クエリを実行するために Amazon EMR(EMR on EC2)を使用できます。EMR クラスターを起動する基本については、[AWS EMR on EC2 ドキュメント](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan.html)を参照してください。 + +

ScalarDB Analytics の設定

+ +ScalarDB Analytics を有効にするには、EMR クラスターを起動するときにソフトウェア設定に次の構成を追加する必要があります。括弧内の内容を必ず置き換えてください: + +```json +[ + { + "Classification": "spark-defaults", + "Properties": { + "spark.jars.packages": "com.scalar-labs:scalardb-analytics-spark-all-_:", + "spark.sql.catalog.": "com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog", + "spark.sql.extensions": "com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions", + "spark.sql.catalog..license.cert_pem": "", + "spark.sql.catalog..license.key": "", + + // 以下にデータソースの設定を続けてください + } + } +] +``` + +括弧内の内容は以下のように変更してください: + +- ``: Spark のバージョン +- ``: Spark のビルドに使用される Scala のバージョン +- ``: ScalarDB Analytics のバージョン +- ``: カタログの名前 +- ``: PEM エンコードされたライセンス証明書 +- ``: ライセンスキー + +詳細については、[ScalarDB Analytics のセットアップのための Spark 設定](./run-analytical-queries.mdx#scalardb-analytics-のセットアップのための-spark-設定)を参照してください。 + +

Spark Driver を介した分析クエリの実行

+ +EMR Spark クラスターが起動した後、ssh を使用して EMR クラスターのプライマリノードに接続し、Spark アプリケーションを実行できます。Spark Driver アプリケーションの作成方法の詳細については、[Spark Driver アプリケーション](./run-analytical-queries.mdx?spark-application-type=spark-driver#spark-アプリケーションの開発)を参照してください。 + +

Spark Connect を介した分析クエリの実行

+ +Spark Connect を使用して、起動した EMR クラスターを使用して Spark アプリケーションをリモートで実行できます。 + +まず、[Spark Driver アプリケーション](./run-analytical-queries.mdx?spark-application-type=spark-driver#spark-アプリケーションの開発)と同じようにソフトウェア設定を構成する必要があります。また、Spark Connect を有効にするために次の設定も行う必要があります。 + +
Spark Connect サーバーのインバウンドトラフィックを許可する
+ +1. Spark Connect サーバーのインバウンドトラフィックを許可するセキュリティグループを作成します(デフォルトはポート15001)。 +2. 「Amazon EMR サービスロール」のロールがセキュリティグループを EMR クラスターのプライマリノードにアタッチできるようにします。 +3. EMR クラスターを起動するときに、「追加のセキュリティグループ」としてセキュリティグループを EMR クラスターのプライマリノードに追加します。 + +
ブートストラップアクションを介した Spark Connect サーバーの起動
+ +1. 次のように Spark Connect サーバーを起動するためのスクリプトファイルを作成します: + +```bash +#!/usr/bin/env bash + +set -eu -o pipefail + +cd /var/lib/spark + +sudo -u spark /usr/lib/spark/sbin/start-connect-server.sh --packages org.apache.spark:spark-connect_:,com.scalar-labs:scalardb-analytics-spark-all-_: +``` + +括弧内の内容は以下のように変更してください: + +- ``: Spark インストールに合わせた Scala のメジャーおよびマイナーバージョン(2.12 や 2.13 など) +- ``: 使用している Spark の完全なバージョン(3.5.3 など) +- ``: 使用している Spark のメジャーおよびマイナーバージョン(3.5 など) +- ``: ScalarDB Analytics のバージョン + +2. スクリプトファイルを S3 にアップロードします。 +3. 「Amazon の EMR 用 EC2 インスタンスプロファイル」のロールがS3にアップロードされたスクリプトファイルにアクセスできるようにします。 +4. EMR クラスターを起動するときに、アップロードされたスクリプトファイルを「ブートストラップアクション」に追加します。 + +
分析クエリの実行
+ +Spark Connect サーバーのリモート URL(`sc://:15001`)を使用して、どこからでも Spark Connect を介して Spark アプリケーションを実行できます。 + +Spark Connect を使用した Spark アプリケーションの作成方法の詳細については、[Spark Connect アプリケーション](./run-analytical-queries.mdx?spark-application-type=spark-connect#spark-アプリケーションの開発)を参照してください。 + +
+ +

Databricks の使用

+ +ScalarDB Analytics を通じて分析クエリを実行するために Databricks を使用できます。 + +:::note + +Databricks は Apache Spark の修正版を提供しており、オリジナルの Apache Spark とは異なる動作をすることに注意してください。 + +::: + +

Databricks クラスターの起動

+ +ScalarDB Analytics は Databricks の汎用クラスターとジョブコンピュートクラスターで動作します。クラスターを起動するとき、ScalarDB Analytics を有効にするために以下のようにクラスターを設定する必要があります: + +1. Databricks CLI を使用して、ライセンス証明書とライセンスキーをクラスターに保存します。 + +```console +databricks secrets create-scope scalardb-analytics-secret # 任意のシークレットスコープ名を使用できます +cat license_key.json | databricks secrets put-secret scalardb-analytics-secret license-key +cat license_cert.pem | databricks secrets put-secret scalardb-analytics-secret license-cert +``` + +:::note + +Databricks CLI のインストールと使用方法の詳細については、[Databricks CLI ドキュメント](https://docs.databricks.com/en/dev-tools/cli/index.html)を参照してください。 + +::: + +2. クラスターモードに「No isolation shared」を選択します。(これは必須です。ScalarDB Analytics はこのクラスターモードでのみ動作します。) +3. Spark 3.4以降をサポートする適切な Databricks ランタイムバージョンを選択します。 +4. 「詳細オプション」>「Spark 設定」を以下のように設定します。`` を使用したいカタログの名前に置き換えてください: + +``` +spark.sql.catalog. com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog +spark.sql.extensions com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions +spark.sql.catalog..license.key {{secrets/scalardb-analytics-secret/license-key}} +spark.sql.catalog..license.cert_pem {{secrets/scalardb-analytics-secret/license-pem}} +``` + +:::note + +データソースも設定する必要があります。詳細については、[ScalarDB Analytics のセットアップのための Spark 設定](./run-analytical-queries.mdx#scalardb-analytics-のセットアップのための-spark-設定)を参照してください。 + +::: + +:::note + +前のステップで異なるシークレット名を指定した場合は、上記の設定でシークレット名を必ず置き換えてください。 + +::: + +5. Maven 依存関係として、起動したクラスターに ScalarDB Analytics のライブラリを追加します。ライブラリの追加方法の詳細については、[Databricks クラスターライブラリドキュメント](https://docs.databricks.com/en/libraries/cluster-libraries.html)を参照してください。 + +

Spark Driver を介した分析クエリの実行

+ +適切に設定された Databricks クラスターで Spark アプリケーションを Databricks Notebook または Databricks Jobs で実行して、ScalarDB Analytics 内のテーブルにアクセスできます。Spark アプリケーションを実行するには、Pyspark、Scala、または Spark SQL アプリケーションを Databricks Notebook に移行するか、Databricks Jobs を使用して Spark アプリケーションを実行できます。ScalarDB Analytics は Notebook、Python、JAR、および SQL のタスクタイプで動作します。 + +Databricks Jobs の使用方法の詳細については、[Databricks Jobs ドキュメント](https://docs.databricks.com/en/jobs/index.html)を参照してください。 + +

JDBC ドライバーを介した分析クエリの実行

+ +Databricks はクラスター上で SQL ジョブを実行するための JDBC をサポートしています。以下のような追加設定を行うことで、ScalarDB Analytics で SQL を使用して Spark アプリケーションを実行できます: + +1. Maven リポジトリから ScalarDB Analytics ライブラリの JAR ファイルをダウンロードします。 +2. JAR ファイルを Databricks ワークスペースにアップロードします。 +3. Maven 依存関係の代わりに、ライブラリとして JAR ファイルをクラスターに追加します。 +4. 以下のように初期化スクリプトを作成します。`` を Databricks ワークスペース内の JAR ファイルのパスに置き換えてください: + +```bash +#!/bin/bash + +# Target directories +TARGET_DIRECTORIES=("/databricks/jars" "/databricks/hive_metastore_jars") +JAR_PATH=" + +# Copy the JAR file to the target directories +for TARGET_DIR in "${TARGET_DIRECTORIES[@]}"; do + mkdir -p "$TARGET_DIR" + cp "$JAR_PATH" "$TARGET_DIR/" +done +``` + +5. 初期化スクリプトを Databricks ワークスペースにアップロードします。 +6. クラスターを起動するときに、「詳細オプション」>「初期化スクリプト」にスクリプトを追加します。 + +クラスターが起動した後、クラスター詳細ページの「詳細オプション」>「JDBC/ODBC」タブでクラスターの JDBC URL を取得できます。 + +JDBC を使用して Databricks クラスターに接続するには、アプリケーションの依存関係に Databricks JDBC ドライバーを追加する必要があります。例えば、Gradle を使用している場合は、`build.gradle` ファイルに次の依存関係を追加できます: + +```groovy +implementation("com.databricks:databricks-jdbc:0.9.6-oss") +``` + +その後、JDBC アプリケーションで一般的なように、JDBC URL(``)を使用して JDBC で Databricks クラスターに接続できます。 + +```java +Class.forName("com.databricks.client.jdbc.Driver"); +String url = ""; +Connection conn = DriverManager.getConnection(url) +``` + +Databricks で JDBC を使用する方法の詳細については、[Databricks JDBC ドライバードキュメント](https://docs.databricks.com/en/integrations/jdbc/index.html)を参照してください。 + +
+
diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/design.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/design.mdx new file mode 100644 index 00000000..f5608580 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/design.mdx @@ -0,0 +1,394 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics の設計 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Analytics は ScalarDB の分析コンポーネントです。ScalarDB と同様に、PostgreSQL や MySQL などの RDBMS から Cassandra や DynamoDB などの NoSQL データベースまで、多様なデータソースを単一の論理データベースに統合します。これにより、複数のデータベースにわたってシームレスに分析クエリを実行することができます。 + +ScalarDB Analytics は主にユニバーサルデータカタログとクエリエンジンの2つのコンポーネントから構成されています。 + +- **ユニバーサルデータカタログ**は、複数のカタログを処理する柔軟なメタデータ管理システムです。カタログはデータソースとビューの独立した論理的なグループ化を提供し、多様なデータ環境の体系的な管理を可能にします。 +- **クエリエンジン**はユニバーサルデータカタログに対してクエリを実行します。ScalarDB Analyticsは基盤となるデータソースとのインターフェースを行うための適切なデータコネクタを提供します。 + +ScalarDB Analyticsはデータカタログとクエリエンジンが分離されたデカップルドアーキテクチャを採用しています。この設計により、拡張可能なアーキテクチャを通じて様々な既存のクエリエンジンとの統合が可能になります。その結果、特定の要件に基づいて異なるクエリエンジンを選択し、同じデータカタログに対してクエリを実行することができます。 + +## ユニバーサルデータカタログ + +ユニバーサルデータカタログはいくつかのレベルで設定され、以下のように構造化されています: + +```mermaid +graph TD + C[Catalog] --> D[Data Source] + C[Catalog] --> D2[Data Source] + subgraph " " + D --> N[Namespace] + D --> N2[Namespace] + N --> T[Table] + N --> T2[Table] + T --> TC[Column] + T --> TC2[Column] + D2 + end + + C --> VN[View Namespace] + C --> VN2[View Namespace] + subgraph " " + VN --> V[View] + VN --> V2[View] + V --> VC[Column] + V --> VC2[Column] + VN2 + end +``` + +これらのレベルの定義は以下の通りです: + +- **Catalog**(カタログ)はすべてのデータソース情報を含むフォルダです。例えば、分析データ用の `analytics_catalog` と日常業務用の `operational_catalog` という2つのカタログを持つことができます。 +- **Data source**(データソース)は接続する各データソースを表します。各データソースについて、以下のような重要な情報を保存します: + - データソースの種類(PostgreSQL、Cassandra など) + - 接続方法(接続詳細とパスワード) + - データソースがサポートする特別な機能(トランザクションなど) +- **Namespace**(名前空間)はデータソース内の関連するテーブルをグループ化するサブフォルダのようなものです。PostgreSQL ではスキーマ、Cassandra ではキースペースと呼ばれます。フォルダ内のフォルダのように、複数レベルの名前空間を持つことができます。 +- **Table**(テーブル)は実際のデータが存在する場所です。各テーブルについて、以下を追跡します: + - どのような列があるか + - 各列がどのタイプのデータを格納できるか + - 列が空(null)になれるかどうか +- **View namespace**(ビュー名前空間)はビュー用の特別なフォルダです。1つのデータソースに紐づく通常の名前空間とは異なり、ビュー名前空間は複数のデータソースと同時に連携できます。 +- **View**(ビュー)は以下のことができる仮想テーブルのようなものです: + - データをよりシンプルな方法で表示する(ScalarDB テーブルの技術的な列を隠すなど) + - SQLクエリを使用して異なるソースからデータを結合する + - 各ビューはテーブルと同様に、特定のタイプと空の値に関するルールを持つ独自の列を持っています。 + +### サポートされているデータ型 + +ScalarDB Analytics は様々なデータソースにわたって幅広いデータ型をサポートしています。ユニバーサルデータカタログはこれらのデータ型を共通のタイプセットにマッピングし、ソース間の互換性と一貫性を確保します。以下のリストは ScalarDB Analytics でサポートされているデータ型を示しています: + +- `BYTE` +- `SMALLINT` +- `INT` +- `BIGINT` +- `FLOAT` +- `DOUBLE` +- `DECIMAL` +- `TEXT` +- `BLOB` +- `BOOLEAN` +- `DATE` +- `TIME` +- `TIMESTAMP` +- `TIMESTAMPTZ` +- `DURATION` +- `INTERVAL` + +### データソース別のカタログ情報マッピング + +データソースを ScalarDB Analytics に登録する際、データソースのカタログ情報(名前空間、テーブル、列など)が解決され、ユニバーサルデータカタログに登録されます。データソースのカタログ情報を解決するために、データソース側の特定のオブジェクトがユニバーサルデータカタログオブジェクトにマッピングされます。このマッピングはカタログレベルのマッピングとデータ型マッピングの2つの部分で構成されています。以下のセクションでは、ScalarDB Analytics が各データソースからカタログレベルとデータ型をユニバーサルデータカタログにどのようにマッピングするかを説明します。 + +#### カタログレベルのマッピング + +カタログレベルのマッピングは、データソースから名前空間名、テーブル名、および列名をユニバーサルデータカタログへのマッピングです。各データソースでのカタログレベルのマッピングを確認するには、データソースを選択してください。 + + + + ScalarDB のカタログ情報は ScalarDB Analytics によって自動的に解決されます。カタログレベルのオブジェクトは以下のようにマッピングされます: + + - ScalarDB 名前空間は名前空間にマッピングされます。したがって、ScalarDB データソースの名前空間は常に単一レベルで、名前空間名のみで設定されます。 + - ScalarDB テーブルはテーブルにマッピングされます。 + - ScalarDB 列は列にマッピングされます。 + + + + + PostgreSQL のカタログ情報は ScalarDB Analytics によって自動的に解決されます。カタログレベルのオブジェクトは以下のようにマッピングされます: + + - PostgreSQL スキーマは名前空間にマッピングされます。したがって、PostgreSQL データソースの名前空間は常に単一レベルで、スキーマ名のみで設定されます。 + - ユーザー定義スキーマのみが名前空間にマッピングされます。以下のシステムスキーマは無視されます: + - `information_schema` + - `pg_catalog` + - PostgreSQL テーブルはテーブルにマッピングされます。 + - PostgreSQL 列は列にマッピングされます。 + + + + MySQL のカタログ情報は ScalarDB Analytics によって自動的に解決されます。カタログレベルのオブジェクトは以下のようにマッピングされます: + + - MySQL データベースは名前空間にマッピングされます。したがって、MySQL データソースの名前空間は常に単一レベルで、データベース名のみで設定されます。 + - ユーザー定義データベースのみが名前空間にマッピングされます。以下のシステムデータベースは無視されます: + - `mysql` + - `sys` + - `information_schema` + - `performance_schema` + - MySQL テーブルはテーブルにマッピングされます。 + - MySQL 列は列にマッピングされます。 + + + + Oracle のカタログ情報は ScalarDB Analytics によって自動的に解決されます。カタログレベルのオブジェクトは以下のようにマッピングされます: + + - Oracle スキーマは名前空間にマッピングされます。したがって、Oracle データソースの名前空間は常に単一レベルで、スキーマ名のみで設定されます。 + - ユーザー定義スキーマのみが名前空間にマッピングされます。以下のシステムスキーマは無視されます: + - `ANONYMOUS` + - `APPQOSSYS` + - `AUDSYS` + - `CTXSYS` + - `DBSNMP` + - `DGPDB_INT` + - `DBSFWUSER` + - `DVF` + - `DVSYS` + - `GGSYS` + - `GSMADMIN_INTERNAL` + - `GSMCATUSER` + - `GSMROOTUSER` + - `GSMUSER` + - `LBACSYS` + - `MDSYS` + - `OJVMSYS` + - `ORDDATA` + - `ORDPLUGINS` + - `ORDSYS` + - `OUTLN` + - `REMOTE_SCHEDULER_AGENT` + - `SI_INFORMTN_SCHEMA` + - `SYS` + - `SYS$UMF` + - `SYSBACKUP` + - `SYSDG` + - `SYSKM` + - `SYSRAC` + - `SYSTEM` + - `WMSYS` + - `XDB` + - `DIP` + - `MDDATA` + - `ORACLE_OCM` + - `XS$NULL` + + + + SQL Server のカタログ情報は ScalarDB Analytics によって自動的に解決されます。カタログレベルのオブジェクトは以下のようにマッピングされます: + + - SQL Server データベースとスキーマは共に名前空間にマッピングされます。したがって、SQL Server データソースの名前空間は常に二段階で、データベース名とスキーマ名で構成されます。 + - ユーザー定義データベースのみが名前空間にマッピングされます。以下のシステムデータベースは無視されます: + - `sys` + - `guest` + - `INFORMATION_SCHEMA` + - `db_accessadmin` + - `db_backupoperator` + - `db_datareader` + - `db_datawriter` + - `db_ddladmin` + - `db_denydatareader` + - `db_denydatawriter` + - `db_owner` + - `db_securityadmin` + - ユーザー定義スキーマのみが名前空間にマッピングされます。以下のシステムスキーマは無視されます: + - `master` + - `model` + - `msdb` + - `tempdb` + - SQL Server テーブルはテーブルにマッピングされます。 + - SQL Server 列は列にマッピングされます。 + + + + DynamoDB はスキーマレスであるため、DynamoDB データソースを登録する際に以下のような形式のJSONを使用してカタログ情報を明示的に指定する必要があります: + + ```json + { + "namespaces": [ + { + "name": "", + "tables": [ + { + "name": "", + "columns": [ + { + "name": "", + "type": "" + }, + ... + ] + }, + ... + ] + }, + ... + ] + } + ``` + + 指定した JSON では、任意の名前空間名を使用できますが、テーブル名は DynamoDB のテーブル名と一致する必要があり、列名と型は DynamoDB のフィールド名と型と一致する必要があります。 + + + + +#### データ型マッピング + +基盤となるデータソースのネイティブデータ型は ScalarDB Analytics のデータ型にマッピングされます。各データソースでのデータ型マッピングを確認するには、データソースを選択してください。 + + + + | **ScalarDB データ型** | **ScalarDB Analytics データ型** | + |:------------------------------|:---------------------------------| + | `BOOLEAN` | `BOOLEAN` | + | `INT` | `INT` | + | `BIGINT` | `BIGINT` | + | `FLOAT` | `FLOAT` | + | `DOUBLE` | `DOUBLE` | + | `TEXT` | `TEXT` | + | `BLOB` | `BLOB` | + | `DATE` | `DATE` | + | `TIME` | `TIME` | + | `TIMESTAMP` | `TIMESTAMP` | + | `TIMESTAMPTZ` | `TIMESTAMPTZ` | + + + | **PostgreSQL データ型** | **ScalarDB Analytics データ型** | + |:------------------------------|:---------------------------------| + | `integer` | `INT` | + | `bigint` | `BIGINT` | + | `real` | `FLOAT` | + | `double precision` | `DOUBLE` | + | `smallserial` | `SMALLINT` | + | `serial` | `INT` | + | `bigserial` | `BIGINT` | + | `char` | `TEXT` | + | `varchar` | `TEXT` | + | `text` | `TEXT` | + | `bpchar` | `TEXT` | + | `boolean` | `BOOLEAN` | + | `bytea` | `BLOB` | + | `date` | `DATE` | + | `time` | `TIME` | + | `time with time zone` | `TIME` | + | `time without time zone` | `TIME` | + | `timestamp` | `TIMESTAMP` | + | `timestamp with time zone` | `TIMESTAMPTZ` | + | `timestamp without time zone` | `TIMESTAMP` | + + + | **MySQL データ型** | **ScalarDB Analytics データ型** | + |:-----------------------|:---------------------------------| + | `bit` | `BOOLEAN` | + | `bit(1)` | `BOOLEAN` | + | `bit(x)` if *x >= 2* | `BLOB` | + | `tinyint` | `SMALLINT` | + | `tinyint(1)` | `BOOLEAN` | + | `boolean` | `BOOLEAN` | + | `smallint` | `SMALLINT` | + | `smallint unsigned` | `INT` | + | `mediumint` | `INT` | + | `mediumint unsigned` | `INT` | + | `int` | `INT` | + | `int unsigned` | `BIGINT` | + | `bigint` | `BIGINT` | + | `float` | `FLOAT` | + | `double` | `DOUBLE` | + | `real` | `DOUBLE` | + | `char` | `TEXT` | + | `varchar` | `TEXT` | + | `text` | `TEXT` | + | `binary` | `BLOB` | + | `varbinary` | `BLOB` | + | `blob` | `BLOB` | + | `date` | `DATE` | + | `time` | `TIME` | + | `datetime` | `TIMESTAMP` | + | `timestamp` | `TIMESTAMPTZ` | + + + | **Oracle データ型** | **ScalarDB Analytics データ型** | + |:-----------------------------------|:---------------------------------| + | `NUMBER` if *scale = 0* | `BIGINT` | + | `NUMBER` if *scale > 0* | `DOUBLE` | + | `FLOAT` if *precision ≤ 53* | `DOUBLE` | + | `BINARY_FLOAT` | `FLOAT` | + | `BINARY_DOUBLE` | `DOUBLE` | + | `CHAR` | `TEXT` | + | `NCHAR` | `TEXT` | + | `VARCHAR2` | `TEXT` | + | `NVARCHAR2` | `TEXT` | + | `CLOB` | `TEXT` | + | `NCLOB` | `TEXT` | + | `BLOB` | `BLOB` | + | `BOOLEAN` | `BOOLEAN` | + | `DATE` | `DATE` | + | `TIMESTAMP` | `TIMESTAMPTZ` | + | `TIMESTAMP WITH TIME ZONE` | `TIMESTAMPTZ` | + | `TIMESTAMP WITH LOCAL TIME ZONE` | `TIMESTAMP` | + | `RAW` | `BLOB` | + + + | **SQL Server データ型** | **ScalarDB Analytics データ型** | + |:---------------------------|:---------------------------------| + | `bit` | `BOOLEAN` | + | `tinyint` | `SMALLINT` | + | `smallint` | `SMALLINT` | + | `int` | `INT` | + | `bigint` | `BIGINT` | + | `real` | `FLOAT` | + | `float` | `DOUBLE` | + | `float(n)` if *n ≤ 24* | `FLOAT` | + | `float(n)` if *n ≥ 25* | `DOUBLE` | + | `binary` | `BLOB` | + | `varbinary` | `BLOB` | + | `char` | `TEXT` | + | `varchar` | `TEXT` | + | `nchar` | `TEXT` | + | `nvarchar` | `TEXT` | + | `ntext` | `TEXT` | + | `text` | `TEXT` | + | `date` | `DATE` | + | `time` | `TIME` | + | `datetime` | `TIMESTAMP` | + | `datetime2` | `TIMESTAMP` | + | `smalldatetime` | `TIMESTAMP` | + | `datetimeoffset` | `TIMESTAMPTZ` | + + + | **DynamoDB データ型** | **ScalarDB Analytics データ型** | + |:-------------------------|:---------------------------------| + | `Number` | `BYTE` | + | `Number` | `SMALLINT` | + | `Number` | `INT` | + | `Number` | `BIGINT` | + | `Number` | `FLOAT` | + | `Number` | `DOUBLE` | + | `Number` | `DECIMAL` | + | `String` | `TEXT` | + | `Binary` | `BLOB` | + | `Boolean` | `BOOLEAN` | + +:::warning + +ScalarDB Analytics に指定されたデータ型として `Number` 型のフィールド値が解析可能であることが必要です。例えば、`Number` 型のフィールドに対応する列が `INT` 型として指定されている場合、その値は整数でなければなりません。値が整数でない場合、クエリの実行時にエラーが発生します。 + +::: + + + + +## クエリエンジン + +クエリエンジンはユニバーサルデータカタログとともに独立したコンポーネントであり、ユニバーサルデータカタログに登録されているデータソースに対してクエリを実行し、結果をユーザーに返す責任を持ちます。ScalarDB Analytics は現在、組み込みのクエリエンジンを提供していません。代わりに、通常はクエリエンジンのプラグインとして提供される既存のクエリエンジンと統合されるように設計されています。 + +クエリを実行するとき、ScalarDB Analytics クエリエンジンプラグインは以下のように動作します。 + +1. ユニバーサルデータカタログ API を呼び出してカタログメタデータを取得します(データソースの場所、テーブルオブジェクト識別子、テーブルスキーマなど)。 +2. カタログメタデータを使用してデータソースコネクタをセットアップします。 +3. カタログメタデータに基づいてクエリ最適化情報をクエリエンジンに提供します。 +4. データソースコネクタを使用してデータソースからデータを読み取ります。 + +ScalarDB Analytics はこれらのプロセスを内部的に管理します。通常のクエリ実行と同じ方法で、クエリエンジン API を使用してユニバーサルデータカタログに対してクエリを実行するだけで済みます。 + +ScalarDB Analytics は現在、クエリエンジンとして Apache Spark をサポートしています。ScalarDB Analytics を Spark で使用する方法の詳細については、[ScalarDB Analytics を通じた分析クエリの実行](./run-analytical-queries.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/run-analytical-queries.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/run-analytical-queries.mdx new file mode 100644 index 00000000..afff7813 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/run-analytical-queries.mdx @@ -0,0 +1,456 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics を通じた分析クエリの実行 + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このガイドでは、ScalarDB Analytics アプリケーションの開発方法について説明します。アーキテクチャと設計の詳細については、[ScalarDB Analytics の設計](./design.mdx)を参照してください。 + +ScalarDB Analytics は現在、実行エンジンとして Spark を使用し、Spark カスタムカタログプラグインを提供することによって、ScalarDB で管理されているデータソースと管理されていないデータソースの統合ビューを Spark テーブルとして提供します。これにより、任意の Spark SQL クエリをシームレスに実行できます。 + +## 準備 + +このセクションでは、前提条件、ScalarDB Analytics セットアップのための Spark 設定、および ScalarDB Analytics 依存関係の追加について説明します。 + +### 前提条件 + +ScalarDB Analytics は Apache Spark 3.4以降で動作します。まだ Spark をインストールしていない場合は、[Apache Spark のウェブサイト](https://spark.apache.org/downloads.html)から Spark ディストリビューションをダウンロードしてください。 + +:::note + +Apache Spark は Scala 2.12 または Scala 2.13 でビルドされています。ScalarDB Analytics は両方のバージョンをサポートしています。後で適切なバージョンの ScalarDB Analytics を選択できるように、使用しているバージョンを確認してください。詳細については、[バージョン互換性](#バージョン互換性)を参照してください。 + +::: + +### ScalarDB Analytics のセットアップのための Spark 設定 + +以下のセクションでは、ScalarDB Analytics で利用可能なすべての設定オプションについて説明します。 + +- ScalarDB Analytics の Spark との統合方法 +- データソースの接続とアクセス方法 +- ライセンス情報の提供方法 + +実践的なシナリオでの設定例については、[サンプルアプリケーション設定](../scalardb-samples/scalardb-analytics-spark-sample/README.mdx#scalardb-analytics-の設定)を参照してください。 + +#### Spark プラグインの設定 + +| 設定キー名 | 必須 | 説明 | +|:-----------------------------------|:------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `spark.jars.packages` | いいえ | 必要な依存関係の Maven 座標をカンマ区切りで指定します。使用する ScalarDB Analytics パッケージを含める必要があります。含めない場合は、Spark アプリケーションの実行時にコマンドライン引数として指定します。ScalarDB Analytics の Maven 座標の詳細については、[ScalarDB Analytics 依存関係の追加](#scalardb-analytics-依存関係の追加)を参照してください。 | +| `spark.sql.extensions` | はい | `com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions` を設定する必要があります。 | +| `spark.sql.catalog.` | はい | `com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog` を設定する必要があります。 | + +`` には任意の名前を指定できます。設定全体で同じカタログ名を使用するようにしてください。 + +#### ライセンスの設定 + +| 設定キー名 | 必須 | 説明 | +|:-----------------------------------------------------|:-----|:------------------------------------------------------------------------------------------------------------------------| +| `spark.sql.catalog..license.key` | はい | ScalarDB Analytics のライセンスキーの JSON 文字列 | +| `spark.sql.catalog..license.cert_pem` | はい | ScalarDB Analytics ライセンスの PEM エンコードされた証明書の文字列。`cert_pem` または `cert_path` のいずれかを設定する必要があります。 | +| `spark.sql.catalog..license.cert_path` | はい | ScalarDB Analytics ライセンスの PEM エンコードされた証明書へのパス。`cert_pem` または `cert_path` のいずれかを設定する必要があります。 | + +#### データソースの設定 + +ScalarDB Analytics は複数のタイプのデータソースをサポートしています。各タイプには特定の設定パラメータが必要です: + + + + +:::note + +ScalarDB Analytics は ScalarDB をデータソースとしてサポートしています。この表では、ScalarDB をデータソースとして設定する方法について説明します。 + +::: + +| 設定キー名 | 必須 | 説明 | +|:------------------------------------------------------------------------------|:-----|:----------------------------| +| `spark.sql.catalog..data_source..type` | はい | 常に `scalardb` を設定します | +| `spark.sql.catalog..data_source..config_path` | はい | ScalarDB の設定ファイルへのパス | + +:::tip + +`` には任意の名前を使用できます。 + +::: + + + + +| 設定キー名 | 必須 | 説明 | +|:---------------------------------------------------------------------------|:------|:-----------------------| +| `spark.sql.catalog..data_source..type` | はい | 常に `mysql` を設定します | +| `spark.sql.catalog..data_source..host` | はい | MySQL サーバーのホスト名 | +| `spark.sql.catalog..data_source..port` | はい | MySQL サーバーのポート番号 | +| `spark.sql.catalog..data_source..username` | はい | MySQL サーバーのユーザー名 | +| `spark.sql.catalog..data_source..password` | はい | MySQL サーバーのパスワード | +| `spark.sql.catalog..data_source..database` | いいえ | 接続するデータベースの名前 | + +:::tip + +`` には任意の名前を使用できます。 + +::: + + + + +| 設定キー名 | 必須 | 説明 | +|:---------------------------------------------------------------------------|:-----|:---------------------------------------------| +| `spark.sql.catalog..data_source..type` | はい | 常に `postgresql` または `postgres` を設定します | +| `spark.sql.catalog..data_source..host` | はい | PostgreSQL サーバーのホスト名 | +| `spark.sql.catalog..data_source..port` | はい | PostgreSQL サーバーのポート番号 | +| `spark.sql.catalog..data_source..username` | はい | PostgreSQL サーバーのユーザー名 | +| `spark.sql.catalog..data_source..password` | はい | PostgreSQL サーバーのパスワード | +| `spark.sql.catalog..data_source..database` | はい | 接続するデータベースの名前 | + +:::tip + +`` には任意の名前を使用できます。 + +::: + + + + +| 設定キー名 | 必須 | 説明 | +|:-------------------------------------------------------------------------------|:-----|:------------------------| +| `spark.sql.catalog..data_source..type` | はい | 常に `oracle` を設定します | +| `spark.sql.catalog..data_source..host` | はい | Oracle サーバーのホスト名 | +| `spark.sql.catalog..data_source..port` | はい | Oracle サーバーのポート番号 | +| `spark.sql.catalog..data_source..username` | はい | Oracle サーバーのユーザー名 | +| `spark.sql.catalog..data_source..password` | はい | Oracle サーバーのパスワード | +| `spark.sql.catalog..data_source..service_name` | はい | Oracle サーバーのサービス名 | + +:::tip + +`` には任意の名前を使用できます。 + +::: + + + + +| 設定キー名 | 必須 | 説明 | +|:---------------------------------------------------------------------------|:-------|:--------------------------------------------------------------------------------------------| +| `spark.sql.catalog..data_source..type` | はい | 常に `sqlserver` または `mssql` を設定します | +| `spark.sql.catalog..data_source..host` | はい | SQL Server のホスト名 | +| `spark.sql.catalog..data_source..port` | はい | SQL Server のポート番号 | +| `spark.sql.catalog..data_source..username` | はい | SQL Server のユーザー名 | +| `spark.sql.catalog..data_source..password` | はい | SQL Server のパスワード | +| `spark.sql.catalog..data_source..database` | いいえ | 接続するデータベースの名前 | +| `spark.sql.catalog..data_source..secure` | いいえ | SQL Server への接続にセキュアな接続を使用するかどうか。セキュアな接続を使用する場合は `true` を設定します。 | + +:::tip + +`` には任意の名前を使用できます。 + +::: + + + + +| 設定キー名 | 必須 | 説明 | +|:---------------------------------------------------------------------------|:--------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------| +| `spark.sql.catalog..data_source..type` | はい | 常に `dynamodb` を設定します | +| `spark.sql.catalog..data_source..region` | `region` または `endpoint` のいずれかを設定する必要があります | DynamoDB インスタンスの AWS リージョン | +| `spark.sql.catalog..data_source..endpoint` | `region` または `endpoint` のいずれかを設定する必要があります | DynamoDB インスタンスの AWS エンドポイント | +| `spark.sql.catalog..data_source..schema` | はい | カタログのスキーマを表す JSON オブジェクト。形式の詳細については、[カタログレベルのマッピング](./design.mdx#カタログレベルのマッピング)を参照してください。 | + +:::tip + +`` には任意の名前を使用できます。 + +::: + + + + +#### 設定例 + +以下は、複数のデータソースを持つ `scalardb` という名前のカタログを設定する ScalarDB Analytics の設定例です: + +```conf +# Sparkプラグインの設定 +spark.jars.packages com.scalar-labs:scalardb-analytics-spark-all-_: +spark.sql.extensions com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions +spark.sql.catalog.scalardb com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog + +# ライセンスの設定 +spark.sql.catalog.scalardb.license.key +spark.sql.catalog.scalardb.license.cert_pem + +# データソースの設定 +spark.sql.catalog.scalardb.data_source.scalardb.type scalardb +spark.sql.catalog.scalardb.data_source.scalardb.config_path /path/to/scalardb.properties + +spark.sql.catalog.scalardb.data_source.mysql_source.type mysql +spark.sql.catalog.scalardb.data_source.mysql_source.host localhost +spark.sql.catalog.scalardb.data_source.mysql_source.port 3306 +spark.sql.catalog.scalardb.data_source.mysql_source.username root +spark.sql.catalog.scalardb.data_source.mysql_source.password password +spark.sql.catalog.scalardb.data_source.mysql_source.database mydb +``` + +括弧内の内容は以下のように変更する必要があります: + +- ``: ScalarDB Analytics のライセンスキー +- ``: ScalarDB Analytics ライセンスの PEM エンコードされた証明書 +- ``: 使用している Spark のメジャーおよびマイナーバージョン (例: 3.4) +- ``: Spark インストールに対応する Scala のメジャーおよびマイナーバージョン (例: 2.12 または 2.13) +- ``: ScalarDB Analytics のバージョン + +### ScalarDB Analytics 依存関係の追加 + +ScalarDB Analytics は Maven Central Repository でホストされています。パッケージ名は `scalardb-analytics-spark-all-_:` で、以下の通りです: + +- ``: 使用している Spark のメジャーおよびマイナーバージョン (例: 3.4) +- ``: Spark インストールに対応する Scala のメジャーおよびマイナーバージョン (例: 2.12 または 2.13) +- ``: ScalarDB Analytics のバージョン + +バージョンの互換性の詳細については、[バージョン互換性](#バージョン互換性)を参照してください。 + +プロジェクトのビルド設定を設定することで、この依存関係をプロジェクトに追加できます。例えば、Gradle を使用している場合は、`build.gradle` ファイルに以下を追加できます: + +```groovy +dependencies { + implementation 'com.scalar-labs:scalardb-analytics-spark-all-_:' +} +``` + +:::note + +Gradle の Shadow プラグインや Maven の Shade プラグインなどを使用して、アプリケーションを単一の fat JAR ファイルにバンドルする場合は、使用しているプラグインに応じて `provided` や `shadow` などの適切な configuration を選択して、fat JAR ファイルから ScalarDB Analytics を除外する必要があります。 + +::: + +## Spark アプリケーションの開発 + +このセクションでは、Java を使用して ScalarDB Analytics を使用する Spark アプリケーションを開発する方法について説明します。 + +ScalarDB Analytics を使用した Spark アプリケーションの開発には3つの方法があります: + +1. **Spark ドライバーアプリケーション:** クラスター内で実行される従来のSparkアプリケーション +2. **Spark Connect アプリケーション:** Spark Connectプロトコルを使用するリモートアプリケーション +3. **JDBC アプリケーション:** JDBCインターフェースを使用するリモートアプリケーション + +:::note + +環境によっては、上記のすべての方法を使用できない場合があります。サポートされる機能とデプロイメントオプションの詳細については、[サポートされるマネージド Spark サービスとそのアプリケーションタイプ](./deployment.mdx#サポートされるマネージド-spark-サービスとそのアプリケーションタイプ)を参照してください。 + +::: + +これらのすべての方法で、同じテーブル識別子形式を使用して ScalarDB Analytics のテーブルを参照できます。ScalarDB Analytics がデータソースからカタログ情報をマッピングする方法の詳細については、[データソース別のカタログ情報マッピング](./design.mdx#データソース別のカタログ情報マッピング)を参照してください。 + + + + +ScalarDB Analytics には一般的に使用される `SparkSession` クラスを使用できます。また、YARN、Kubernetes、スタンドアロン、ローカルモードなど、Spark がサポートするあらゆるタイプのクラスターデプロイメントを使用できます。 + +ScalarDB Analytics のテーブルからデータを読み取るには、通常のSparkテーブルを読み取る場合と同じように `spark.sql` または `spark.read.table` 関数を使用できます。 + +まず、Java プロジェクトをセットアップする必要があります。例えば、Gradle を使用している場合は、`build.gradle` ファイルに以下を追加できます: + +```groovy +dependencies { + implementation 'com.scalar-labs:scalardb-analytics-spark-_:' +} +``` + +以下は Spark ドライバーアプリケーションの例です: + +```java +import org.apache.spark.sql.SparkSession; + +public class MyApp { + public static void main(String[] args) { + // SparkSessionを作成 + try (SparkSession spark = SparkSession.builder().getOrCreate()) { + // ScalarDB Analyticsのテーブルからデータを読み取る + spark.sql("SELECT * FROM my_catalog.my_data_source.my_namespace.my_table").show(); + } + } +} +``` + +その後、`spark-submit` コマンドを使用してアプリケーションをビルドして実行できます。 + +:::note + +通常の Spark アプリケーションと同様に、アプリケーションの fat JAR ファイルをビルドする必要がある場合があります。 + +::: + +```console +spark-submit --class MyApp --master local[*] my-spark-application-all.jar +``` + +:::tip + +`spark-sql` や `spark-shell` などの Spark が提供する他の CLI ツールを使用して、ScalarDB Analytics のテーブルを操作することもできます。 + +::: + + + + +[Spark Connect](https://spark.apache.org/spark-connect/) を使用して ScalarDB Analytics と対話できます。Spark Connect を使用することで、リモートの Spark クラスターにアクセスし、Spark ドライバーアプリケーションと同じ方法でデータを読み取ることができます。以下では、Spark Connect の使用方法について簡単に説明します。 + +まず、リモートの Spark クラスターで以下のコマンドを実行して、Spark Connect サーバーを起動する必要があります: + +```console +./sbin/start-connect-server.sh --packages org.apache.spark:spark-connect_:,com.scalar-labs:scalardb-analytics-spark-all-_: +``` + +括弧内の内容は以下のように変更する必要があります: + +- ``: Spark インストールに対応する Scala のメジャーおよびマイナーバージョン (例: 2.12 または 2.13) +- ``: 使用している Spark の完全なバージョン (例: 3.5.3) +- ``: 使用している Spark のメジャーおよびマイナーバージョン (例 3.5) +- ``: ScalarDB Analytics のバージョン + +:::note + +パッケージのバージョンは、使用している Spark と ScalarDB Analytics のバージョンと一致する必要があります。 + +::: + +また、アプリケーションに Spark Connect クライアントパッケージを含める必要があります。例えば、Gradle を使用している場合は、`build.gradle` ファイルに以下を追加できます: + +```kotlin +implementation("org.apache.spark:spark-connect-client-jvm_2.12:3.5.3") +``` + +その後、Spark Connect クライアントアプリケーションを作成してサーバーに接続し、データを読み取ることができます。 + +```java +import org.apache.spark.sql.SparkSession; + +public class MyApp { + public static void main(String[] args) { + try (SparkSession spark = SparkSession.builder() + .remote("sc://:") + .getOrCreate()) { + + // ScalarDB Analyticsのテーブルからデータを読み取る + spark.sql("SELECT * FROM my_catalog.my_data_source.my_namespace.my_table").show(); + } + } +} +``` + +以下のコマンドを実行して、Spark Connect クライアントアプリケーションを通常の Java アプリケーションとして実行できます: + +```console +java -jar my-spark-connect-client.jar +``` + +Spark Connect の使用方法の詳細については、[Spark Connect のドキュメント](https://spark.apache.org/docs/latest/spark-connect-overview.html)を参照してください。 + + + + +残念ながら、Spark Thrift JDBC サーバーは ScalarDB Analytics に必要な Spark の機能をサポートしていないため、Apache Spark 環境でJDBCを使用して ScalarDB Analytics からデータを読み取ることはできません。JDBC アプリケーションについてここで言及しているのは、一部のマネージド Spark サービスが JDBC インターフェースを介して Spark クラスターと対話する異なる方法を提供しているためです。詳細については、[サポートされているマネージド Spark サービスとそのアプリケーションタイプ](./deployment.mdx#サポートされているマネージド-spark-サービスとそのアプリケーションタイプ)を参照してください。 + + + + +## カタログ情報のマッピング + +ScalarDB Analytics は、データソース、名前空間、テーブル、列を含む独自のカタログを管理します。この情報は自動的に Spark カタログにマッピングされます。このセクションでは、ScalarDB Analytics がカタログ情報を Spark カタログにマッピングする方法について説明します。 + +データソース内の情報が ScalarDB Analytics カタログにマッピングされる方法の詳細については、[データソース別のカタログ情報マッピング](./design.mdx#データソース別のカタログ情報マッピング)を参照してください。 + +### カタログレベルのマッピング + +ScalarDB Analytics カタログの各カタログレベルオブジェクトは、Spark カタログにマッピングされます。以下の表は、カタログレベルがどのようにマッピングされるかを示しています: + +#### データソーステーブル + +ScalarDB Analytics カタログのデータソースのテーブルは、Spark テーブルにマッピングされます。ScalarDB Analytics テーブルに対応する Spark テーブルの識別子には以下の形式が使用されます: + +```console +... +``` + +括弧内の内容は以下の通りです: + +- ``: カタログの名前 +- ``: データソースの名前 +- ``: 名前空間の名前。名前空間が複数レベルある場合は、ドット (`.`) で区切って連結されます +- ``: テーブルの名前 + +例えば、`my_catalog` という名前の ScalarDB カタログに、`my_data_source` という名前のデータソースと `my_schema` という名前のスキーマがある場合、そのスキーマ内の `my_table` という名前のテーブルを `my_catalog.my_data_source.my_schema.my_table` として参照できます。 + +#### ビュー + +ScalarDB Analytics のビューは、ビューではなく Spark カタログのテーブルとして提供されます。ScalarDB Analytics ビューに対応する Spark テーブルの識別子には以下の形式が使用されます: + +```console +.view.. +``` + +括弧内の内容は以下の通りです: + +- ``: カタログの名前 +- ``: ビュー名前空間の名前。ビュー名前空間が複数レベルある場合は、ドット (`.`) で区切って連結されます +- ``: ビューの名前 + +例えば、`my_catalog` という名前の ScalarDB カタログと `my_view_namespace` という名前のビュー名前空間がある場合、その名前空間内の `my_view` という名前のビューを `my_catalog.view.my_view_namespace.my_view` として参照できます。 + +:::note + +データソーステーブル識別子との競合を避けるため、`view` が接頭辞として付けられます。 + +::: + +##### WAL 解釈ビュー + +[ScalarDB Analytics の設計](./design.mdx)で説明されているように、ScalarDB Analytics は WAL 解釈ビューと呼ばれる特別なタイプのビューを提供します。これらのビューは、ScalarDB データソースのテーブルに対して自動的に作成され、テーブル内の WAL メタデータを解釈することでユーザーフレンドリーなビューを提供します。 + +元の ScalarDB テーブルのデータソース名と名前空間の名前が WAL 解釈ビューのビュー名前空間の名前として使用されるため、`my_data_source` という名前のデータソースの `my_namespace` という名前の名前空間にある `my_table` という名前の ScalarDB テーブルがある場合、そのテーブルの WAL 解釈ビューを `my_catalog.view.my_data_source.my_namespace.my_table` として参照できます。 + +### データ型マッピング + +ScalarDB Analytics は、カタログ内のデータ型を Spark データ型にマッピングします。以下の表は、データ型がどのようにマッピングされるかを示しています: + +| ScalarDB データ型 | Spark データ型 | +|:----------------|:-------------------| +| `BYTE` | `Byte` | +| `SMALLINT` | `Short` | +| `INT` | `Integer` | +| `BIGINT` | `Long` | +| `FLOAT` | `Float` | +| `DOUBLE` | `Double` | +| `DECIMAL` | `Decimal` | +| `TEXT` | `String` | +| `BLOB` | `Binary` | +| `BOOLEAN` | `Boolean` | +| `DATE` | `Date` | +| `TIME` | `TimestampNTZ` | +| `TIMESTAMP` | `TimestampNTZ` | +| `TIMESTAMPTZ` | `Timestamp` | +| `DURATION` | `CalendarInterval` | +| `INTERVAL` | `CalendarInterval` | + +## バージョン互換性 + +Spark と Scala は異なるマイナーバージョン間で互換性がない場合があるため、ScalarDB Analytics は様々な Spark と Scala バージョン向けに `scalardb-analytics-spark-all-_` という形式で異なるアーティファクトを提供しています。使用している Spark と Scala のバージョンに合わせてアーティファクトを選択してください。例えば、Spark 3.5 と Scala 2.13 を使用している場合は、`scalardb-analytics-spark-all-3.5_2.13` を指定する必要があります。 + +Java バージョンに関しては、ScalarDB Analytics は Java 8以降をサポートしています。 + +以下は、ScalarDB Analytics の各バージョンでサポートされている Spark と Scalar のバージョンのリストです。 + +| ScalarDB Analytics バージョン | ScalarDB バージョン | サポートされている Spark バージョン | サポートされている Scala バージョン | 最小 Java バージョン | +|:----------------------------|:------------------|:-------------------------------|:-------------------------------|:-------------------| +| 3.15 | 3.15 | 3.5, 3.4 | 2.13, 2.12 | 8 | +| 3.14 | 3.14 | 3.5, 3.4 | 2.13, 2.12 | 8 | +| 3.12 | 3.12 | 3.5, 3.4 | 2.13, 2.12 | 8 | diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics/version-compatibility.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/version-compatibility.mdx similarity index 100% rename from i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/current/scalardb-analytics/version-compatibility.mdx rename to i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-analytics/version-compatibility.mdx diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-benchmarks/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-benchmarks/README.mdx new file mode 100644 index 00000000..42b3d318 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-benchmarks/README.mdx @@ -0,0 +1,239 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB ベンチマークツール + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、ScalarDB のベンチマークツールを実行する方法について説明します。データベースベンチマークは、一連の標準データセットワークロードに対するデータベースのパフォーマンスを評価するのに役立ちます。 + +## ベンチマークのワークロード + +- TPC-C +- YCSB (ワークロード A、C、および F) +- マルチストレージ YCSB (ワークロード C および F) + - この YCSB バリアントは、ScalarDB を使用するマルチストレージ環境用です。 + - マルチストレージ YCSB のワーカーは、2つの名前空間 (`ycsb_primary` と `ycsb_secondary`) で同じ数の読み取り操作と書き込み操作を実行します。 + +## 前提条件 + +- 次の Java Development Kit (JDK) のいずれか: + - [Oracle JDK](https://www.oracle.com/java/technologies/downloads/) LTS バージョン 8 + - [OpenJDK](https://openjdk.org/install/) LTS バージョン 8 +- Gradle +- [Kelpie](https://github.com/scalar-labs/kelpie) + - Kelpie は、システムのベンチマークや検証などのエンドツーエンドのテストを実行するためのフレームワークです。 [Kelpie Releases](https://github.com/scalar-labs/kelpie) から最新バージョンを入手し、アーカイブファイルを解凍します。 +- ベンチマークツールを実行するクライアント +- ターゲットデータベース + - ScalarDB がサポートするデータベースの一覧については、[Databases](../requirements.mdx#データベース) を参照してください。 + +:::note + +現在、ベンチマークツールを実行するときに使用できるのは JDK 8のみです。 + +::: + +## ベンチマークツールをセットアップする + +次のセクションでは、ベンチマークツールのセットアップ方法について説明します。 + +### ScalarDB ベンチマークリポジトリをクローンする + +**ターミナル**を開き、次のコマンドを実行して ScalarDB ベンチマークリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-benchmarks +``` + +次に、下記のコマンドを実行して、ベンチマークファイルが含まれるディレクトリに移動します。 + +```console +cd scalardb-benchmarks +``` + +### ツールをビルドする + +ベンチマークツールをビルドするには、次のコマンドを実行します。 + +```console +./gradlew shadowJar +``` + +### スキーマをロードする + +初期データをロードする前に、[ScalarDB Schema Loader](../schema-loader.mdx) を使用してテーブルを定義する必要があります。ScalarDB Schema Loader は、[ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) ページからダウンロードできます。ScalarDB へのアクセス方法に基づいて Schema Loader を選択してください。 +- **ScalarDB コアライブラリ (コミュニティエディション) を使用する場合:** 使用している ScalarDB のバージョンに応じて `scalardb-schema-loader-.jar` を選択します。次に、`.jar` ファイルを `scalardb-benchmarks` ルートディレクトリに保存します。 +- **ScalarDB Cluster (エンタープライズエディション) を使用する場合:** 使用している ScalarDB Cluster のバージョンに応じて `scalardb-cluster-schema-loader--all.jar` を選択します。次に、`.jar` ファイルを `scalardb-benchmarks` ルート ディレクトリに保存します。 + +さらに、Java CRUD インターフェースを介して ScalarDB にアクセスするためのプロパティファイルも必要です。ScalarDB プロパティファイルの設定の詳細については、[ScalarDB 設定](../configurations.mdx)または [ScalarDB Cluster クライアント設定](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#クライアント設定)を参照してください。 + +スキーマを適用してプロパティファイルを設定したら、ベンチマークを選択し、指示に従ってテーブルを作成します。 + + + + TPC-C ベンチマーク用のテーブル ([`tpcc-schema.json`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/tpcc-schema.json)) を作成するには、山括弧内の内容を説明に従って置き換えて、次のコマンドを実行します。 + + ```console + java -jar scalardb-schema-loader-.jar --config -f tpcc-schema.json --coordinator + ``` + + ScalarDB Cluster を使用している場合は、代わりに次のコマンドを実行します。 + + ```console + java -jar scalardb-cluster-schema-loader--all.jar --config -f tpcc-schema.json --coordinator + ``` + + + YCSB ベンチマーク用のテーブル ([`ycsb-schema.json`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/ycsb-schema.json)) を作成するには、山括弧内の内容を説明に従って置き換えて、次のコマンドを実行します。 + + ```console + java -jar scalardb-schema-loader-.jar --config -f ycsb-schema.json --coordinator + ``` + + ScalarDB Cluster を使用している場合は、代わりに次のコマンドを実行します。 + + ```console + java -jar scalardb-cluster-schema-loader--all.jar --config -f ycsb-schema.json --coordinator + ``` + + + マルチストレージ YCSB ベンチマーク用のテーブル ([`ycsb-multi-storage-schema.json`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/ycsb-multi-storage-schema.json)) を作成するには、山括弧内の内容を説明に従って置き換えて、次のコマンドを実行します。 + + ```console + java -jar scalardb-schema-loader-.jar --config -f ycsb-multi-storage-schema.json --coordinator + ``` + + ScalarDB Cluster を使用している場合は、代わりに次のコマンドを実行します。 + + ```console + java -jar scalardb-cluster-schema-loader--all.jar --config -f ycsb-multi-storage-schema.json --coordinator + ``` + + + +### ベンチマーク設定ファイルを準備する + +ベンチマークを実行するには、まずベンチマーク設定ファイルを準備する必要があります。設定ファイルには、少なくとも実行するワークロードモジュールの場所とデータベース設定が必要です。 + +以下は、TPC-C ベンチマークを実行するための設定例です。`config_file` に指定する ScalarDB プロパティファイルは、[スキーマをロードする](#スキーマをロードする)の手順の1つとして設定したプロパティファイルである必要があります。 + +:::note + +または、ScalarDB プロパティファイルを使用する代わりに、`.toml` ファイルで各データベース設定項目を指定することもできます。`config_file` が指定されている場合、`[database_config]` の下の他のすべての設定は、コメントが解除されていても無視されます。 + +::: + +```toml +[modules] +[modules.preprocessor] +name = "com.scalar.db.benchmarks.tpcc.TpccLoader" +path = "./build/libs/scalardb-benchmarks-all.jar" +[modules.processor] +name = "com.scalar.db.benchmarks.tpcc.TpccBench" +path = "./build/libs/scalardb-benchmarks-all.jar" +[modules.postprocessor] +name = "com.scalar.db.benchmarks.tpcc.TpccReporter" +path = "./build/libs/scalardb-benchmarks-all.jar" + +[database_config] +config_file = "" +#contact_points = "localhost" +#contact_port = 9042 +#username = "cassandra" +#password = "cassandra" +#storage = "cassandra" +``` + +モジュールに渡すパラメータは設定ファイルで定義できます。詳細については、以下のサンプル設定ファイルと [共通パラメータ](#共通パラメータ)で使用可能なパラメータを参照してください。 + +- **TPC-C:** [`tpcc-benchmark-config.toml`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/tpcc-benchmark-config.toml) +- **YCSB:** [`ycsb-benchmark-config.toml`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/ycsb-benchmark-config.toml) +- **マルチストレージ YCSB:** [`ycsb-multi-storage-benchmark-config.toml`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/ycsb-multi-storage-benchmark-config.toml) + +## ベンチマークを実行する + +ベンチマークを選択し、指示に従ってベンチマークを実行します。 + + + + TPC-C ベンチマークを実行するには、`` を Kelpie ディレクトリへのパスに置き換えて、次のコマンドを実行します。 + + ```console + //bin/kelpie --config tpcc-benchmark-config.toml + ``` + + + YCSB ベンチマークを実行するには、`` を Kelpie ディレクトリへのパスに置き換えて、次のコマンドを実行します。 + + ```console + //bin/kelpie --config ycsb-benchmark-config.toml + ``` + + + マルチストレージ YCSB ベンチマークを実行するには、`` を Kelpie ディレクトリへのパスに置き換えて、次のコマンドを実行します。 + + ```console + //bin/kelpie --config ycsb-multi-storage-benchmark-config.toml + ``` + + + +さらに、次のオプションが利用可能です。 + +- `--only-pre`。データのみをロードします。 +- `--only-process`。ベンチマークのみを実行します。 +- `--except-pre`。データをロードせずにジョブを実行します。 +- `--except-process`。ベンチマークを実行せずにジョブを実行します。 + +## 共通パラメータ + +| 名前 | 説明 | デフォルト | +|:---------------|:----------------------------------|:----------| +| `concurrency` | ベンチマーク用のスレッド数。 | `1` | +| `run_for_sec` | ベンチマークの継続時間 (秒単位)。 | `60` | +| `ramp_for_sec` | ベンチマーク前の立ち上げ時間 (秒単位)。 | `0` | + +## ワークロード固有のパラメータ + +ワークロードを選択すると、使用可能なパラメータが表示されます。 + + + + | 名前 | 説明 | デフォルト | + |:-----------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------| + | `num_warehouses` | ベンチマーク用のウェアハウスの数 (スケール係数)。 | `1` | + | `load_concurrency` | ロード用のスレッド数。 | `1` | + | `load_start_warehouse` | ロード中のウェアハウスの開始 ID。このオプションは、複数のクライアントで大規模なデータをロードする場合や、ウェアハウスを追加する場合に、`--skip-item-load` と一緒に使用すると便利です。 | `1` | + | `load_end_warehouse` | ロード中のウェアハウスの終了 ID。ロード中のウェアハウスの数を指定するには、`--num-warehouses` または `--end-warehouse` のいずれかを使用できます。 | `1` | + | `skip_item_load` | アイテムテーブルのロードをスキップするかどうか。 | `false` | + | `use_table_index` | ScalarDB のセカンダリインデックスの代わりに、汎用テーブルベースのセカンダリインデックスを使用するかどうか。 | `false` | + | `np_only` | 新規注文と支払いトランザクションのみ (それぞれ 50%) でベンチマークを実行します。 | `false` | + | `rate_new_order` | 新規注文トランザクションの割合。必要に応じてこの割合を指定する場合、他のすべてのレートパラメータの割合を指定する必要があります。その場合、すべてのレートパラメータの合計は 100% に等しくなければなりません。 | N/A | + | `rate_payment` | 支払いトランザクションの割合。必要に応じてこの割合を指定する場合、他のすべてのレートパラメータの割合を指定する必要があります。その場合、すべてのレートパラメータの合計は 100% に等しくなければなりません。 | N/A | + | `rate_order_status` | 注文ステータストランザクションの割合。ニーズに基づいてこのパーセンテージを指定する場合、他のすべてのレートパラメータのパーセンテージを指定する必要があります。その場合、すべてのレートパラメータの合計は100パーセントに等しくなければなりません。 | N/A | + | `rate_delivery` | 配送トランザクションのパーセンテージ。ニーズに基づいてこのパーセンテージを指定する場合、他のすべてのレートパラメータのパーセンテージを指定する必要があります。その場合、すべてのレートパラメータの合計は100パーセントに等しくなければなりません。 | N/A | + | `rate_stock_level` | 在庫レベルトランザクションのパーセンテージ。ニーズに基づいてこのパーセンテージを指定する場合、他のすべてのレートパラメータのパーセンテージを指定する必要があります。その場合、すべてのレートパラメータの合計は100パーセントに等しくなければなりません。 | N/A | + | `backoff` | 競合によりトランザクションがアボートされた後に挿入されるスリープ時間 (ミリ秒単位)。 | `0` | + + + | 名前 | 説明 | デフォルト | + |:------------------------|:----------------------------------------------------------------------------------|:----------------------------------------------| + | `load_concurrency` | ロード用のスレッド数。 | `1` | + | `load_batch_size` | 1回のロードトランザクションで入力されるレコード数。 | `1` | + | `load_overwrite` | レコードをロードするときに上書きするかどうか。 | `false` | + | `ops_per_tx` | 1回のトランザクションでの操作数。 | `2` (ワークロード A および C)
`1` (ワークロード F) | + | `record_count` | ターゲットテーブル内のレコード数。 | `1000` | + | `use_read_modify_write` | ワークロード A でブラインド書き込みではなく読み取り、変更、書き込みを使用するかどうか。 | `false`[^rmw] | + + [^rmw]: ワークロード A はトランザクションが最初に元のレコードを読み取ることを想定していないため、`use_read_modify_write` のデフォルト値は `false` です。ただし、トランザクションマネージャーとして Consensus Commit を使用している場合は、`use_read_modify_write` を `true` に設定する必要があります。これは、ScalarDB が既存のレコードに対するブラインド書き込みを許可しないためです。 +
+
diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/common-reference.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/common-reference.mdx new file mode 100644 index 00000000..027b6078 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/common-reference.mdx @@ -0,0 +1,198 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK リファレンス + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このリファレンスでは、ScalarDB Cluster .NET Client SDK の動作について詳しく説明します。 + +## クライアント設定 + +クライアントは、次のものを使用して設定できます。 + +- 設定ファイル (`appsettings.json` など) またはカスタム JSON ファイル +- 環境変数 +- `ScalarDbOptions` オブジェクト + +ASP.NET Core で SDK を使用する場合は、アプリをさまざまな方法で設定できます。詳細については、[ASP.NET Core の構成](https://learn.microsoft.com/ja-jp/aspnet/core/fundamentals/configuration/?view=aspnetcore-8.0)を参照してください。 + +設定できるオプションの一覧については、[使用可能なオプション](#使用可能なオプション)を参照してください。 + +### 設定ファイルの使用 + +SDK は、標準の `appsettings.json` とカスタム JSON 設定ファイルの両方をサポートしています。 JSON ファイルでクライアントを設定するには、`ScalarDbOptions` セクションを追加し、必要なオプションを設定します。例: + +```json +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053", + "HopLimit": 10 + } +} +``` + +次に、次のように設定された `TransactionFactory` オブジェクトを作成します。 + +```c# +// If appsettings.json is used, call the Create() method without parameters. +var factory = TransactionFactory.Create(); + +// Or, if a custom file is used, call the Create() method that is passed in the path to the custom file as a parameter. +factory = TransactionFactory.Create("scalardb-options.json"); +``` + +ASP.NET Core で SDK を使用する場合、登録されたトランザクションマネージャーや `ScalarDbContext` が作成されると、`appsettings.json` の設定が自動的に適用されます。カスタム JSON ファイルを使用する場合は、次のように設定フレームワークに追加します。 + +```c# +var builder = WebApplication.CreateBuilder(args); + +// ... + +builder.Configuration.AddJsonFile("scalardb-options.json"); +``` + +:::warning + +カスタム JSON ファイルはすべての標準設定プロバイダーの後に適用されるため、カスタムファイルの値が他のソースの値を上書きします。 + +::: + +### 環境変数の使用 + +クライアントが環境変数を使用するように設定するには、プレフィックス `ScalarDbOptions__` を使用します。例: + +```console +export ScalarDbOptions__Address="http://localhost:60053" +export ScalarDbOptions__HopLimit=10 +``` + +:::warning + +環境変数の値は設定ファイルの値を上書きします。 + +::: + +### `ScalarDbOptions` オブジェクトの使用 + +次のように `ScalarDbOptions` オブジェクトを使用して、実行時にクライアントを設定できます。 + +```c# +var options = new ScalarDbOptions() +{ + Address = "http://localhost:60053", + HopLimit = 10 +}; + +var factory = TransactionFactory.Create(options); +``` + +また、次のように、JSON ファイルや環境変数の値を使用して `ScalarDbOptions` オブジェクトを初期化し、残りの値を実行時に設定することもできます。 + +```c# +// If appsettings.json is used, call the Load() method without parameters. +var options = ScalarDbOptions.Load(); + +// Or, if a custom file is used, call the Load() method that is passed in the path to the custom file as a parameter. +options = ScalarDbOptions.Load("scalardb-options.json"); + +options.HopLimit = 10; + +var factory = TransactionFactory.Create(options); +``` + +ASP.NET Core で SDK を使用する場合は、次のように `AddScalarDb` および `AddScalarDbContext` のラムダ式を使用できます。 + +```c# +var builder = WebApplication.CreateBuilder(args); + +//... + +builder.Services.AddScalarDb(options => +{ + options.Address = "http://localhost:60053"; + options.HopLimit = 10; +}); + +builder.Services.AddScalarDbContext(options => +{ + options.Address = "http://localhost:60053"; + options.HopLimit = 10; +}); +``` + +この設定を使用すると、ラムダ式に渡される `ScalarDbOptions` オブジェクト (上記の例では `options` という名前) が、JSON ファイル、環境変数、およびその他のソースからの値で初期化されます。 + +### 使用可能なオプション + +利用可能なオプションは次のとおりです。 + +| 名前 | 説明 | デフォルト | +|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------| +| `Address` | **必須:** クラスターのアドレス。形式は `://:` です。``: ワイヤ暗号化 (TLS) が有効な場合は `https`、それ以外の場合は `http` です。``: クラスターの FQDN または IP アドレスです。``: クラスターのポート番号 (デフォルトでは `60053`)。 | - | +| `HopLimit` | クラスターへのリクエストのホップ数。`HopLimit` の目的は、クラスター内での無限ループを防ぐことです。リクエストが別のクラスターノードに転送されるたびに、`HopLimit` は1ずつ減少します。`HopLimit` が0に達すると、リクエストは拒否されます。 | `3` | +| `RetryCount` | クラスターが利用できない場合にクライアントがクラスターへの接続を試行できる回数。 | `10` | +| `AuthEnabled` | 認証と認可が有効かどうか。 | `false` | +| `Username` | 認証/認可のためのユーザー名。 | | +| `Password` | 認証用のパスワード。設定されていない場合は、パスワードなしで認証が行われます。 | | +| `AuthTokenExpirationTime` | 認証トークンを更新するまでの時間。`AuthTokenExpirationTime` に設定された時間がクラスターの有効期限よりも長い場合、認証エラーを受信すると認証トークンが更新されます。認証トークンが正常に更新されると、認証エラーはクライアントコードに伝播されません。代わりに、認証エラーで失敗した操作が自動的に再試行されます。複数の操作が並行して実行されている場合、認証トークンが更新される前に、これらすべての操作が認証エラーで一度失敗します。 | `00:00:00` (クラスターから受信した認証トークンの有効期限が使用されます。) | +| `TlsRootCertPem` | TLS 通信用のカスタム CA ルート証明書 (PEM データ)。 | | +| `TlsRootCertPath` | TLS 通信用のカスタム CA ルート証明書へのファイルパス。 | | +| `TlsOverrideAuthority` | TLS 通信のカスタム認証局。これは、実際に接続しているホストを変更するものではありません。これは主にテストを目的としています。たとえば、クラスターの証明書 (クラスターの `scalar.db.cluster.node.tls.cert_chain_path` パラメータ) に記載されているホスト名を指定できます。クラスターの証明書に複数のホスト名がある場合は、最初のホスト名のみがチェックされます。 | | +| `LogSensitiveData` | `true` に設定すると、gRPC リクエストとレスポンスをログに記録するときに、ユーザー名、パスワード、認証トークンなどの情報がマスクされずにそのままログに記録されます。 | `false` | +| `GrpcRequestTimeout` | gRPC リクエストのタイムアウト。内部的には、タイムアウトの値はクラスターへの各 gRPC リクエストのデッドラインを計算して設定するために使用されます。設定されたデッドラインを超えると、リクエストはキャンセルされ、`DeadlineExceededException` がスローされます。タイムアウトが `0` に設定されている場合、デッドラインは設定されません。 | `00:01:00` | +| `GrpcMaxReceiveMessageSize` | クライアントが受信できる最大メッセージサイズ (バイト単位)。`0` に設定すると、メッセージサイズは無制限になります。 | `4 MB` | +| `GrpcMaxSendMessageSize` | クライアントから送信できる最大メッセージサイズ (バイト単位)。`0` に設定すると、メッセージサイズは無制限になります。 | `0` (無制限) | + +## ScalarDB 列型と .NET 型間の変換方法 + +[LINQ](getting-started-with-linq.mdx#クラスを設定する) または [Transactional API](getting-started-with-scalardb-tables-as-csharp-classes.mdx#すべての-scalardb-テーブルのクラスを作成する)、[SQL API](getting-started-with-distributed-sql-transactions.mdx#sql-クエリを実行する)、または [Administrative API](getting-started-with-scalardb-tables-as-csharp-classes.mdx#administrative-api-を使用する) の拡張メソッドを使用すると、クラスターから受信した列の値は、対応する .NET 型に自動的に変換されます。同様に、オブジェクトがクラスターに保存されるときに、.NET プロパティの値は対応するクラスターの型に自動的に変換されます。 + +次の表に、型がどのように変換されるかを示します。 + +| ScalarDB 型 | .NET 型 | C# エイリアス | +|-------------|----------------------------|----------| +| TEXT | System.String | string | +| INT | System.Int32 | int | +| BIGINT | System.Int64 | long | +| FLOAT | System.Single | float | +| DOUBLE | System.Double | double | +| BOOLEAN | System.Boolean | bool | +| BLOB | Google.Protobuf.ByteString | | +| DATE | NodaTime.LocalDate | | +| TIME | NodaTime.LocalTime | | +| TIMESTAMP | NodaTime.LocalDateTime | | +| TIMESTAMPTZ | NodaTime.Instant | | + +:::note + +ScalarDB Cluster .NET Client SDK は、`BLOB` 型には [Google.Protobuf](https://www.nuget.org/packages/Google.Protobuf) を使用し、時間関連の型には [NodaTime](https://www.nuget.org/packages/NodaTime) を使用します。 + +::: + +:::warning + +.NET の時間関連型の精度は、ScalarDB でサポートされている精度よりも高くなります。そのため、外部ソースから受信した時間関連の値を保存するときは注意が必要です。ScalarDB Cluster .NET Client SDK には、次の方法で時間関連の値の精度を下げるために使用できる `WithScalarDbPrecision` 拡張メソッドが含まれています: + +```c# +using ScalarDB.Client.Extensions; + +// ... + +var updatedAt = Instant.FromDateTimeUtc(DateTime.UtcNow) + .WithScalarDbPrecision(); + +// using NodaTime to get current instant +updatedAt = clockInstance.GetCurrentInstant() + .WithScalarDbPrecision(); +``` + +ScalarDB の値の範囲と精度の詳細については、[ScalarDB と他のデータベース間のデータ型マッピング](../schema-loader.mdx#scalardb-と他のデータベース間のデータ型マッピング)を参照してください。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/exception-handling.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/exception-handling.mdx new file mode 100644 index 00000000..009ab8b9 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/exception-handling.mdx @@ -0,0 +1,177 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK での例外処理 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +トランザクションを実行するときは、例外も適切に処理する必要があります。 + +:::warning + +例外を適切に処理しないと、異常やデータの不整合が発生する可能性があります。 + +::: + +:::note + +この例では Transactional API が使用されていますが、SQL API または `ScalarDbContext` を使用する場合も例外は同じ方法で処理できます。 + +::: + +次のサンプルコードは、例外を処理する方法を示しています。 + +```c# +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client; +using ScalarDB.Client.DataAnnotations; +using ScalarDB.Client.Exceptions; +using ScalarDB.Client.Extensions; + +var options = new ScalarDbOptions { Address = "http://:"}; + +var factory = TransactionFactory.Create(options); +using var manager = factory.GetTransactionManager(); + +var retryCount = 0; +TransactionException? lastException = null; + +while (true) +{ + if (retryCount++ > 0) + { + // Retry the transaction three times maximum in this sample code + if (retryCount > 3) + // Throw the last exception if the number of retries exceeds the maximum + throw lastException!; + + // Sleep 100 milliseconds before retrying the transaction in this sample code + await Task.Delay(100); + } + + // Begin a transaction + var tran = await manager.BeginAsync(); + try + { + // Execute CRUD operations in the transaction + var getKeys = new Dictionary { { nameof(Item.Id), 1 } }; + var result = await tran.GetAsync(getKeys); + + var scanKeys = new Dictionary { { nameof(Item.Id), 1 } }; + await foreach (var item in tran.ScanAsync(scanKeys, null)) + Console.WriteLine($"{item.Id}, {item.Name}, {item.Price}"); + + await tran.InsertAsync(new Item { Id = 1, Name = "Watermelon", Price = 4500 }); + await tran.DeleteAsync(new Item { Id = 1 }); + + // Commit the transaction + await tran.CommitAsync(); + + return; + } + catch (UnsatisfiedConditionException) + { + // You need to handle `UnsatisfiedConditionException` only if a mutation operation specifies + // a condition. This exception indicates the condition for the mutation operation is not met. + // InsertAsync/UpdateAsync implicitlly sets IfNotExists/IfExists condition + + try + { + await tran.RollbackAsync(); + } + catch (TransactionException ex) + { + // Rolling back the transaction failed. As the transaction should eventually recover, you + // don't need to do anything further. You can simply log the occurrence here + Console.WriteLine($"Rollback error: {ex}"); + } + + // You can handle the exception here, according to your application requirements + + return; + } + catch (UnknownTransactionStatusException) + { + // If you catch `UnknownTransactionStatusException` when committing the transaction, it + // indicates that the status of the transaction, whether it has succeeded or not, is + // unknown. In such a case, you need to check if the transaction is committed successfully + // or not and retry it if it failed. How to identify a transaction status is delegated to users + return; + } + catch (TransactionException ex) + { + // For other exceptions, you can try retrying the transaction. + + // For `TransactionConflictException` and `TransactionNotFoundException`, + // you can basically retry the transaction. However, for the other exceptions, + // the transaction may still fail if the cause of the exception is nontransient. + // In such a case, you will exhaust the number of retries and throw the last exception + + try + { + await tran.RollbackAsync(); + } + catch (TransactionException e) + { + // Rolling back the transaction failed. As the transaction should eventually recover, + // you don't need to do anything further. You can simply log the occurrence here + Console.WriteLine($"Rollback error: {e}"); + } + + lastException = ex; + } +} + +[Table("order_service.items")] +public class Item +{ + [PartitionKey] + [Column("item_id", Order = 0)] + public int Id { get; set; } + + [Column("name", Order = 1)] + public string Name { get; set; } = String.Empty; + + [Column("price", Order = 2)] + public int Price { get; set; } +} + +``` + +:::note + +サンプルコードでは、トランザクションは最大3回再試行され、再試行される前に100ミリ秒間スリープします。アプリケーションの要件に応じて、指数バックオフなどの再試行ポリシーを選択できます。 + +::: + +### 例外の詳細 + +以下の表は、クラスターとの通信時に発生する可能性のあるトランザクション例外を示しています。 + +| 例外 | 操作 | 説明 | +|-----------------------------------|--------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| AuthorizationErrorException | Put, Insert, Update, Delete, Mutate, Execute, Administrative | 権限が不足しているため、認証に失敗しました。 | +| IllegalArgumentException | 全て | 要求メッセージ内の引数が無効です。 | +| IllegalStateException | 全て | RPC が無効な状態で呼び出されました。 | +| InternalErrorException | 全て | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合は、トランザクションが失敗する可能性があります。 | +| TransactionConflictException | Begin、Join、Rollback を除くすべて | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| TransactionNotFoundException | Begin、Join を除くすべて | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合、トランザクションを最初から再試行してください。 | +| UnavailableException | 全て | ScalarDB Cluster は、複数回接続を試みても利用できません。 | +| UnknownTransactionStatusException | Commit | トランザクションのステータスは不明です (トランザクションが正常にコミットされたかどうかは不明です)。この状況では、トランザクションが正常にコミットされたかどうかを確認し、そうでない場合は再試行する必要があります。トランザクションステータスの判断はユーザーの責任です。トランザクションステータステーブルを作成し、他のアプリケーションデータと連動して更新すると、役立つ場合があります。そうすることで、テーブル自体からトランザクションのステータスを判断できるようになります。 | +| UnsatisfiedConditionException | Put, Insert, Update, Delete, Mutate | 突然変異条件が満たされていません。 | + +例外が発生した場合は、`Begin` の場合を除き、トランザクションをロールバックする必要があります。トランザクションをロールバックした後、再試行によって解決できる例外については、トランザクションを最初から再試行できます。 + +上記の例外の他に、gRPC ライブラリによってスローされる例外が発生する場合があります。このような場合は、`RpcException` プロパティで詳細を確認できます。 + +また、`ScalarDbContext` は、次の場合に `TransactionException` タイプの例外をスローします。 + +- すでにアクティブなトランザクションがあるときに `BeginTransaction` または `JoinTransaction` が呼び出された場合 +- アクティブなトランザクションがない状態で `CommitTransaction` または `RollbackTransaction` が呼び出された場合 +- アクティブな2フェーズコミットトランザクションがない状態で `PrepareTransaction` または `ValidateTransaction` が呼び出された場合 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-admin-api.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-admin-api.mdx new file mode 100644 index 00000000..1c2b0c7e --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-admin-api.mdx @@ -0,0 +1,132 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK の Administrative API をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK は、ScalarDB Cluster の Administrative API をサポートしています。この API を使用すると、.NET アプリケーションから ScalarDB Cluster を管理できます。 + +:::note + +次の例のように非同期メソッドを使用することをお勧めしますが、代わりに同期メソッドを使用することもできます。 + +::: + +## SDK をインストールする + +ScalarDB Cluster と同じメジャーバージョンとマイナーバージョンの [SDK](https://www.nuget.org/packages/ScalarDB.Client) を .NET プロジェクトにインストールします。組み込みの NuGet パッケージマネージャーを使用してこれを行うことができます。`.` を、使用しているバージョンに置き換えます。 + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## 設定ファイルを作成する + +`scalardb-options.json` ファイルを作成し、次の内容を追加します。`` を FQDN または IP アドレスに、`` をクラスターのポート番号 (デフォルトでは `60053`) に置き換えます。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +設定ファイルやクライアントを設定するその他の方法の詳細については、[クライアント設定](common-reference.mdx#クライアント設定)を参照してください。 + +## トランザクションマネージャーを取得する + +Administrative API とやり取りするためのオブジェクトを取得する必要があります。オブジェクトを取得するには、次のように `TransactionFactory` を使用します。 + +```c# +// Pass the path to the settings file created in the previous step. +var factory = TransactionFactory.Create("scalardb-options.json"); + +using var admin = factory.GetTransactionAdmin(); +``` + +## ScalarDB Cluster の管理 + +ScalarDB Cluster .NET Client SDK を使用して、次の操作を実行できます。 + +### 新しい名前空間を作成する + +```c# +await admin.CreateNamespaceAsync("ns", ifNotExists: true); +``` + +### 名前空間を削除する + +```c# +await admin.DropNamespaceAsync("ns", ifExists: true); +``` + +### 名前空間が存在するかどうかを確認する + +```c# +var namespaceExists = await admin.IsNamespacePresentAsync("ns"); +``` + +### 新しいテーブルを作成する + +```c# +// ... +using ScalarDB.Client.Builders.Admin; +using ScalarDB.Client.Core; + +// ... + +var tableMetadata = + new TableMetadataBuilder() + .AddPartitionKey("pk", DataType.Int) + .AddClusteringKey("ck", DataType.Double) + .AddSecondaryIndex("index", DataType.Float) + .AddColumn("ordinary", DataType.Text) + .Build(); + +await admin.CreateTableAsync("ns", "table_name", tableMetadata, ifNotExists: true); +``` + +### テーブルを削除する + +```c# +await admin.DropTableAsync("ns", "table_name", ifExists: true); +``` + +### テーブルが存在するかどうかを確認する + +```c# +var tableExists = await admin.IsTablePresentAsync("ns", "table_name"); +``` + +### 既存のテーブルの名前を取得する + +```c# +var tablesList = await admin.GetTableNamesAsync("ns"); +``` + +### Coordinator テーブルを作成する + +```c# +await admin.CreateCoordinatorTablesAsync(); +``` + +### Coordinator テーブルを削除する + +```c# +await admin.DropCoordinatorTablesAsync(); +``` + +### Coordinator テーブルが存在するかどうかを確認します + +```c# +var exists = await admin.AreCoordinatorTablesPresentAsync(); +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-aspnet-and-di.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-aspnet-and-di.mdx new file mode 100644 index 00000000..fd650847 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-aspnet-and-di.mdx @@ -0,0 +1,88 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK での ASP.NET Core と依存性注入をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK は、ASP.NET Core などのフレームワークでの依存性注入 (DI) をサポートしています。 + +## SDK をインストールする + +ScalarDB Cluster と同じメジャーバージョンとマイナーバージョンの [SDK](https://www.nuget.org/packages/ScalarDB.Client) を .NET プロジェクトにインストールします。組み込みの NuGet パッケージマネージャーを使用してこれを行うことができます。`.` を使用しているバージョンに置き換えます。 + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## クライアント設定の追加 + +ASP.NET Core アプリの `appsettings.json` ファイルに `ScalarDbOptions` セクションを追加し、`` を FQDN または IP アドレスに、`` をクラスターのポート番号 (デフォルトでは `60053`) に置き換えます。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +設定ファイルやクライアントを設定するその他の方法の詳細については、[クライアント設定](common-reference.mdx#クライアント設定)を参照してください。 + +## トランザクションマネージャーをセットアップする + +次のようにして、DI コンテナーに ScalarDB トランザクションマネージャーを登録できます。 + +```c# +using ScalarDB.Client.Extensions; + +//... + +var builder = WebApplication.CreateBuilder(args); + +//... + +builder.Services.AddScalarDb(); +``` + +:::note + +ScalarDB トランザクションマネージャーは、一時的なサービスとして登録されます。サービス有効期間の詳細については、 [.NET の依存関係の挿入 - サービスの有効期間](https://learn.microsoft.com/ja-jp/dotnet/core/extensions/dependency-injection#service-lifetimes)を参照してください。 + +::: + +トランザクションマネージャーを登録したら、次のようにコントローラーのコンストラクターに挿入できます。 + +```c# +[ApiController] +public class OrderController: ControllerBase +{ + private readonly IDistributedTransactionManager _manager; + private readonly ISqlTransactionManager _sqlManager; + private readonly ITwoPhaseCommitTransactionManager _twoPhaseManager; + private readonly ISqlTwoPhaseCommitTransactionManager _sqlTwoPhaseManager; + private readonly IDistributedTransactionAdmin _admin; + + public OrderController(IDistributedTransactionManager manager, + ISqlTransactionManager sqlManager, + ITwoPhaseCommitTransactionManager twoPhaseManager, + ISqlTwoPhaseCommitTransactionManager sqlTwoPhaseManager, + IDistributedTransactionAdmin admin) + { + _manager = manager; + _sqlManager = sqlManager; + _twoPhaseManager = twoPhaseManager; + _sqlTwoPhaseManager = sqlTwoPhaseManager; + _admin = admin; + } +} +``` + +これらの例は WebApi プロジェクト用ですが、GrpcService プロジェクトでも同様に動作します。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-auth.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-auth.mdx new file mode 100644 index 00000000..458d29f6 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-auth.mdx @@ -0,0 +1,71 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK を使用した認証と認可をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK は [認証と認可](../scalardb-cluster/scalardb-auth-with-sql.mdx)をサポートしており、これにより ScalarDB Cluster へのリクエストを認証および認可できます。 + +## SDK をインストールする + +ScalarDB Cluster と同じメジャーバージョンとマイナーバージョンの [SDK](https://www.nuget.org/packages/ScalarDB.Client) を .NET プロジェクトにインストールします。組み込みの NuGet パッケージマネージャーを使用してこれを行うことができます。`.` を使用しているバージョンに置き換えます。 + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## 設定ファイルで資格情報を設定する + +設定ファイルの資格情報を次のように設定し、山括弧内の内容を置き換えてください。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10, + "AuthEnabled": true, + "Username": "", + "Password": "" + } +} +``` + +設定ファイルやクライアントを設定するその他の方法の詳細については、[クライアント設定](common-reference.mdx#クライアント設定)を参照してください。 + +## トランザクションマネージャーを取得する + +次のように `TransactionFactory` を使用して、トランザクションマネージャーまたはトランザクション管理オブジェクトを取得する必要があります。`` を `GetTransactionManager()`、`GetTwoPhaseCommitTransactionManager()`、`GetSqlTransactionManager()`、または `GetSqlTwoPhaseCommitTransactionManager()` に置き換えてください。 + +```c# +// Pass the path to the settings file. +var factory = TransactionFactory.Create("scalardb-options.json"); + +// To get a transaction manager +using var manager = factory.(); + +// To get a transaction admin +using var admin = factory.GetTransactionAdmin(); +``` + +提供された資格情報を使用して `TransactionFactory` から作成されたトランザクションマネージャーまたはトランザクション管理オブジェクトは、ScalarDB Cluster に自動的にログインし、通信できます。 + +## ワイヤ暗号化 + +[ワイヤ暗号化](../scalardb-cluster/scalardb-auth-with-sql.mdx#ワイヤ暗号化) もサポートされています。次のように `Address` を `https` で始まる URL に設定することで有効にできます。 + +```json +{ + "ScalarDbOptions": { + "Address": "https://:" + } +} +``` + +設定ファイルやクライアントを設定するその他の方法の詳細については、[クライアント設定](common-reference.mdx#クライアント設定)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx new file mode 100644 index 00000000..7b80e872 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx @@ -0,0 +1,196 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK での分散 SQL トランザクションをはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK は、ScalarDB Cluster の分散 SQL トランザクション機能をサポートします。SDK には、クラスター内での通信を容易にするためのトランザクションとマネージャーの抽象化が含まれています。 + +:::note + +次の例のように非同期メソッドを使用することをお勧めしますが、代わりに同期メソッドを使用することもできます。 + +::: + +分散非 SQL トランザクションの詳細については、[ScalarDB Cluster .NET Client SDK での分散トランザクションをはじめよう](getting-started-with-distributed-transactions.mdx)を参照してください。 + +## SDK をインストールする + +ScalarDB Cluster と同じメジャーバージョンとマイナーバージョンの [SDK](https://www.nuget.org/packages/ScalarDB.Client) を .NET プロジェクトにインストールします。組み込みの NuGet パッケージマネージャーを使用してこれを行うことができます。`.` を、使用しているバージョンに置き換えます。 + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## 設定ファイルを作成する + +`scalardb-options.json` ファイルを作成し、次の内容を追加します。`` を FQDN または IP アドレスに、`` をクラスターのポート番号 (デフォルトでは `60053`) に置き換えます。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +設定ファイルやクライアントを設定するその他の方法の詳細については、[クライアント設定](common-reference.mdx#クライアント設定)を参照してください。 + +## トランザクションマネージャーを取得する + +分散 SQL トランザクション用のトランザクションマネージャーオブジェクトを取得する必要があります。トランザクションマネージャーオブジェクトを取得するには、次のように `TransactionFactory` を使用します。 + +```c# +// Pass the path to the settings file created in the previous step. +var factory = TransactionFactory.Create("scalardb-options.json"); + +using var manager = factory.GetSqlTransactionManager(); +``` + +## SQL クエリを実行する + +SQL ステートメントを実行するには、次のようにビルダーを使用して作成できる `ISqlStatement` オブジェクトが必要です。 + +```c# +using ScalarDB.Client.Builders.Sql; + +// ... + +var sqlStatement = + new SqlStatementBuilder() + .SetSql("SELECT * FROM order_service.statements WHERE item_id = :item_id") + .AddParam("item_id", 2) + .Build(); +``` + +次のようにトランザクションマネージャーを使用して、単一の SQL ステートメントを直接実行できます。 + +```c# +var resultSet = await manager.ExecuteAsync(sqlStatement); +``` + +`ExecuteAsync` メソッドの結果には、クラスターから受信したレコードが含まれます。特定の列の値は、次の方法で取得できます。 + +```c# +foreach (var record in resultSet.Records) +{ + // Getting an integer value from the "item_id" column. + // If it fails, an exception will be thrown. + var itemId = record.GetValue("item_id"); + + // Trying to get a string value from the "order_id" column. + // If it fails, no exception will be thrown. + if (record.TryGetValue("order_id", out var orderId)) + Console.WriteLine($"order_id: {orderId}"); + + // Checking if the "count" column is null. + if (record.IsNull("count")) + Console.WriteLine("'count' is null"); +} +``` + +`GetValue` および `TryGetValue` で使用する型の詳細については、[ScalarDB 列型を .NET 型に変換する方法](common-reference.mdx#scalardb-列型と-net-型間の変換方法) を参照してください。 + +## トランザクションで SQL クエリを実行する + +1つのトランザクションの一部として複数の SQL ステートメントを実行するには、トランザクションオブジェクトが必要です。 + +次のようにトランザクションマネージャーを使用してトランザクションオブジェクトを作成できます。 + +```c# +var transaction = await manager.BeginAsync(); +``` + +次のようにして、すでに開始されているトランザクションを再開することもできます。 + +```c# +var transaction = manager.Resume(transactionIdString); +``` + +:::note + +`Resume` メソッドはトランザクションオブジェクトを作成するだけなので、非同期バージョンはありません。このため、間違った ID を使用してトランザクションを再開する可能性があります。 + +::: + +トランザクションには、トランザクションマネージャーと同じ `ExecuteAsync` メソッドがあります。このメソッドを使用して、SQL ステートメントを実行できます。 + +トランザクションをコミットする準備ができたら、次のようにトランザクションの `CommitAsync` メソッドを呼び出すことができます。 + +```c# +await transaction.CommitAsync(); +``` + +トランザクションをロールバックするには、`RollbackAsync` メソッドを使用できます。 + +```c# +await transaction.RollbackAsync(); +``` + +## メタデータを取得する + +次のように、Metadata プロパティを使用して ScalarDB のメタデータを取得できます。 + +```c# +// namespaces, tables metadata +var namespaceNames = new List(); + +await foreach (var ns in manager.Metadata.GetNamespacesAsync()) +{ + namespaceNames.Add(ns.Name); + Console.WriteLine($"Namespace: {ns.Name}"); + + await foreach (var tbl in ns.GetTablesAsync()) + { + Console.WriteLine($" Table: {tbl.Name}"); + + Console.WriteLine($" Columns:"); + foreach (var col in tbl.Columns) + Console.WriteLine($" {col.Name} [{col.DataType}]"); + + Console.WriteLine($" PartitionKey:"); + foreach (var col in tbl.PartitionKey) + Console.WriteLine($" {col.Name}"); + + Console.WriteLine($" ClusteringKey:"); + foreach (var col in tbl.ClusteringKey) + Console.WriteLine($" {col.Name} [{col.ClusteringOrder}]"); + + Console.WriteLine($" Indexes:"); + foreach (var index in tbl.Indexes) + Console.WriteLine($" {index.ColumnName}"); + + Console.WriteLine(); + } +} + +// users metadata +await foreach (var user in manager.Metadata.GetUsersAsync()) +{ + Console.WriteLine($"User: {user.Name} [IsSuperuser: {user.IsSuperuser}]"); + + foreach (var nsName in namespaceNames) + { + Console.WriteLine($" Namespace: {nsName}"); + + Console.WriteLine($" Privileges:"); + foreach (var privilege in await user.GetPrivilegesAsync(nsName)) + Console.WriteLine($" {privilege}"); + } + + Console.WriteLine(); +} +``` + +:::note + +`IAsyncEnumerable` で LINQ メソッドを使用するには、[System.Linq.Async](https://www.nuget.org/packages/System.Linq.Async/) パッケージをインストールします。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions.mdx new file mode 100644 index 00000000..8341c8de --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions.mdx @@ -0,0 +1,330 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK での分散トランザクションをはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK は、ScalarDB Cluster の分散トランザクション機能をサポートします。SDK には、クラスター内での通信を容易にするためのトランザクションとマネージャーの抽象化が含まれています。 + +:::note + +次の例のように非同期メソッドを使用することをお勧めしますが、代わりに同期バージョンを使用することもできます。 + +::: + +分散 SQL トランザクションの詳細については、[ScalarDB Cluster .NET Client SDK での分散 SQL トランザクションをはじめよう](getting-started-with-distributed-sql-transactions.mdx)を参照してください。 + +## SDK をインストールする + +ScalarDB Cluster と同じメジャーバージョンとマイナーバージョンの [SDK](https://www.nuget.org/packages/ScalarDB.Client) を .NET プロジェクトにインストールします。組み込みの NuGet パッケージマネージャーを使用して、`.` を使用しているバージョンに置き換えることでこれを行うことができます。 + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## 設定ファイルを作成する + +`scalardb-options.json` ファイルを作成し、次の内容を追加します。`` を FQDN または IP アドレスに、`` をクラスターのポート番号 (デフォルトでは `60053`) に置き換えます。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +設定ファイルやクライアントを設定するその他の方法の詳細については、[クライアント設定](common-reference.mdx#クライアント設定)を参照してください。 + +## トランザクションマネージャーを取得する + +分散トランザクションにはトランザクションマネージャーを取得する必要があります。トランザクションマネージャーを取得するには、次のように `TransactionFactory` を使用します。 + +```c# +// Pass the path to the settings file created in the previous step. +var factory = TransactionFactory.Create("scalardb-options.json"); + +using var manager = factory.GetTransactionManager(); +``` + +## トランザクションを管理する + +複数の CRUD 操作を単一のトランザクションの一部として実行するには、まずトランザクションを開始する必要があります。次のようにトランザクションマネージャーを使用してトランザクションを開始できます。 + +```c# +var transaction = await manager.BeginAsync(); +``` + +次のようにして、すでに実行中のトランザクションを再開することもできます。 + +```c# +var transaction = manager.Resume(transactionIdString); +``` + +:::note + +`Resume` メソッドはトランザクションオブジェクトを作成するだけなので、非同期バージョンはありません。このため、間違った ID を使用してトランザクションを再開する可能性があります。 + +::: + +トランザクションをコミットする準備ができたら、次のようにトランザクションの `CommitAsync` メソッドを呼び出すことができます。 + +```c# +await transaction.CommitAsync(); +``` + +トランザクションをロールバックするには、`RollbackAsync` メソッドを使用できます。 + +```c# +await transaction.RollbackAsync(); +``` + +## CRUD 操作を実行する + +トランザクションには、クラスターに対して CRUD 操作を実行するための `GetAsync`、`ScanAsync`、`InsertAsync`、`UpsertAsync`、`UpdateAsync`、`DeleteAsync`、および `MutateAsync` メソッドがあります。パラメーターとして、これらのメソッドには操作オブジェクトがあります。操作オブジェクトは、このセクションにリストされているビルダーを使用して作成できます。 + +:::note + +CRUD 操作は、トランザクションを明示的に作成する必要なく、ワンショットトランザクション方式で実行できます。そのために、マネージャーオブジェクトには、トランザクションオブジェクトと同じ CRUD メソッドがあります。 + +::: + +ビルダーを使用するには、`using` セクションに次の名前空間を追加します。 + +```c# +using ScalarDB.Client.Builders; +``` + +:::note + +クラスターは1つのトランザクション内でのコマンドの並列実行をサポートしていないため、非同期メソッドには必ず `await` を使用してください。 + +::: + +### `GetAsync` メソッドの例 + +単一のレコードを取得するには、次のように `GetAsync` メソッドを使用します。 + +```c# +var get = + new GetBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .SetProjections("item_id", "count") + .Build(); + +var getResult = await transaction.GetAsync(get); +``` + +パーティションキーの代わりにインデックスを使用してレコードを取得することも可能です。そのためには、次のように操作の種類を `GetWithIndex` に設定する必要があります。 + +```c# +// ... +using ScalarDB.Client.Core; + +// ... + +var get = + new GetBuilder() + // ... + .SetGetType(GetOperationType.GetWithIndex) + .AddPartitionKey("index_column", "1") + .Build(); +``` + +取得されたレコードが満たす必要のある任意の条件を指定することもできます。満たさない場合はレコードは返されません。条件は、次のように条件の結合として設定できます。 + +```c# +var get = + new GetBuilder() + // ... + .AddConjunction(c => c.AddCondition("cost", 1000, Operator.LessThan)) + .AddConjunction(c => + { + c.AddCondition("cost", 10000, Operator.LessThan); + c.AddCondition("in_stock", true, Operator.Equal); + }) + .Build(); +``` + +上記の例では、`cost` が `1000` 未満の場合、または `cost` が `10000` 未満で `in_stock` が true の場合にのみ、レコードが返されます。 + +#### `IResult` オブジェクトの処理 + +`GetAsync` メソッドと `ScanAsync` メソッドは `IResult` オブジェクトを返します。`IResult` オブジェクトには、取得されたレコードの列が含まれます。特定の列の値は、次の方法で取得できます。 + +```c# +// Getting an integer value from the "item_id" column. +// If it fails, an exception will be thrown. +var itemId = result.GetValue("item_id"); + +// Trying to get a string value from the "order_id" column. +// If it fails, no exception will be thrown. +if (result.TryGetValue("order_id", out var orderId)) + Console.WriteLine($"order_id: {orderId}"); + +// Checking if the "count" column is null. +if (result.IsNull("count")) + Console.WriteLine("'count' is null"); +``` + +`GetValue` および `TryGetValue` で使用する型の詳細については、[ScalarDB 列型と .NET 型間の変換方法](common-reference.mdx#scalardb-列型を-net-型間の変換方法) を参照してください。 + +### `ScanAsync` メソッドの例 + +レコードの範囲を取得するには、次のように `ScanAsync` メソッドを使用できます。 + +```c# +var scan = + new ScanBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddStartClusteringKey("item_id", 2) + .SetStartInclusive(true) + .AddEndClusteringKey("item_id", 8) + .SetEndInclusive(true) + .SetProjections("item_id", "count") + .Build(); + +var scanResult = await transaction.ScanAsync(scan); +``` + +パーティションキーの代わりにインデックスを使用してレコードを取得することも可能です。そのためには、次のように操作の種類を `ScanWithIndex` に設定する必要があります。 + +```c# +// ... +using ScalarDB.Client.Core; + +// ... +var scan = + new ScanBuilder() + // ... + .SetScanType(ScanOperationType.ScanWithIndex) + .AddPartitionKey("index_column", "1") + .Build(); +``` + +取得されたレコードが満たす必要のある任意の条件は、[get 操作](getting-started-with-distributed-transactions.mdx#getasync-メソッドの例)の場合と同様に、スキャン操作に対しても設定できます。 + +### `InsertAsync` メソッドの例 + +新しいレコードを挿入するには、次のように `InsertAsync` メソッドを使用します。 + +```c# +var insert = + new InsertBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .AddColumn("count", 11) + .Build(); + +await transaction.InsertAsync(insert); +``` + +### `UpsertAsync` メソッドの例 + +レコードをUPSERTする (既存のレコードを更新するか、新しいレコードを挿入する) には、次のように `UpsertAsync` メソッドを使用できます。 + +```c# +var upsert = + new UpsertBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .AddColumn("count", 11) + .Build(); + +await transaction.UpsertAsync(upsert); +``` + +### `UpdateAsync` メソッドの例 + +既存のレコードを更新するには、次のように `UpdateAsync` メソッドを使用します。 + +```c# +// ... +using ScalarDB.Client.Core; + +// ... + +var update = + new UpdateBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .AddColumn("count", 11) + .AddCondition("processed", false, Operator.Equal) + .Build(); + +await transaction.UpdateAsync(update); +``` + +### `DeleteAsync` メソッドの例 + +レコードを削除するには、次のように `DeleteAsync` メソッドを使用します。 + +```c# +// ... +using ScalarDB.Client.Core; + +// ... +var delete = + new DeleteBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .AddCondition("processed", false, Operator.Equal) + .Build(); + +await transaction.DeleteAsync(delete); +``` + +### `MutateAsync` メソッドの例 + +`MutateAsync` メソッドを使用すると、クラスターへの1回の呼び出しで複数のミューテーション操作を実行できます。これは次の方法で実行できます。 + +```c# +// ... +using ScalarDB.Client.Core; + +// ... +var mutations = new IMutation[] + { + new InsertBuilder() + // ... + .Build(), + new UpsertBuilder() + // ... + .Build(), + new UpdateBuilder() + // ... + .Build(), + new DeleteBuilder() + // ... + .Build() + }; + +await transaction.MutateAsync(mutations); +``` + +:::note + +`InsertAsync`、`UpsertAsync`、`UpdateAsync`、`DeleteAsync`、または `MutateAsync` メソッドを使用してデータを変更するには、まず `GetAsync` または `ScanAsync` メソッドを使用してデータを取得する必要があります。 + +::: diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx new file mode 100644 index 00000000..3b55e7e3 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx @@ -0,0 +1,373 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK での LINQ をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK は、LINQ と Entity Framework のような機能を使用してクラスターをクエリすることをサポートしています。 + +:::note + +この SDK は [Entity Framework](https://learn.microsoft.com/ja-jp/ef/) をサポートしていません。代わりに、この SDK は Entity Framework に似た機能を実装します。 + +::: + +:::note + +LINQ を使用するには、クラスターで SQL サポートを有効にする必要があります。 + +::: + +## SDK をインストールする + +ScalarDB Cluster と同じメジャーバージョンとマイナーバージョンの [SDK](https://www.nuget.org/packages/ScalarDB.Client) を .NET プロジェクトにインストールします。組み込みの NuGet パッケージマネージャーを使用してこれを行うことができます。`.` を、使用しているバージョンに置き換えます。 + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## クライアント設定の追加 + +ASP.NET Core アプリの `appsettings.json` ファイルに `ScalarDbOptions` セクションを追加し、`` を FQDN または IP アドレスに、`` をクラスターのポート番号 (デフォルトでは `60053`) に置き換えます。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +設定ファイルやクライアントを設定するその他の方法の詳細については、[クライアント設定](common-reference.mdx#クライアント設定)を参照してください。 + +## クラスを設定する + +SQL サポートが有効になっていることを確認したら、使用する ScalarDB テーブルごとに C# クラスを作成します。例: + +```c# +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client.DataAnnotations; + +// ... + +[Table("ns.statements")] +public class Statement +{ + [PartitionKey] + [Column("statement_id", Order = 0)] + public int Id { get; set; } + + [SecondaryIndex] + [Column("order_id", Order = 1)] + public string OrderId { get; set; } = String.Empty; + + [SecondaryIndex] + [Column("item_id", Order = 2)] + public int ItemId { get; set; } + + [Column("count", Order = 3)] + public int Count { get; set; } +} + +[Table("order_service.items")] +public class Item +{ + [PartitionKey] + [Column("item_id", Order = 0)] + public int Id { get; set; } + + [Column("name", Order = 1)] + public string Name { get; set; } = String.Empty; + + [Column("price", Order = 2)] + public int Price { get; set; } +} +``` + +パーティションキー、クラスタリングキー、またはセカンダリインデックスが複数の列で設定されている場合、`ColumnAttribute` の `Order` プロパティによってキーまたはインデックス内の順序が決まります。 + +プロパティに使用する型の詳細については、[ScalarDB 列型と .NET 型間の変換方法](common-reference.mdx#scalardb-列型と-net-型間の変換方法) を参照してください。 + +すべてのクラスが作成されたら、作成されたコンテキストを依存性注入コンテナに登録する必要があります。例: + +```c# + public class MyDbContext: ScalarDbContext + { + public ScalarDbSet Statements { get; set; } + public ScalarDbSet Items { get; set; } + } +``` + +:::note + +コンテキストクラスは一時的なサービスとして登録されます。サービス有効期間の詳細については、[.NET の依存関係の挿入 - サービスの有効期間](https://learn.microsoft.com/ja-jp/dotnet/core/extensions/dependency-injection#service-lifetimes)を参照してください。 + +::: + +すべてのクラスが作成されたら、作成されたコンテキストを依存性注入に追加する必要があります。例: + +```c# +using ScalarDB.Client.Extensions; + +//... + +var builder = WebApplication.CreateBuilder(args); + +//... + +builder.Services.AddScalarDbContext(); +``` + +コンテキストは、次のようにコントローラーのコンストラクターに挿入できます。 + +```c# +[ApiController] +public class OrderController: ControllerBase +{ + private readonly MyDbContext _myDbContext; + + public OrderController(MyDbContext myDbContext) + { + _myDbContext = myDbContext; + } +} +``` + +## LINQ を使用してプロパティをクエリする + +コントローラーで `MyDbContext` を受け取ったら、LINQ を使用してそのプロパティをクエリできます。例: + +### クエリ構文を使用する + +```c# +from stat in _myDbContext.Statements +join item in _myDbContext.Items on stat.ItemId equals item.Id +where stat.Count > 2 && item.Name.Contains("apple") +orderby stat.Count descending, stat.ItemId +select new { item.Name, stat.Count }; +``` + +### メソッド構文を使用する + +```c# +_myDbContext.Statements + .Where(stat => stat.OrderId == "1") + .Skip(1) + .Take(2); +``` + +### `First` メソッドを使用して、パーティションキーで1つの `Statement` を取得します。 + +```c# +_myDbContext.Statements.First(stat => stat.OrderId == "1"); +``` + +### `DefaultIfEmpty` メソッドを使用して左外部結合を実行します + +```c# +from stat in _myDbContext.Statements +join item in _myDbContext.Items on stat.ItemId equals item.Id into items +from i in items.DefaultIfEmpty() +select new { ItemName = i != null ? i.Name : "" } +``` + +以下のメソッドがサポートされています: + +- `Select` +- `Where` +- `Join` +- `GroupJoin` +- `First`/`FirstOrDefault` +- `Skip` +- `Take` +- `OrderBy`/`OrderByDescending` +- `ThenBy`/`ThenByDescending` + +次の `String` メソッドは、`Where` メソッドと `First`/`FirstOrDefault` メソッドの述語内でサポートされています。 + +- `Contains` +- `StartsWith` +- `EndsWith` + +サポートされていない LINQ メソッドは、サポートされているメソッドの後に使用できます。例: + +```c# +_myDbContext.Statements + .Where(stat => stat.OrderId == "1") // Will be executed remotely on the cluster. + .Distinct() // Will be executed locally in the app. + .Where(stat => stat.ItemId < 5); // Will be executed locally. +``` + +:::note + +`Take` または `First`/`FirstOrDefault` の前に `Skip` が指定されている場合、`Skip` に渡される数値が SQL クエリの `LIMIT` 数値に追加されます。`Skip` 自体では、結果の SQL クエリは変更されません。 + +::: + +## `ScalarDbSet{T}` オブジェクトに対して LINQ を使用する場合の制限 + +- すべてのメソッド呼び出しは `Select` 内でサポートされます。例: + +```c# +.Select(stat => convertToSomething(stat.ItemId)) +//... +.Select(stat => stat.ItemId * getSomeNumber()) +``` + +- クエリオブジェクトに対する呼び出しを除くメソッド呼び出しは、`Where` および `First`/`FirstOrDefault` 内でもサポートされます。例: + +```c# +.Where(stat => stat.ItemId == getItemId()) // is OK +//... +.Where(stat => stat.ItemId.ToString() == "1") // is not supported +``` + +- すべてのメソッド呼び出しは、`Join` および `GroupJoin` の結果選択ラムダ内でサポートされます。例: + +```c# +.Join(_myDbContext.Items, + stat => stat.ItemId, + item => item.Id, + (stat, item) => new { ItemName = convertToSomething(item.Name), + ItemCount = stat.Count.ToString() }) +``` + +- `Join` および `GroupJoin` のキー選択ラムダ内では、メソッド呼び出しはサポートされていません。 +- カスタム等価比較子はサポートされていません。`Join` および `GroupJoin` メソッドの `comparer` 引数は、引数が渡された場合は無視されます。 +- `DefaultIfEmpty` メソッドを使用して左外部結合を実行する場合を除き、1つのクエリ内で複数の `from` を直接使用することはサポートされていません。後続の各 `from` は、個別のクエリと見なされます。 + +```c# +var firstQuery = from stat in _myDbContext.Statements + where stat.Count > 2 + select new { stat.Count }; + +var secondQuery = from item in _myDbContext.Items + where item.Price > 6 + select new { item.Name }; + +var finalQuery = from first in firstQuery + from second in secondQuery + select new { first.Count, second.Name }; + +// 1. firstQuery will be executed against the cluster. +// 2. secondQuery will be executed against the cluster for each object (row) from 1. +// 3. finalQuery will be executed locally with the results from 1 and 2. +var result = finalQuery.ToArray(); +``` + +- メソッド呼び出しは、`OrderBy`/`OrderByDescending` または `ThenBy`/`ThenByDescending` 内ではサポートされていません。 +- `Where` および `First`/`FirstOrDefault` 内では、単一の文字列引数を持つ `Contains`、`StartsWith`、および `EndsWith` メソッドのオーバーロードのみがサポートされています。 + +## `ScalarDbContext` を使用してクラスター内のデータを変更する + +`ScalarDbContext` から継承されたクラスのプロパティを使用して、データを変更できます。 + +### `AddAsync` メソッドを使用して新しいオブジェクトを追加します + +```c# +var statement = new Statement + { + OrderId = "2", + ItemId = 4, + Count = 8 + }; +await _myDbContext.Statements.AddAsync(statement); +``` + +### `UpdateAsync` メソッドを使用してオブジェクトを更新する + +```c# +var statement = _myDbContext.Statements.First(stat => stat.Id == 1); + +// ... + +statement.Count = 10; +await _myDbContext.Statements.UpdateAsync(statement); +``` + +### `RemoveAsync` メソッドを使用してオブジェクトを削除する + +```c# +var statement = _myDbContext.Statements.First(stat => stat.Id == 1); + +// ... + +await _myDbContext.Statements.RemoveAsync(statement); +``` + +## トランザクションの管理 + +LINQ クエリと `AddAsync`、`UpdateAsync`、および `RemoveAsync` メソッドは、明示的に開始されたトランザクションなしで実行できます。ただし、1つのトランザクションの一部として複数のクエリとメソッドを実行するには、トランザクションを明示的に開始してコミットする必要があります。`ScalarDbContext` は、通常のトランザクションと、ScalarDB の2フェーズコミットインターフェイスを使用したトランザクションの両方をサポートします。 + +### 新しいトランザクションを開始する + +```c# +await _myDbContext.BeginTransactionAsync(); +``` + +### 2フェーズコミットインターフェースで新しいトランザクションを開始する + +```c# +await _myDbContext.BeginTwoPhaseCommitTransactionAsync(); +``` + +### 現在アクティブなトランザクションのIDを取得する + +```c# +var transactionId = _myDbContext.CurrentTransactionId; +``` + +### 2フェーズコミットインターフェースを使用して既存のトランザクションに参加する + +```c# +await _myDbContext.JoinTwoPhaseCommitTransactionAsync(transactionId); +``` + +### 既存のトランザクションを再開する + +```c# +await _myDbContext.ResumeTransaction(transactionId); +``` + +### 2フェーズコミットインターフェースを使用して既存のトランザクションを再開する + +```c# +await _myDbContext.ResumeTwoPhaseCommitTransaction(transactionId); +``` + +:::note + +`ResumeTransaction`/`ResumeTwoPhaseCommitTransaction` メソッドには非同期バージョンがありません。これは、クラスターを照会せずに `ScalarDbContext` 継承オブジェクト内のトランザクションデータを初期化するだけだからです。このため、間違った ID を使用してトランザクションを再開する可能性があります。 + +::: + +### トランザクションをコミットする(通常または2フェーズコミット) + +```c# +await _myDbContext.CommitTransactionAsync(); +``` + +### トランザクションをロールバックする(通常または2フェーズコミット) + +```c# +await _myDbContext.RollbackTransactionAsync(); +``` + +### コミット用の2フェーズコミットインターフェースを使用してトランザクションを準備する + +```c# +await _myDbContext.PrepareTransactionAsync(); +``` + +### コミット前に2フェーズコミットインターフェースでトランザクションを検証する + +```c# +await _myDbContext.ValidateTransactionAsync(); +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-scalardb-tables-as-csharp-classes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-scalardb-tables-as-csharp-classes.mdx new file mode 100644 index 00000000..30a247bc --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-scalardb-tables-as-csharp-classes.mdx @@ -0,0 +1,208 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK で C# クラスとしてテーブルをはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK は、ScalarDB テーブルを C# オブジェクトとして抽象化することで、クラスターにアクセスするコードの作成に役立ちます。クラスター内のテーブルを表すクラスを定義すると、クラスターをクエリするときに列名やその型が混同されないようにすることができます。さらに、テーブルの構造が変更された場合は、IDE のリファクタリング機能を使用してコードに変更を適用できます。 + +:::note + +次の例のように非同期メソッドを使用することをお勧めしますが、代わりに同期メソッドを使用することもできます。 + +::: + +## SDK をインストールする + +ScalarDB Cluster と同じメジャーバージョンとマイナーバージョンの [SDK](https://www.nuget.org/packages/ScalarDB.Client) を .NET プロジェクトにインストールします。組み込みの NuGet パッケージマネージャーを使用してこれを行うことができます。`.` を、使用しているバージョンに置き換えます。 + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## すべての ScalarDB テーブルのクラスを作成する + +ScalarDB テーブルを C# オブジェクトとして操作するには、使用するテーブルごとにクラスを作成する必要があります。例: + +```c# +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client.DataAnnotations; + +// ... + +[Table("ns.statements")] +public class Statement +{ + [PartitionKey] + [Column("order_id", Order = 0)] + public string OrderId { get; set; } = String.Empty; + + [ClusteringKey] + [Column("item_id", Order = 1)] + public int ItemId { get; set; } + + [Column("count", Order = 2)] + public int Count { get; set; } +} +``` + +プロパティに使用する型の詳細については、[ScalarDB 列型と .NET 型間の変換方法](common-reference.mdx#scalardb-列型と-net-型間の変換方法)を参照してください。 + +## CRUD 操作を実行する + +各テーブルのクラスを作成した後、`ITransactionCrudOperable` の汎用 `GetAsync`、`ScanAsync`、`InsertAsync`、`UpdateAsync`、`DeleteAsync`、`UpsertAsync`、または `MutateAsync` メソッドを使用して、クラスをオブジェクトとして使用できます。 + +これらの汎用メソッドを使用するには、`using` セクションに次の名前空間を追加します。 + +```c# +using ScalarDB.Client.Extensions; +``` + +### `GetAsync` メソッドを使用して1つのオブジェクトを取得します + +```c# +var keys = new Dictionary + { + { nameof(Statement.OrderId), "1" } + }; +var statement = await transaction.GetAsync(keys); + +Console.WriteLine($"ItemId: {statement.ItemId}, Count: {statement.Count}"); +``` + +### `ScanAsync` メソッドを使用して複数のオブジェクトを取得する + +```c# +var startKeys = new Dictionary + { + { nameof(Statement.OrderId), "1" }, + { nameof(Statement.ItemId), 3 } + }; +var endKeys = new Dictionary + { + { nameof(Statement.ItemId), 6} + }; + +await foreach (var s in transaction.ScanAsync(startKeys, endKeys)) + Console.WriteLine($"ItemId: {s.ItemId}, Count: {s.Count}"); +``` + +:::note + +`IAsyncEnumerable` で LINQ メソッドを使用するには、[System.Linq.Async](https://www.nuget.org/packages/System.Linq.Async/) パッケージをインストールします。 + +::: + +### `InsertAsync` メソッドを使用して新しいオブジェクトを挿入します + +```c# +var statement = new Statement + { + OrderId = "2", + ItemId = 4, + Count = 8 + }; +await transaction.InsertAsync(statement); +``` + +### `UpdateAsync` メソッドを使用してオブジェクトを更新する + +```c# +// ... +statement.ItemId = 4; +statement.Count = 8; + +await transaction.UpdateAsync(statement); +``` + +### `DeleteAsync` メソッドを使用してオブジェクトを削除する + +```c# +// ... +await transaction.DeleteAsync(statement); +``` + +### `UpsertAsync` メソッドを使用してオブジェクトをUPSERTする + +```c# +var statement = new Statement + { + OrderId = "2", + ItemId = 4, + Count = 8 + }; +await transaction.UpsertAsync(statement); +``` + +### `MutateAsync` メソッドを使用して複数のオブジェクトを一度にUPSERTおよび削除する + +```c# +var statement = new Statement + { + OrderId = "2", + ItemId = 4, + Count = 16 + }; + +// ... + +await transaction.MutateAsync(objectsToUpsert: new[] { statement }, + objectsToDelete: new[] { statement2 }); +``` + +:::note + +`UpdateAsync`、`DeleteAsync`、`UpsertAsync`、または `MutateAsync` メソッドを使用してオブジェクトを変更するには、まず `GetAsync` または `ScanAsync` メソッドを使用してオブジェクトを取得する必要があります。 + +::: + +## Administrative API を使用する + +C# オブジェクトも Administrative API で使用できます。汎用 Administrative API メソッドを使用するには、次の名前空間を `using` セクションに追加します。 + +```c# +using ScalarDB.Client.Extensions; +``` + +### 新しい名前空間を作成する + +```c# +await admin.CreateNamespaceAsync(); +``` + +### 既存の名前空間を削除する + +```c# +await admin.DropNamespaceAsync(); +``` + +### 名前空間が存在するかどうかを確認する + +```c# +var namespaceExists = await admin.IsNamespacePresentAsync(); +``` + +### 新しいテーブルを作成する + +```c# +await admin.CreateTableAsync(); +``` + +### 既存のテーブルを削除する + +```c# +await admin.DropTableAsync(); +``` + +### テーブルが存在するかどうかを確認する + +```c# +var tableExists = await admin.IsTablePresentAsync(); +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx new file mode 100644 index 00000000..03f35727 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx @@ -0,0 +1,146 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK の2フェーズコミットインターフェイスを使用した分散トランザクションをはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK は、ScalarDB の2フェーズコミットインターフェイスを使用したトランザクションをサポートします。SDK には、クラスター内の通信を強化するためのトランザクションとマネージャーの抽象化が含まれています。 + +:::note + +次の例のように非同期メソッドを使用することをお勧めしますが、代わりに同期メソッドを使用することもできます。 + +::: + +## 2フェーズコミットインターフェースを使用したトランザクションについて + +SDK を使用すると、複数のアプリケーションにまたがる2フェーズコミットインターフェースを使用したトランザクションを実行できます。たとえば、複数のマイクロサービスがある場合、それぞれのマイクロサービスにトランザクションマネージャーを作成し、それらのマイクロサービスにまたがるトランザクションを実行できます。 + +2フェーズコミットインターフェースを使用したトランザクションには、コーディネーターと参加者の2つのロールがあり、これらが協力して1つのトランザクションを実行します。 + +コーディネータープロセスは最初にトランザクションを開始し、トランザクションの ID をすべての参加者に送信し、参加者プロセスがトランザクションに参加します。 CRUD または SQL 操作を実行した後、コーディネータープロセスと参加者プロセスは2フェーズインターフェースを使用してトランザクションをコミットします。 + +## SDK をインストールする + +ScalarDB Cluster と同じメジャーバージョンとマイナーバージョンの [SDK](https://www.nuget.org/packages/ScalarDB.Client) を .NET プロジェクトにインストールします。組み込みの NuGet パッケージマネージャーを使用してこれを行うことができます。`.` を、使用しているバージョンに置き換えます。 + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## 設定ファイルを作成する + +`scalardb-options.json` ファイルを作成し、次の内容を追加します。`` を FQDN または IP アドレスに、`` をクラスターのポート番号 (デフォルトでは `60053`) に置き換えます。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +設定ファイルやクライアントを設定するその他の方法の詳細については、[クライアント設定](common-reference.mdx#クライアント設定)を参照してください。 + +## トランザクションマネージャーを取得します (コーディネータと参加者用) + +2フェーズコミットインターフェイスを使用した分散トランザクションには、トランザクションマネージャーを取得する必要があります。トランザクションマネージャーを取得するには、次のように `TransactionFactory` を使用します。 + +```c# +// Pass the path to the settings file created in the previous step. +var factory = TransactionFactory.Create("scalardb-options.json"); + +using var manager = factory.GetTwoPhaseCommitTransactionManager(); +``` + +あるいは、次のトランザクションマネージャーを指定して、2フェーズコミットインターフェイスを使用したトランザクションに CRUD 操作の代わりに SQL を使用することもできます。 + +```c# +using var manager = factory.GetSqlTwoPhaseCommitTransactionManager(); +``` + +## トランザクションを開始する (コーディネータ用) + +次のように、コーディネータの2フェーズコミットインターフェイスを使用してトランザクションを開始できます。 + +```c# +var transaction = await manager.BeginAsync(); +``` + +開始されたトランザクションの ID は、次のコードで取得できます。 + +```c# +var transactionId = transaction.Id; +``` + +## トランザクションに参加する (参加者向け) + +参加者の2フェーズコミットインターフェイスを使用して、次のようにトランザクションに参加できます。 + +```c# +var transaction = await manager.JoinAsync(transactionId); +``` + +## トランザクションを再開する (コーディネータと参加者用) + +通常、2フェーズコミットインターフェイスを使用したトランザクションには、複数の要求と応答の交換が含まれます。以前の要求で開始または参加したトランザクションを操作する必要がある場合は、次のようにしてそのトランザクションを再開できます。 + +```c# +var transaction = manager.Resume(transactionId); +``` + +:::note + +`Resume` メソッドはトランザクションオブジェクトを作成するだけなので、非同期バージョンはありません。このため、間違った ID を使用してトランザクションを再開する可能性があります。 + +::: + +## トランザクションをロールバックする + +トランザクションがコミットに失敗した場合は、次のようにトランザクションをロールバックできます。 + +```c# +await transaction.RollbackAsync(); +``` + +## トランザクションをコミットする (コーディネータと参加者用) + +CRUD または SQL 操作を完了したら、トランザクションをコミットする必要があります。ただし、2フェーズコミットインターフェイスを使用したトランザクションの場合は、まずコーディネータとすべての参加者でトランザクションを準備する必要があります。 + +```c# +await transaction.PrepareAsync(); +``` + +次に、並行性制御プロトコルに応じて、次のようにコーディネーターとすべての参加者でトランザクションを検証する必要がある場合があります。 + +```c# +await transaction.ValidateAsync(); +``` + +最後に、次のようにしてコーディネーターとすべての参加者にトランザクションをコミットできます。 + +```c# +await transaction.CommitAsync(); +``` + +コーディネータまたは参加者のいずれかがトランザクションの準備または検証に失敗した場合は、コーディネータとすべての参加者で `RollbackAsync` を呼び出す必要があります。 + +また、コーディネータとすべての参加者がトランザクションのコミットに失敗した場合は、コーディネータとすべての参加者で `RollbackAsync` を呼び出す必要があります。 + +ただし、コーディネータまたは一部の参加者のみがトランザクションのコミットに失敗した場合は、コーディネータまたはいずれかの参加者がトランザクションのコミットに成功している限り、トランザクションはコミットされたとみなされます。 + +## CRUD 操作を実行する + +トランザクションの2フェーズコミットインターフェイスには、通常のトランザクションと同じ CRUD 操作メソッドがあります。詳細については、[CRUD 操作を実行する](getting-started-with-distributed-transactions.mdx#crud-操作を実行する) を参照してください。 + +## SQL ステートメントを実行する + +SQL トランザクションの2フェーズコミットインターフェイスには、通常の SQL トランザクションと同じ SQL クエリを実行するメソッドがあります。詳細については、[SQL クエリを実行する](getting-started-with-distributed-sql-transactions.mdx#sql-クエリを実行する)を参照してください. diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/index.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/index.mdx new file mode 100644 index 00000000..fa80ad09 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster-dotnet-client-sdk/index.mdx @@ -0,0 +1,26 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster .NET Client SDK の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster .NET Client SDK を使用すると、アプリケーションは gRPC を使用して ScalarDB Cluster に接続できるようになります。 + +ScalarDB Cluster .NET Client SDK を使用するには、次の入門ガイドを参照してください。 + +* [分散トランザクションをはじめよう](getting-started-with-distributed-transactions.mdx) +* [分散 SQL トランザクションをはじめよう](getting-started-with-distributed-sql-transactions.mdx) +* [Administrative API をはじめよう](getting-started-with-admin-api.mdx) +* [C# クラスとしての ScalarDB テーブルをはじめよう](getting-started-with-scalardb-tables-as-csharp-classes.mdx) +* [ASP.NET Core と依存性注入をはじめよう](getting-started-with-aspnet-and-di.mdx) +* [LINQ をはじめよう](getting-started-with-linq.mdx) +* [2フェーズコミットインターフェイスを使用した分散トランザクションをはじめよう](getting-started-with-two-phase-commit-transactions.mdx) +* [認証と認可をはじめよう](getting-started-with-auth.mdx) +* [例外処理](exception-handling.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/authorize-with-abac.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/authorize-with-abac.mdx new file mode 100644 index 00000000..c9a639a0 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/authorize-with-abac.mdx @@ -0,0 +1,863 @@ +--- +tags: + - Enterprise Premium Option + - Private Preview +displayed_sidebar: docsJapanese +--- + +# ユーザーアクセスをきめ細かく制御する + +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster は、属性ベースのアクセス制御 (ABAC) と呼ばれるメカニズムを使用して、ユーザーをきめ細かく認証できます。このページでは、ScalarDB Cluster で ABAC を使用する方法について説明します。 + +## ABAC とは? + +ABAC は ScalarDB Cluster のきめ細かいアクセス制御メカニズムであり、[単純な認証](./scalardb-auth-with-sql.mdx)によって実行されるテーブルレベルのアクセス制御だけでなく、レコードレベルのアクセス制御を可能にします。ABAC を使用すると、ユーザーは、ユーザーの属性とレコードの属性が一致する場合にのみ、特定のレコードにアクセスできます。たとえば、機密性の高いレコードへのアクセスを、必要な権限を持つユーザーのみに制限できます。このメカニズムは、複数のアプリケーションが同じテーブルを共有しているが、それぞれの権限に基づいて異なるセグメントにアクセスする必要がある場合にも役立ちます。 + +## ABAC を使用する理由 + +エンタープライズデータベースでは、多くの場合、行レベルのセキュリティまたは同様の代替手段が提供され、データベーステーブル内の行へのアクセスを制御できます。ただし、システムが複数のデータベースで構成されている場合は、各データベースを1つずつ同じ方法で設定する必要があります。異なる種類のデータベースを使用する場合は、各データベースの機能の違いを理解した上で各データベースを設定する必要があります。このような設定は負担が大きすぎ、エラーが発生しやすくなります。ABAC を使用すると、ScalarDB で複数のデータベースを管理する場合でも、1回設定するだけで済みます。 + +ほとんどのデータベースの行レベルのセキュリティ機能では、ストアドプロシージャなどの関数を使用してマッチングロジックを実装する必要があります。これにより、必要なロジックを実現するために大量のコードを記述することになり、負担が大きくなることがあります。対照的に、ABAC では、タグと呼ばれる属性を使用してマッチングロジックを設定できます。ABAC では、これらのタグを定義してユーザーとレコードに割り当てるだけでよいため、コーディングの必要がありません。タグは、柔軟かつ簡単な方法でマッチングロジックを指定できる複数のコンポーネントで構成されています。 + +## コンポーネント + +ABAC には、タグやポリシーなどのいくつかのコンポーネントがあります。 + +### タグ + +タグは、レベル、コンパートメント、グループの3つのコンポーネントで構成される単一の属性であり、ユーザーやデータに割り当てることができます。ユーザーに割り当てられたタグは `ユーザータグ` と呼ばれ、データに割り当てられたタグは `データタグ` と呼ばれます。 + +#### レベル + +レベルコンポーネントはデータの機密性を示します。すべてのユーザータグとデータタグにはレベルが必要です。たとえば、ユーザーは `機密`、`機密性の高い`、`非常に機密性の高い` などのレベルを定義できます。 + +各レベルについて、スーパーユーザーは次の属性を定義します。 + +| 属性 | 説明 | +|---------------|---------------------------------------------------------| +| 短い名前 | レベルの短い識別子。この名前は最大30文字まで含めることができます。 | +| 長い名前 | レベルの長く説明的な名前。 | +| レベル番号 | レベルのランクを表す数値。 | + +:::note + +スーパーユーザーは各レベル (および他のタグコンポーネント) の長い名前と短い名前の両方を定義しますが、ABAC の下で行を取得する際に表示されるのは短い名前のみです。ユーザーがタグを操作する際には、コンポーネントの短い名前のみを使用する必要があります。 + +::: + +#### コンパートメント + +コンパートメントコンポーネントはオプションであり、コンパートメントは互いに独立しています。通常、1つ以上のコンパートメントが定義され、データを異なるカテゴリに分類します。コンパートメントは、特定のデータタイプ、知識領域、地理的地域、または特別な承認が必要なプロジェクトを表すことがあります。たとえば、`HR`、`Finance`、`Accounting` などです。 + +各コンパートメントについて、スーパーユーザーは次の属性を定義します。 + +| 属性 | 説明 | +|--------------|-----------------------------------------------------------------| +| 短い名前 | コンパートメントの短い識別子。この名前は最大30文字まで含めることができます。 | +| 長い名前 | コンパートメントの長く説明的な名前。 | + +#### グループ + +グループコンポーネントもオプションであり、コンパートメントと似ていますが、1つの重要な違いがあります。グループは親子関係を持つことができます。通常、1つ以上のグループが定義され、データを整理します。グループは、組織構造や地域ごとにデータをセグメント化するために最もよく使用されます。たとえば、`EU` には子グループ `France` と `Italy` があり、`North America` には子グループ `US` と `Canada` があります。 + +各グループについて、スーパーユーザーは次の属性を定義します。 + +| 属性 | 説明 | +|--------------|----------------------------------------------------------| +| 短い名前 | グループの短い識別子。この名前は最大30文字まで含めることができます。 | +| 長い名前 | グループの長く説明的な名前。 | + +#### タグ構文 + +タグは、レベル、コンパートメント、およびグループで構成される文字列として表されます。タグの構文は次のとおりです。 + +```plaintext +LEVEL:COMPARTMENT1,...,COMPARTMENTn:GROUP1,...,GROUPn +``` + +コロン (`:`) はコンポーネント間の区切り文字として使用されます。末尾の区切り文字は省略可能です。 + +たとえば、レベルが `SENSITIVE`、コンパートメントが `HR` と `FINANCIAL`、グループが `EU` と `NA` のタグは次のようになります。 + +```plaintext +SENSITIVE:HR,FINANCIAL:EU,NA +``` + +コンパートメントやグループがない場合、タグは次のようになります。 + +```plaintext +SENSITIVE +``` + +コンパートメントがあり、グループがない場合、タグは次のようになります。 + +```plaintext +SENSITIVE:HR,FINANCIAL +``` + +グループがあり、コンパートメントがない場合、タグは次のようになります。 + +```plaintext +SENSITIVE::EU,NA +``` + +### ポリシー + +ABAC ポリシーは、アクセス制御の動作を定義するメタデータを格納するコンテナです。このコンテナには、ポリシー名と、保護されたテーブルに ABAC が追加する列の名前 (データタグ列) が指定されます。この列には、テーブル内の各行に割り当てられたデータタグが格納されます。 + +スーパーユーザーは、固有の名前を持つ複数のポリシーを作成できます。各ポリシーには1つのデータタグ列しか持つことができず、データタグ列の名前はすべてのポリシーで一意である必要があります。 + +データタグ列は非表示の列であり、デフォルトでは表示されません。データタグ列を操作するには、クエリに明示的に含める必要があります。 + +#### 名前空間ポリシーとテーブルポリシー + +名前空間ポリシーは、名前空間に適用される ABAC ポリシーです。名前空間に名前空間ポリシーがある場合、その名前空間のすべてのテーブルは適用されたポリシーを使用します。同様に、テーブルポリシーはテーブルに適用される ABAC ポリシーです。 + +名前空間またはテーブルポリシーが作成されると、データタグ列は自動的に名前空間内のすべてのテーブルまたは指定されたテーブルに追加されます。さらに、名前空間に名前空間ポリシーが既にある場合、その名前空間に後で追加されたテーブルにもデータタグ列が自動的に追加されます。 + +## ユーザーおよびデータタグを使用してユーザーアクセスを制御する + +ABAC は、ユーザーおよびデータのタグを定義し、それらが一致するかどうかを確認することでユーザーアクセスを制御します。 + +ABAC ポリシーがデータへのアクセスを制御するために使用する2つの主要なコンポーネントがあります。 + +- **ユーザータグ:** ユーザータグは、ユーザーの機密性レベルと、タグ付けされたデータへのアクセスを制約するコンパートメントおよびグループを定義します。 +- **データタグ:** 各行に割り当てられたデータタグは、その行の機密性レベルを示し、ユーザーがその行にアクセスするために認可される必要があるコンパートメントおよびグループを含みます。 + +ABAC で保護されたデータにアクセスするには、ユーザーはポリシーで定義されたタグに基づいて適切な認可を持っている必要があります。 + +### ユーザータグ + +各 ABAC ユーザーには、次のコンポーネントを含む認可が設定されています。 + +- 最大レベル +- 認可されたコンパートメントのセット +- 認可されたグループのセット +- 各コンパートメントおよびグループごとに、読み取り専用アクセスまたは読み取り/書き込みアクセスの指定 + +#### 読み取りおよび書き込みタグ + +読み取りタグは、ユーザーが読み取りを許可されたレベル、コンパートメント、およびグループの特定の組み合わせであり、ユーザーがデータを読み取るときに使用されます。書き込みタグは、ユーザーが書き込みを許可されたレベル、コンパートメント、およびグループの特定の組み合わせであり、ユーザーがデータを書き込むときに使用されます。 + +ユーザーは、各操作の読み取りおよび書き込みタグを指定してデータへのアクセスをさらに制限できますが、デフォルトの読み取りおよび書き込みタグがデフォルトで使用されます。詳細については、[各操作のユーザータグを調整する](#各操作のユーザータグを調整する)を参照してください。 + +#### 行タグ + +行タグは、ユーザーが書き込みを許可されたレベル、コンパートメント、およびグループの特定の組み合わせであり、新しく挿入されたデータのデータタグとして使用されます。 + +ユーザーは、`INSERT` および `UPSERT` 操作の行タグを指定できますが、デフォルトの行タグがデフォルトで使用されます。詳細については、[各操作のユーザータグを調整する](#各操作のユーザータグを調整する)を参照してください。 + +#### ユーザータグ情報 + +スーパーユーザーは、ユーザーに対してレベル、コンパートメント、およびグループの認可を明示的に設定します。これをユーザータグ情報と呼びます。 + +- レベル + - レベル + - ユーザーが読み取りおよび書き込み操作中にアクセスできる最大の機密性レベル。 + - デフォルトレベル + - ユーザーのデフォルトタグで使用されるレベル。 + - 行レベル + - ユーザーのデフォルト行タグで使用されるレベル。 +- コンパートメント + - アクセスモード: `READ_ONLY` または `READ_WRITE` + - ユーザーがタグにコンパートメントを含むデータに書き込みを許可されているかどうかを決定します。 + - デフォルト + - コンパートメントがユーザーのデフォルトタグに追加されるかどうかを決定します。 + - 行 + - コンパートメントがユーザーのデフォルト行タグに追加されるかどうかを決定します。 +- グループ + - アクセスモード: `READ_ONLY` または `READ_WRITE` + - ユーザーがタグにグループを含むデータに書き込みを許可されているかどうかを決定します。 + - デフォルト + - グループがユーザーのデフォルトタグに追加されるかどうかを決定します。 + - 行 + - グループがユーザーのデフォルト行タグに追加されるかどうかを決定します。 + +##### 計算されたユーザータグ + +ABAC は、ユーザータグ情報に基づいていくつかのユーザータグを自動的に計算します。 + +| 計算されたユーザータグ | 説明 | +|----------------------------|-------------------------------------------------------------------------------------------------------------------------| +| **最大読み取りタグ** | ユーザーのレベルと、ユーザーがアクセスできるすべての認可されたコンパートメントおよびグループの組み合わせ。 | +| **最大書き込みタグ** | ユーザーのレベルと、ユーザーが書き込みアクセス権を持つすべてのコンパートメントおよびグループの組み合わせ。 | +| **デフォルト読み取りタグ** | ユーザーのデフォルトレベルと、ユーザーにデフォルトとして指定されたコンパートメントおよびグループの組み合わせ。 | +| **デフォルト書き込みタグ** | デフォルト読み取りタグのサブセットであり、ユーザーが書き込みアクセス権を持つコンパートメントおよびグループのみを含む。 | +| **デフォルト行タグ** | ユーザーの書き込みタグのコンポーネントの組み合わせであり、デフォルトで新しく挿入されたデータのデータタグとして使用される。 | + +### データタグ + +データタグは各行に割り当てられ、その行の機密性レベルを示し、ユーザーがその行にアクセスするために認可される必要があるコンパートメントおよびグループを含みます。新しいデータが挿入されると、行タグがデータタグとして使用されます。既存の行のデータタグを更新することもできます。詳細については、[データタグを更新する](#データタグを更新する)を参照してください。 + +### マッチングアルゴリズム + +このセクションでは、読み取りおよび書き込みのマッチングアルゴリズムについて説明します。 + +#### 読み取りのマッチングアルゴリズム + +このフローチャートは、読み取りのマッチングアルゴリズムを示しています。このアルゴリズムは、`SELECT`、`UPSERT`、`UPDATE`、および `DELETE` ステートメントで使用されます。 + +```mermaid +flowchart LR + A[ユーザーレベル >= データレベル?] + B[データにグループがあるか?] + C[ユーザーが少なくとも1つのグループを持っているか?] + D[データにコンパートメントがあるか?] + E[ユーザーがすべてのコンパートメントを持っているか?] + F[アクセス] + G[アクセス拒否] + A -->|はい| B + A -->|いいえ| G + B -->|はい| C + B -->|いいえ| D + C -->|はい| D + C -->|いいえ| G + D -->|はい| E + D -->|いいえ| F + E -->|はい| F + E -->|いいえ| G +``` + +1. ユーザーのレベルがデータのレベル以上であるかどうかを確認します。 +2. はいの場合、かつデータにグループがある場合、ユーザーがデータタグに含まれるグループの少なくとも1つにアクセスできるかどうかを確認します。 +3. はいの場合、かつデータにコンパートメントがある場合、ユーザーがデータタグに含まれるすべてのコンパートメントにアクセスできるかどうかを確認します。 +4. すべての条件が満たされている場合、ユーザーはデータにアクセスできます。いずれかの条件が満たされない場合、ScalarDB はデータへのアクセスを拒否します。 + +#### 書き込みのマッチングアルゴリズム + +このフローチャートは、書き込みのマッチングアルゴリズムを示しており、読み取りのアルゴリズムと似ています。違いは、書き込みのアルゴリズムは、コンパートメントとグループに書き込みアクセスがあるかどうかも確認することです。このアルゴリズムは、`UPSERT`、`UPDATE`、および `DELETE` ステートメントで使用されます。 + +```mermaid +flowchart LR + A[ユーザーレベル >= データレベル?] + B[データにグループがあるか?] + C[ユーザーが書き込みアクセス権を持つ少なくとも1つのグループを持っているか?] + D[データにコンパートメントがあるか?] + E[ユーザーが書き込みアクセス権を持つすべてのコンパートメントを持っているか?] + F[アクセス] + G[アクセス拒否] + A -->|はい| B + A -->|いいえ| G + B -->|はい| C + B -->|いいえ| D + C -->|はい| D + C -->|いいえ| G + D -->|はい| E + D -->|いいえ| F + E -->|はい| F + E -->|いいえ| G +``` + +1. ユーザーのレベルがデータのレベル以上であるかどうかを確認します。 +2. はいの場合、かつデータにグループがある場合、ユーザーがデータタグに含まれるグループの少なくとも1つに対して書き込みアクセス権を持っているかどうかを確認します。 +3. はいの場合、かつデータにコンパートメントがある場合、ユーザーがデータタグに含まれるすべてのコンパートメントに対して書き込みアクセス権を持っているかどうかを確認します。 +4. すべての条件が満たされている場合、ユーザーはデータにアクセスできます。いずれかの条件が満たされない場合、ScalarDB はデータへのアクセスを拒否します。 + +#### グループの読み取り/書き込み認可の伝播 + +ユーザーが親グループに読み取り/書き込みアクセス権を持っている場合、自動的にその子グループにも読み取り/書き込みアクセス権を継承します。さらに、スーパーユーザーは、親グループのアクセス権に影響を与えずに、子グループに書き込みアクセス権を独立して付与できます。 + +#### ユーザータグとデータタグの連携方法 + +ユーザーは、自分のタグ認可の範囲内でのみデータにアクセスできます。 + +たとえば、ポリシーで次のレベル、コンパートメント、およびグループが定義されているとします。 + +レベル: + +- `HS` (`HIGHLY_SENSITIVE`)、レベル番号は 4000 +- `S` (`SENSITIVE`)、レベル番号は 3000 +- `C` (`CONFIDENTIAL`)、レベル番号は 2000 +- `P` (`PUBLIC`)、レベル番号は 1000 + +コンパートメント: + +- `HR` +- `FIN` +- `LEG` + +グループ: + +- `EU` +- `FRA` (`EU` の子) +- `ITA` (`EU` の子) +- `NA` +- `US` (`NA` の子) + +次に、以下のテーブルがあるとします。 + +| 行 | データタグ | +|----|------------------| +| 1 | `S:HR:EU` | +| 2 | `C:HR,FIN:FRA` | +| 3 | `HS:HR,FIN:EU` | +| 4 | `C:HR:NA` | +| 5 | `P:LEG:EU` | +| 6 | `P:FIN:ITA` | +| 7 | `P:HR:US` | + +読み取りタグ `S:HR,FIN:EU` を使用してテーブルで読み取り操作を行うと、行 `1`、`2`、および `6` にアクセスできます。以下はその理由です。 + +- 読み取りタグに `S` レベルが含まれているため、`S`、`C`、および `P` レベルの行にアクセスできます。認可されたレベルよりも高い `HS` レベルのデータにはアクセスできません。したがって、`HS` レベルの行 `3` を読み取ることはできません。 +- 読み取りタグに `HR` および `FIN` コンパートメントが含まれているため、これらのコンパートメントのいずれかまたは両方を持つ行にアクセスできます。したがって、`LEG` コンパートメントを持つ行 `5` を読み取ることはできません。 +- 読み取りタグに `EU` グループが含まれているため、`EU` グループまたはその子グループ `FRA` および `ITA` に属する行にアクセスできます。したがって、`NA` および `US` グループを持つ行 `4` および `7` を読み取ることはできません。 + +書き込みタグ `C:HR:NA` を使用してテーブルで書き込み操作を行うと、行 `4` および `7` に書き込むことができます。以下はその理由です。 + +- 書き込みタグに `C` レベルが含まれているため、`C` および `P` レベルのデータに書き込むことができます。認可されたレベルよりも高い `S` および `HS` レベルのデータには書き込むことができません。したがって、`1` および `3` の行に書き込むことはできません。 +- 書き込みタグに `HR` コンパートメントが含まれているため、このコンパートメントを持つデータに書き込むことができます。したがって、`FIN` および `LEG` コンパートメントを持つ行 `2`、`3`、`5`、および `6` に書き込むことはできません。 +- 書き込みタグに `NA` グループが含まれているため、`NA` グループまたはその子グループ `US` に属するデータに書き込むことができます。したがって、`EU`、`FRA`、および `ITA` グループを持つ行 `1`、`2`、`3`、`5`、および `6` に書き込むことはできません。 + +### 各操作のユーザータグを調整する + +デフォルトでは、ABAC は各操作に対してデフォルトの計算されたユーザータグを使用します。ただし、ユーザーは各操作のタグを調整してデータへのアクセスをさらに制限できます。 + +#### 読み取りタグを調整する + +ユーザーがデータを読み取るとき、デフォルトではユーザータグ情報からのデフォルトの読み取りタグが使用されます。データの読み取りは、`SELECT`、`UPSERT`、`UPDATE`、および `DELETE` 操作を行うときに発生します。 + +ただし、ユーザーは操作ごとに読み取りタグを指定してデータへのアクセスをさらに制限できます。このタグのレベルは、ユーザータグ情報のレベルまで設定できます。そして、コンパートメントとグループは、ユーザータグ情報に含まれるコンパートメントとグループに設定できます。 + +指定された読み取りタグを使用してデータを読み取る構文は次のとおりです。 + +`SELECT` の場合: + +```sql +SELECT * FROM table_name WHERE ... WITH ABAC_READ_TAG '' FOR POLICY ''; +``` + +`UPSERT` の場合: + +```sql +UPSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...) WITH ABAC_READ_TAG '' FOR POLICY ''; +``` + +`UPDATE` の場合: + +```sql +UPDATE table_name SET column1 = value1, column2 = value2, column3 = value3, ... WHERE ... WITH ABAC_READ_TAG '' FOR POLICY ''; +``` + +`DELETE` の場合: + +```sql +DELETE FROM table_name WHERE ... WITH ABAC_READ_TAG '' FOR POLICY ''; +``` + +#### 書き込みタグを調整する + +ユーザーがデータを書き込む場合、デフォルトではユーザータグ情報からのデフォルトの書き込みタグが使用されます。これは、`UPSERT`、`UPDATE`、および `DELETE` 操作に適用され、これらには何らかの形で書き込み操作が含まれます。 + +ただし、ユーザーは操作ごとにタグを設定してデータへのアクセスをさらに制限することができます。このタグのレベルは、ユーザータグ情報のレベルまで設定できます。ただし、このタグのコンパートメントとグループはより制限されています。このタグには、ユーザータグ情報に含まれるコンパートメントとグループのみを含めることができ、その中でもユーザーが書き込みアクセス権を持つものだけを含めることができます。 + +書き込みタグを指定してデータを書き込む構文は次のとおりです。 + +`UPSERT` の場合: + +```sql +UPSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...) WITH ABAC_WRITE_TAG '' FOR POLICY ''; +``` + +`UPDATE` の場合: + +```sql +UPDATE table_name SET column1 = value1, column2 = value2, column3 = value3, ... WHERE ... WITH ABAC_WRITE_TAG '' FOR POLICY ''; +``` + +`DELETE` の場合: + +```sql +DELETE FROM table_name WHERE ... WITH ABAC_WRITE_TAG '' FOR POLICY ''; +``` + +#### 行タグを調整する + +ユーザーがデータを挿入する際にデータタグを指定しない場合、デフォルトでユーザータグ情報からのデフォルトの行タグが自動的に割り当てられます。 + +ただし、ユーザーは書き込まれる行のデータタグをユーザータグ情報の特定の制限内で設定できます。このタグのレベルは、ユーザータグ情報のレベルまで設定できます。ただし、この行の新しいタグのコンパートメントとグループはより制限されています。新しいタグには、ユーザータグ情報に含まれるコンパートメントとグループのみを含めることができ、その中でもユーザーが書き込みアクセス権を持つものだけを含めることができます。 + +データタグを指定してデータを挿入する構文は次のとおりです。 + +`INSERT` の場合: + +```sql +INSERT INTO table_name (column1, column2, column3, ..., ) VALUES (value1, value2, value3, ..., ''); +``` + +`UPSERT` の場合: + +```sql +UPSERT INTO table_name (column1, column2, column3, ..., ) VALUES (value1, value2, value3, ..., ''); +``` + +データを挿入する際に、列リストにデータタグ列を含め、値リストにデータタグ値を提供することで、データタグを指定できます。 + +:::note + +データタグ列は本質的に非表示の列であるため、データタグを設定または調整する場合は、列リストにデータタグ列を明示的に含める必要があります。 + +::: + +### データタグを表示する + +ユーザーがデータを読み取る際に、`SELECT` ステートメントで明示的に指定することで、データタグをデータと一緒に表示できます。 + +```sql +SELECT column1, column2, column3, ..., FROM table_name; +``` + +### データタグを更新する + +ユーザーが既存のデータを更新する際に、データタグを指定することでデータタグを更新できます。ユーザーは、ユーザータグ情報の特定の制限内でデータタグを更新できます。このタグのレベルは、ユーザータグ情報のレベルまで設定できます。ただし、このデータタグのコンパートメントとグループはより制限されています。データタグには、ユーザータグ情報に含まれるコンパートメントとグループのみを含めることができ、その中でもユーザーが書き込みアクセス権を持つものだけを含めることができます。 + +データタグを更新する構文は次のとおりです。 + +`UPDATE` の場合: + +```sql +UPDATE table_name SET column1 = value1, column2 = value2, column3 = value3, ..., = '' WHERE ...; +``` + +`UPSERT` の場合: + +```sql +UPSERT INTO table_name (column1, column2, column3, ..., ) VALUES (value1, value2, value3, ..., ''); +``` + +### 設定 + +ABAC 機能を有効にするには、ScalarDB Cluster ノードの設定ファイルで `scalar.db.cluster.abac.enabled` を `true` に設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|----------------------------------|-------------------------------|------------| +| `scalar.db.cluster.abac.enabled` | ABAC 機能が有効かどうか。 | `false` | + +:::warning + +ABAC 機能を有効にする場合は、次のことも行う必要があります。 + +- 認証と認可を有効にします。詳細については、[ユーザーの認証と認可](./scalardb-auth-with-sql.mdx)を参照してください。 +- システム名前空間 (デフォルトは `scalardb`) のために `scalar.db.cross_partition_scan.enabled` を `true` に設定します。これは、ABAC 機能が内部的にクロスパーティションスキャンを実行するためです。 + +::: + +次のプロパティも設定できます。 + +| 名前 | 説明 | デフォルト | +|-------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------| +| `scalar.db.cluster.abac.cache_expiration_time_millis` | ABAC メタデータキャッシュのキャッシュ有効期限 (ミリ秒単位)。ABAC メタデータ (たとえば、ポリシー設定) を更新する場合、変更が適用されるまでこの有効期限が経過するのを待つ必要がある場合があります。このプロパティを低い値に設定すると、バックエンドデータベースへのアクセス回数が増加し、パフォーマンスが低下する可能性があります。 | `60000` (1分) | + +### 制限事項 + +- 単一の CRUD 操作トランザクションマネージャーは ABAC をサポートしていません。 +- データタグ列は `WHERE` 句や `ORDER BY` 句で使用できません。 + +## チュートリアル: ABAC の使用方法 + +このチュートリアルでは、ABAC 機能の使用方法を説明します。 + +### 前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10 以降、および [Docker Compose](https://docs.docker.com/compose/install/) V2 以降 + +:::note + +このチュートリアルは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。ScalarDB の要件の詳細については、互換性のある JDK ディストリビューションを含む[要件](../requirements.mdx)を参照してください。 + +::: + + + +### 1. ScalarDB Cluster の設定ファイルを作成する + +次の設定ファイルを `scalardb-cluster-node.properties` として作成し、`` および `` を ScalarDB ライセンスキーおよびライセンスチェック証明書の値に置き換えます。ライセンスキーと証明書の詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + +```properties +scalar.db.storage=jdbc +scalar.db.contact_points=jdbc:postgresql://postgresql:5432/postgres +scalar.db.username=postgres +scalar.db.password=postgres +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.cross_partition_scan.enabled=true +scalar.db.cross_partition_scan.filtering.enabled=true +scalar.db.sql.enabled=true + +# Enable authentication and authorization +scalar.db.cluster.auth.enabled=true + +# Enable ABAC +scalar.db.cluster.abac.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +### 2. Docker Compose ファイルを作成する + +次の設定ファイルを `docker-compose.yaml` として作成します。 + +```yaml +services: + postgresql: + container_name: "postgresql" + image: "postgres:15" + ports: + - 5432:5432 + environment: + - POSTGRES_PASSWORD=postgres + healthcheck: + test: ["CMD-SHELL", "pg_isready || exit 1"] + interval: 1s + timeout: 10s + retries: 60 + start_period: 30s + + scalardb-cluster-standalone: + container_name: "scalardb-cluster-node" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-with-abac-byol-premium:3.15.4" + ports: + - 60053:60053 + - 9080:9080 + volumes: + - ./scalardb-cluster-node.properties:/scalardb-cluster/node/scalardb-cluster-node.properties + depends_on: + postgresql: + condition: service_healthy +``` + +:::note + +`ghcr.io/scalar-labs/scalardb-cluster-node-with-abac-byol-premium` イメージは、ABAC 機能が有効になっている ScalarDB Cluster ノードイメージであり、公開されていません。このイメージへのアクセスを取得するには、[お問い合わせ](https://www.scalar-labs.com/contact)ください。 + +::: + +### 3. PostgreSQL と ScalarDB Cluster を起動する + +次のコマンドを実行して、PostgreSQL とスタンドアローンモードの ScalarDB Cluster を起動します。 + +```console +docker compose up -d +``` + +ScalarDB Cluster が完全に起動するまでに数分かかる場合があります。 + +### 4. スーパーユーザーとして ScalarDB Cluster に接続する + +ScalarDB Cluster に接続するには、このチュートリアルでは SQL CLI を使用します。SQL CLI は、ScalarDB Cluster に接続して SQL クエリを実行するためのツールです。SQL CLI は [ScalarDB リリースページ](https://github.com/scalar-labs/scalardb/releases)からダウンロードできます。 + +`scalardb-cluster-sql-cli.properties` という名前の設定ファイルを作成します。このファイルは、SQL CLI を使用して ScalarDB Cluster に接続するために使用されます。 + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost + +# Enable authentication and authorization +scalar.db.cluster.auth.enabled=true +``` + +次に、以下のコマンドを実行して SQL CLI を起動します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +ユーザー名とパスワードとして、それぞれ `admin` と `admin` を入力します。 + +これで、ABAC 機能が有効になっている ScalarDB Cluster を使用する準備が整いました。 + +### 5. 名前空間とテーブルを作成する + +名前空間を作成します。 + +```sql +CREATE NAMESPACE n; +``` + +次に、`n` 名前空間にテーブルを作成します。 + +```sql +CREATE TABLE n.t ( + id INT PRIMARY KEY, + col INT); +``` + +### 6. ユーザーを作成し、テーブルへのアクセス権を付与する + +ユーザーを作成します。 + +```sql +CREATE USER user1 WITH PASSWORD 'user1'; +CREATE USER user2 WITH PASSWORD 'user2'; +CREATE USER user3 WITH PASSWORD 'user3'; +``` + +次に、ユーザーにテーブルへのアクセス権を付与します。 + +```sql +GRANT ALL ON n.t TO user1; +GRANT ALL ON n.t TO user2; +GRANT ALL ON n.t TO user3; +``` + +### 7. ポリシーを作成する + +ABAC ポリシーを作成する必要があります。これは、ポリシーの動作を説明するメタデータを格納するコンテナです。 + +この例では、次のコマンドを実行して、データタグ列名を `data_tag` とする `p` という名前のポリシーを作成できます。 + +```sql +CREATE ABAC_POLICY p WITH DATA_TAG_COLUMN data_tag; +``` + +:::note + +データタグ列を省略した場合、デフォルトの列名 `_data_tag` が使用されます。 + +::: + +次のコマンドを実行して、作成されたポリシーを確認できます。 + +```sql +SHOW ABAC_POLICIES; +``` + +出力に作成されたポリシー `p` が表示されます。 + +### 8. ポリシーにレベルを作成する + +次に、ポリシーにレベルを作成します。 + +この例では、次のコマンドを実行して、`HS` (`HIGHLY_SENSITIVE`) および `S` (`SENSITIVE`) の2つのレベルを作成できます。 + +```sql +CREATE ABAC_LEVEL HS WITH LONG_NAME HIGHLY_SENSITIVE AND LEVEL_NUMBER 20 IN POLICY p; +CREATE ABAC_LEVEL S WITH LONG_NAME SENSITIVE AND LEVEL_NUMBER 10 IN POLICY p; +``` + +次のコマンドを実行して、作成されたレベルを確認できます。 + +```sql +SHOW ABAC_LEVELS IN POLICY p; +``` + +出力に作成されたレベル `HS` および `S` が表示されます。 + +### 9. ポリシーにコンパートメントを作成する + +次に、ポリシーにコンパートメントを作成します。 + +この例では、次のコマンドを実行して、`HR` および `LEG` の2つのコンパートメントを作成できます。 + +```sql +CREATE ABAC_COMPARTMENT HR WITH LONG_NAME HR IN POLICY p; +CREATE ABAC_COMPARTMENT LEG WITH LONG_NAME LEGAL IN POLICY p; +``` + +次のコマンドを実行して、作成されたコンパートメントを確認できます。 + +```sql +SHOW ABAC_COMPARTMENTS IN POLICY p; +``` + +出力に作成されたコンパートメント `HR` および `LEG` が表示されます。 + +### 10. テーブルポリシーを作成してポリシーをテーブルに適用する + +次に、ポリシー `p` をテーブル `n.t` に適用するテーブルポリシーを作成できます。 + +この例では、次のコマンドを実行して、`tp` という名前のテーブルポリシーを作成できます。 + +```sql +CREATE ABAC_TABLE_POLICY tp USING POLICY p AND TABLE n.t; +``` + +この時点で、データタグ列 `data_tag` がテーブル `n.t` に追加されます。次のコマンドを実行して確認できます。 + +```sql +DESC n.t; +``` + +次のコマンドを実行して、作成されたテーブルポリシーを確認できます。 + +```sql +SHOW ABAC_TABLE_POLICIES; +``` + +出力に作成されたテーブルポリシー `tp` が表示されます。 + +### 11. ユーザーにレベルとコンパートメントを割り当てる + +次に、ユーザーにレベルとコンパートメントを割り当てます。 + +`user1` には、次のコマンドを実行して、レベル `S` とコンパートメント `HR` を割り当てることができます。 + +```sql +SET ABAC_LEVEL S FOR USER user1 IN POLICY p; +ADD ABAC_COMPARTMENT HR TO USER user1 IN POLICY p; +``` + +`user2` には、次のコマンドを実行して、レベル `HS` とコンパートメント `HR` および `LEG` を割り当てることができます。 + +```sql +SET ABAC_LEVEL HS FOR USER user2 IN POLICY p; +ADD ABAC_COMPARTMENT HR TO USER user2 IN POLICY p; +ADD ABAC_COMPARTMENT LEG TO USER user2 IN POLICY p; +``` + +`user3` には、次のコマンドを実行して、レベル `HS` と読み取り/書き込みアクセス権を持つコンパートメント `LEG` を割り当てることができます。 + +```sql +SET ABAC_LEVEL HS FOR USER user3 IN POLICY p; +ADD ABAC_COMPARTMENT LEG TO USER user3 WITH READ_WRITE_ACCESS IN POLICY p; +``` + +次のコマンドを実行して、割り当てられたレベルとコンパートメントを確認できます。 + +```sql +SHOW ABAC_USER_TAG_INFO FOR USER user1 IN POLICY p; +SHOW ABAC_USER_TAG_INFO FOR USER user2 IN POLICY p; +SHOW ABAC_USER_TAG_INFO FOR USER user3 IN POLICY p; +``` + +出力に各ユーザーに割り当てられたレベルとコンパートメントが表示されます。 + +### 12. テーブルにデータを挿入する + +スーパーユーザーとして次のコマンドを実行して、テーブルにデータを挿入します。 + +```sql +INSERT INTO n.t (id, col, data_tag) values (1, 1, 'S:HR'), (2, 2, 'HS:HR,LEG'), (3, 3, 'HS:LEG'); +``` + +:::note + +このチュートリアルでは、初期データを挿入するためにスーパーユーザーを使用しました。ただし、実稼働環境では、適切な行タグをユーザーに割り当て、データを挿入させてください。 + +::: + +次に、以下のコマンドを実行してテーブルからデータを選択します。 + +```sql +SELECT id, col, data_tag FROM n.t; +``` + +出力にすべての挿入された行が表示されます。 + +### 13. `user1` としてデータを読み取る + +次に、`user1` としてデータを読み取ります。 + +SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +ユーザー名とパスワードとして、それぞれ `user1` と `user1` を入力します。 + +次に、以下のコマンドを実行してデータを読み取ります。 + +```sql +SELECT id, col, data_tag FROM n.t; +``` + +出力には `S:HR` のデータタグを持つ行のみが表示されます。これは、`user1` が `S` レベルを持っており、`HS` レベルのデータにはアクセスできないためです。 + +### 14. `user2` としてデータを読み取る + +次に、`user2` としてデータを読み取ります。 + +SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +ユーザー名とパスワードとして、それぞれ `user2` と `user2` を入力します。 + +次に、以下のコマンドを実行してデータを読み取ります。 + +```sql +SELECT id, col, data_tag FROM n.t; +``` + +出力にはすべての挿入された行が表示されます。これは、`user2` が `HS` レベルと `HR` および `LEG` コンパートメントを持っており、すべてのデータにアクセスできるためです。 + +### 15. `user3` としてデータを読み取る + +次に、`user3` としてデータを読み取ります。 + +SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +ユーザー名とパスワードとして、それぞれ `user3` と `user3` を入力します。 + +次に、以下のコマンドを実行してデータを読み取ります。 + +```sql +SELECT id, col, data_tag FROM n.t; +``` + +出力には `HS:LEG` のデータタグを持つ行のみが表示されます。これは、`user3` が `HS` レベルと `LEG` コンパートメントを持っており、`HR` コンパートメントのデータにはアクセスできないためです。 + +### 16. `user2` としてデータを書き込む + +次に、`user2` としてデータを書き込みます。 + +SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +ユーザー名とパスワードとして、それぞれ `user2` と `user2` を入力します。 + +次に、以下のコマンドを実行してデータを書き込みます。 + +```sql +UPDATE n.t SET col = 10 WHERE id = 3; +``` + +ただし、`user2` には `LEG` コンパートメントへの書き込みアクセス権がないため、エラーメッセージが表示されます。 + +### 17. `user3` としてデータを書き込む + +次に、`user3` としてデータを書き込みます。 + +SQL CLI を終了します。次に、以下のコマンドを実行して SQL CLI を再起動します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +ユーザー名とパスワードとして、それぞれ `user3` と `user3` を入力します。 + +次に、以下のコマンドを実行してデータを書き込みます。 + +```sql +UPDATE n.t SET col = 10 WHERE id = 3; +``` + +`user3` には `LEG` コンパートメントへの書き込みアクセス権があるため、コマンドは正常に実行されます。 + +次に、以下のコマンドを実行してデータを読み取ります。 + +```sql +SELECT id, col, data_tag FROM n.t; +``` + +出力に更新された行が表示されます。 + +## 追加の詳細 + +ABAC 機能は現在、プライベートプレビュー中です。詳細については、[お問い合わせ](https://www.scalar-labs.com/contact)いただくか、この機能が将来のバージョンで一般公開されるまでお待ちください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/compatibility.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/compatibility.mdx new file mode 100644 index 00000000..589d2714 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/compatibility.mdx @@ -0,0 +1,52 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster 互換性マトリックス + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、クライアント SDK バージョン間の ScalarDB Cluster バージョンの互換性を示します。 + +## ScalarDB Cluster とクライアント SDK の互換性 + +| ScalarDB Cluster バージョン | ScalarDB Cluster Java Client SDK バージョン | ScalarDB Cluster .NET Client SDK バージョン | +|:--------------------------|:------------------------------------------|:------------------------------------------| +| 3.15 | 3.9 - 3.15 | 3.12* - 3.15 | +| 3.14 | 3.9 - 3.14 | 3.12* - 3.14 | +| 3.13 | 3.9 - 3.13 | 3.12* - 3.13 | +| 3.12 | 3.9 - 3.12 | 3.12* | +| 3.11 | 3.9 - 3.11 | サポート対象外 | +| 3.10 | 3.9 - 3.10 | サポート対象外 | +| 3.9 | 3.9 | サポート対象外 | + +\* このバージョンはプライベートプレビュー段階であるため、将来のバージョンでは下位互換性のない更新が行われる可能性があります。 + +:::note + +- クライアントツール (例えば、[ScalarDB Cluster SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli) や [ScalarDB Cluster Schema Loader](developer-guide-for-scalardb-cluster-with-java-api.mdx#クラスター用-schema-loader)) は、ScalarDB Cluster Java Client SDK と同じものと見なすことができます。つまり、ScalarDB Cluster Java Client SDK と同じ互換性ルールをクライアントツールに適用できます。 +- ScalarDB Data Loader を使用してバックエンドデータベースにアクセスする場合は、使用している ScalarDB Cluster のバージョンと互換性のあるバージョンの ScalarDB Data Loader を使用する必要があります。この場合、サポートされている ScalarDB Data Loader のバージョンは、上記の表に示されている ScalarDB Cluster Java Client SDK のバージョンと同じです。ScalarDB Data Loader は ScalarDB Cluster に直接アクセスしないことに注意してください。 +- ScalarDB Cluster が新しいマイナーバージョンで提供する新機能を使用する場合は、同じバージョンまたはそれ以降のバージョンのクライアントツールの利用、もしくは既存のスキーマの再作成 (または更新) が必要となる場合があります。詳細については、各機能の関連ドキュメントを参照してください。 + +::: + +## バージョンスキューポリシー + +:::note + +バージョンは `x.y.z` として表されます。`x` はメジャーバージョン、`y` はマイナーバージョン、`z` はパッチバージョンを表します。この形式は [セマンティックバージョニング](https://semver.org/) に従います。 + +::: + +- ScalarDB Cluster とクライアント SDK の **メジャー** バージョンが異なる場合、それらは **互換性がない** ため、**サポートされていません**。 +- ScalarDB Cluster とクライアント SDK の **メジャー** バージョンが同じで、**マイナー** バージョンが異なる場合、ScalarDB Cluster のバージョンはクライアント SDK バージョン以上である必要があります。例: + - **サポート対象:** ScalarDB Cluster 3.13とクライアント SDK 3.11の組み合わせ + - **サポート対象外:** ScalarDB Cluster 3.11とクライアント SDK 3.13の組み合わせ +- **メジャー** バージョンと **マイナー** バージョンが同じ場合、ScalarDB Cluster とクライアント SDK 間で異なる **パッチ** バージョンを使用できます。例: + - **サポート対象:** ScalarDB Cluster 3.13.2とクライアント SDK 3.13.0の組み合わせ + - **サポート対象:** ScalarDB Cluster 3.13.0とクライアント SDK 3.13.2の組み合わせ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/deployment-patterns-for-microservices.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/deployment-patterns-for-microservices.mdx new file mode 100644 index 00000000..98ca1ec8 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/deployment-patterns-for-microservices.mdx @@ -0,0 +1,76 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# マイクロサービスにおける ScalarDB Cluster のデプロイパターン + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster を使用するマイクロサービスアプリケーションを構築する場合、ScalarDB Cluster のデプロイ方法として、共有クラスターパターンと分離クラスターパターンの2つのパターンを選択できます。 +このドキュメントでは、まずこれらのパターンについて説明し、それらの違いと、どの場合にどちらを選択するかの基本的なガイドラインを示します。 + +また、このドキュメントでは、マイクロサービスアプリケーションが database-per-service パターンに基づいて作成されているものと想定しています。このパターンでは、各マイクロサービスがデータベースを管理し、マイクロサービスはマイクロサービス間の API を介して別のマイクロサービスのデータベースにアクセスする必要があります。 + +## ScalarDB Cluster のデプロイパターン + +共有クラスターパターンでは、マイクロサービスはシステム内で1つの ScalarDB Cluster インスタンス (ScalarDB Cluster ノードのクラスタ) を共有するため、同じ ScalarDB Cluster インスタンスにアクセスしてデータベースとやり取りします。一方、分離クラスターパターンでは、マイクロサービスは複数の ScalarDB Cluster インスタンスを使用します。通常、1つのマイクロサービスが1つの ScalarDB Cluster インスタンスにアクセスして、データベースとやり取りします。 + +次の図は2つのパターンを示しています。(MS はマイクロサービスの略です。) + +![マイクロサービスにおける ScalarDB Cluster のデプロイパターン。](images/scalardb-deployment-patterns.png) + +:::note + +どちらのパターンでも、マイクロサービスに必要なデータベースに加えて、Coordinator テーブルも管理する必要があります。 + +::: + +## 長所と短所 + +明らかな違いの1つは、ScalarDB Cluster インスタンスのリソースの量です。分離クラスターパターンでは、アプリケーションを管理するためのリソースが増えます。これにより、メンテナンスの負担とコストも増加します。 + +さらに、使用する ScalarDB Cluster API も異なります。具体的には、共有クラスターパターンの場合、[1フェーズコミットインターフェース](../api-guide.mdx#transactional-api)を使用する必要があります。このインターフェースでは、マイクロサービスがレコードを読み書きした後、1つのマイクロサービスのみが `commit` を呼び出してトランザクションをコミットします。分離クラスターパターンの場合、[2フェーズコミットインターフェース](../two-phase-commit-transactions.mdx)を使用する必要があります。このインターフェースでは、すべてのマイクロサービスが最初に `prepare` を呼び出し、すべての`prepare` 呼び出しが成功した場合に `commit` を呼び出します。したがって、分離クラスターパターンのマイクロサービスは、トランザクションとそのエラーをよりきめ細かい方法で処理する必要があるため、共有クラスターパターンのマイクロサービスよりも複雑になる可能性があります。 + +さらに、リソースの分離レベルも異なります。マイクロサービスは、保守性と開発効率を高めるために十分に分離されている必要がありますが、共有クラスターパターンではリソースの分離が弱くなります。リソースの分離が弱いと、セキュリティも弱くなる可能性があります。ただし、認証や承認などの ScalarDB Cluster のセキュリティ機能を使用することで、セキュリティリスクを軽減できます。 + +同様に、システムの管理方法にも違いがあります。具体的には、共有クラスターパターンでは、他のチームに代わって ScalarDB Cluster インスタンスを管理するタスクをチームに割り当てる必要があります。通常は中央データチームが管理しますが、そのようなチームが存在しない場合は問題が発生する可能性があります。分離クラスターパターンでは、管理のバランスがより取れていますが、Coordinator テーブルに関して同様の問題が発生します。この問題は、調整用のマイクロサービスを用意し、1つのチームにそのマイクロサービスを管理させることで対処できます。 + +次に、パターンの長所と短所をまとめます。 + +### 共有クラスターパターン + +- **長所:** + - 1フェーズコミットインターフェースのため、トランザクションとエラーの処理が簡単です。(データベースのバックアップ操作も簡単です。) + - 1つの ScalarDB Cluster インスタンスを使用するため、リソース使用量が少なくなります。 +- **短所:** + - マイクロサービス間のリソース分離が弱い。 + - 管理のバランスが取れていない。(1つのチームが他のチームに代わって ScalarDB Cluster インスタンスを管理する必要があります。) + +### 分離クラスターパターン + +- **利点:** + - リソースの分離が向上します。 + - 管理のバランスがより取れます。(1つのチームが1つのマイクロサービスと1つの ScalarDB Cluster インスタンスを管理します。また、1つのチームに Coordinator ターテーブルの管理を任せる必要があります。) +- **欠点:** + - 2フェーズコミットインターフェースによるトランザクションとエラー処理が複雑です。(データベースのバックアップ操作も複雑になることがあります。) + - 複数の ScalarDB Cluster インスタンスがあるため、リソース使用量が増加します。 + + +## どのパターンを選択するか + +可能な限り、共有クラスターパターンを使用することをお勧めします。共有クラスターパターンには前述のようにいくつかの欠点がありますが、そのシンプルさと管理のしやすさはそれらの欠点を上回ります。さらに、ScalarDB Cluster はすべての重要な状態を基盤となるデータベースに保存し、メモリには重要な状態を保持しないため、データベースへの単なるパスとして見ることができます。したがって、共有クラスターパターンのシステムは依然としてサービスごとのデータベースパターンに準拠しており、マイクロサービスの理念にあまり違反していないと考えています。 + +共有クラスターパターンの欠点が受け入れられない場合は、分離クラスターパターンを使用できます。ただし、2フェーズコミットインターフェースのメカニズムと使用方法を適切に理解している場合にのみ、このパターンを使用してください。そうでない場合、データベースの異常などの問題が発生する可能性があります。 + +## 制限事項 + +ScalarDB は、CRUD、SQL、Spring Data JDBC などのいくつかの API を提供します。 CRUD および SQL インターフェースは共有クラスターパターンと分離クラスターパターンの両方をサポートしていますが、Spring Data JDBC インターフェースは共有クラスターパターンをサポートしていません。これは、Spring Data JDBC の1フェーズコミットインターフェースが現在、アプリケーションがモノリシックであり、相互にやり取りするマイクロサービスに分割されていないことを前提としているためです。Spring Data JDBC インターフェースは、他の API と同様に、2フェーズコミットインターフェースと分離クラスターパターンをサポートしています。 + +## 参照 + +- [2フェーズコミットインターフェースを使用したトランザクション](../two-phase-commit-transactions.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx new file mode 100644 index 00000000..d4bc52a9 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx @@ -0,0 +1,303 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Java API を使用した ScalarDB Cluster の開発者ガイド + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster は、アプリケーションを開発するための Java API を提供します。このドキュメントでは、Java API の使用方法を説明します。 + +## ビルドに ScalarDB Cluster Java Client SDK を追加する + +ScalarDB Cluster Java Client SDK は、[Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-cluster-java-client-sdk) で入手できます。 + +Gradle を使用して ScalarDB Cluster Java Client SDK への依存関係を追加するには、以下を使用します。 + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' +} +``` + +Maven を使用して依存関係を追加するには、以下を使用します。 + +```xml + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + +``` + +## クライアントモード + +ScalarDB Cluster Java Client SDK は、`indirect` と `direct-kubernetes` の2つのクライアントモードをサポートしています。以下では、クライアントモードについて説明します。 + +### `indirect` クライアントモード + +このモードでは、単にリクエストを任意のクラスターノードに送信します (通常は Envoy などのロードバランサー経由)。リクエストを受信したクラスターノードは、トランザクション状態を持つ適切なクラスターノードにリクエストをルーティングします。 + +![ScalarDB Cluster アーキテクチャ](images/indirect-client-mode.png) + +このモードの利点は、クライアントを軽量に保てることです。 +欠点は、正しいクラスターノードに到達するために追加のホップが必要になり、パフォーマンスに影響する可能性があることです。 + +アプリケーションが別の Kubernetes クラスターで実行されていて、アプリケーションが Kubernetes API と各クラスターノードにアクセスできない場合でも、この接続モードを使用できます。 +アプリケーションが ScalarDB Cluster ノードと同じ Kubernetes クラスターで実行されている場合は、`direct-kubernetes` クライアントモードを使用できます。 + +### `direct-kubernetes` クライアントモード + +このモードでは、クライアントはメンバーシップロジック (Kubernetes API を使用) と分散ロジック (コンシステントハッシュアルゴリズム) を使用して、トランザクション状態を持つ適切なクラスターノードを見つけます。次に、クライアントはクラスターノードに直接リクエストを送信します。 + +![ScalarDB Cluster アーキテクチャ](images/direct-kubernetes-client-mode.png) + +このモードの利点は、適切なクラスターノードに到達するためのホップ数を減らすことができるため、パフォーマンスが向上することです。このモードの欠点は、クライアントにメンバーシップロジックとリクエストルーティングロジックが必要なため、クライアントをファットにする必要があることです。 + +この接続モードは Kubernetes API と各クラスターノードにアクセスする必要があるため、アプリケーションが ScalarDB Cluster ノードと同じ Kubernetes クラスターで実行されている場合にのみ、この接続モードを使用できます。アプリケーションが別の Kubernetes クラスターで実行されている場合は、`indirect` クライアントモードを使用します。 + +`direct-kubernetes` クライアントモードで Kubernetes にアプリケーションをデプロイする方法の詳細については、[`direct-kubernetes` モードを使用してクライアントアプリケーションを Kubernetes にデプロイする](../helm-charts/how-to-deploy-scalardb-cluster.mdx#direct-kubernetes-モードを使用してクライアント-アプリケーションを-kubernetes-にデプロイします) を参照してください。 + +## ScalarDB Cluster Java API + +ScalarDB Cluster Java Client SDK は、アプリケーションが ScalarDB Cluster にアクセスするための Java API を提供します。次の図は、ScalarDB Cluster Java API のアーキテクチャを示しています。 + +``` + +-----------------------+ + | ユーザー/アプリケーション | + +-----------------------+ + ↓ Java API + +--------------+ + | ScalarDB API | + +--------------+ + ↓ gRPC + +------------------+ + | ScalarDB Cluster | + +------------------+ + ↓ DB ベンダー固有のプロトコル + +----+ + | DB | + +----+ +``` + +ScalarDB Cluster Java API の使用は、クライアント設定と Schema Loader が異なることを除いて、ScalarDB Java API の使用とほぼ同じです。詳細については、[ScalarDB Java API ガイド](../api-guide.mdx) を参照してください。 + +次のセクションでは、ScalarDB Cluster Java API とクラスター用 Schema Loader のクライアント設定について説明します。 + +### クライアント設定 + +次の表は、ScalarDB Cluster Java API のクライアント設定を示しています。 + +| 名前 | 説明 | デフォルト | +|----------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------| +| `scalar.db.transaction_manager` | `cluster` を指定する必要があります。 | - | +| `scalar.db.contact_points` | クラスターの連絡先。`indirect` クライアントモードを使用する場合は、`indirect:` の形式を使用して、クラスターノードの前にあるロードバランサーの IP アドレスを指定します。`direct-kubernetes` クライアントモードを使用する場合は、`direct-kubernetes:/` または単に `direct-kubernetes:` の形式を使用して、名前空間名 (オプション) と [エンドポイントリソース](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) の名前を指定して、メンバーシップ情報を取得します。名前空間名を指定しない場合、クライアントは `default` 名前空間を使用します。 | | +| `scalar.db.contact_port` | 連絡先のポート番号。 | `60053` | +| `scalar.db.cluster.grpc.deadline_duration_millis` | gRPC の期限期間(ミリ秒単位)。 | `60000` (60秒) | +| `scalar.db.cluster.grpc.max_inbound_message_size` | 単一の gRPC フレームに許可される最大メッセージサイズ。 | gRPCのデフォルト値 | +| `scalar.db.cluster.grpc.max_inbound_metadata_size` | 受信できるメタデータの最大サイズ。 | gRPCのデフォルト値 | + +たとえば、`indirect` クライアントモードを使用し、ロードバランサーの IP アドレスが `192.168.10.1` の場合、クライアントを次のように設定できます。 + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:192.168.10.1 +``` + +または、エンドポイントの名前空間を `ns`、エンドポイント名を `scalardb-cluster` として `direct-kubernetes` クライアントモードを使用する場合は、次のようにクライアントを設定できます。 + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=direct-kubernetes:ns/scalardb-cluster +``` + +### クラスター用 Schema Loader + +ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (クラスター用 Schema Loader) を使用する必要があります。クラスター用Schema Loader の使用方法は、JAR ファイルの名前が異なることを除いて、[ScalarDB Schema Loader](../schema-loader.mdx) の使用方法と基本的に同じです。クラスター用 Schema Loader は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドでクラスター用 Schema Loader を実行できます。 + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config -f --coordinator +``` + +## ScalarDB Cluster SQL + +ScalarDB Cluster SQL には、次のように Java の ScalarDB 用 JDBC および Spring Data JDBC を介してアクセスできます。 + +``` + +----------------------------------------------+ + | ユーザー/アプリケーション | + +----------------------------------------------+ + ↓ ↓ Java API +Java API ↓ +-------------------------------+ + (JDBC) ↓ | Spring Data JDBC for ScalarDB | + ↓ +-------------------------------+ ++----------------------------------------------+ +| ScalarDB JDBC (ScalarDB SQL) | ++----------------------------------------------+ + ↓ gRPC + +----------------------+ + | ScalarDB Cluster SQL | + +----------------------+ + ↓ DB ベンダー固有のプロトコル + +----+ + | DB | + +----+ +``` + +このセクションでは、JDBC 経由で ScalarDB Cluster SQL を使用する方法と、Spring Data JDBC for ScalarDB を使用する方法について説明します。 + +### JDBC 経由の ScalarDB Cluster SQL + +JDBC 経由での ScalarDB Cluster SQL の使用は、プロジェクトに JDBC ドライバーを追加する方法を除いて、[ScalarDB JDBC](../scalardb-sql/jdbc-guide.mdx) を使用する場合とほぼ同じです。 + +[ビルドに ScalarDB Cluster Java Client SDK を追加する](#add-scalardb-cluster-java-client-sdk-to-your-build) で説明されているように ScalarDB Cluster Java Client SDK を追加することに加えて、プロジェクトに次の依存関係を追加する必要があります。 + +Gradle を使用して ScalarDB Cluster JDBC ドライバーへの依存関係を追加するには、以下を使用します。 + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql-jdbc:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' +} +``` + +Maven を使用して依存関係を追加するには、以下を使用します。 + +```xml + + + com.scalar-labs + scalardb-sql-jdbc + 3.15.4 + + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + +``` + +それ以外は、JDBC 経由で ScalarDB Cluster SQL を使用することは、ScalarDB JDBC を使用することと同じです。ScalarDB JDBC の詳細については、[ScalarDB JDBC ガイド](../scalardb-sql/jdbc-guide.mdx) を参照してください。 + +### Spring Data JDBC for ScalarDB 経由の ScalarDB Cluster SQL + +JDBC 経由の ScalarDB Cluster SQL と同様に、Spring Data JDBC for ScalarDB 経由の ScalarDB Cluster SQL を使用することは、プロジェクトへの追加方法を除いて、[Spring Data JDBC for ScalarDB](../scalardb-sql/spring-data-guide.mdx) を使用することとほぼ同じです。 + +[ScalarDB Cluster Java Client SDK をビルドに追加する](#add-scalardb-cluster-java-client-sdk-to-your-build) で説明されているように ScalarDB Cluster Java Client SDK を追加することに加えて、プロジェクトに次の依存関係を追加する必要があります: + +Gradle を使用して依存関係を追加するには、以下を使用します: + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql-spring-data:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' +} +``` + +Maven を使用して依存関係を追加するには、以下を使用します。 + +```xml + + + com.scalar-labs + scalardb-sql-spring-data + 3.15.4 + + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + +``` + +それ以外では、Spring Data JDBC for ScalarDB 経由で ScalarDB Cluster SQL を使用することは、Spring Data JDBC for ScalarDB を使用することと同じです。Spring Data JDBC for ScalarDB の詳細については、[Spring Data JDBC for ScalarDB ガイド](../scalardb-sql/spring-data-guide.mdx) を参照してください。 + +### ScalarDB Cluster SQL クライアント設定 + +次の表は、ScalarDB Cluster SQL の設定を示しています。 + +| 名前 | 説明 | デフォルト | +|----------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------| +| `scalar.db.sql.connection_mode` | `cluster` を指定する必要があります。 | - | +| `scalar.db.sql.cluster_mode.contact_points` | クラスターの連絡先。`indirect` クライアントモードを使用する場合は、`indirect:` の形式を使用して、クラスターノードの前にあるロードバランサーの IP アドレスを指定します。`direct-kubernetes` クライアントモードを使用する場合は、`direct-kubernetes:/` または単に `direct-kubernetes:` の形式を使用して、名前空間名 (オプション) と [エンドポイントリソース](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) の名前を指定して、メンバーシップ情報を取得します。名前空間名を指定しない場合、クライアントは `default` 名前空間を使用します。 | | +| `scalar.db.sql.cluster_mode.contact_port` | 連絡先のポート番号。 | `60053` | +| `scalar.db.sql.default_transaction_mode` | デフォルトのトランザクションモード。`TRANSACTION` または `TWO_PHASE_COMMIT_TRANSACTION` を設定できます。 | `TRANSACTION` | +| `scalar.db.sql.default_namespace_name` | デフォルトの名前空間名。SQL ステートメントで名前空間名を指定しない場合は、この値が使用されます。 | | +| `scalar.db.cluster.grpc.deadline_duration_millis` | gRPC の期限期間(ミリ秒単位)。 | `60000` (60秒) | +| `scalar.db.cluster.grpc.max_inbound_message_size` | 単一の gRPC フレームに許可される最大メッセージサイズ。 | gRPCのデフォルト値 | +| `scalar.db.cluster.grpc.max_inbound_metadata_size` | 受信できるメタデータの最大サイズ。 | gRPCのデフォルト値 | + +たとえば、`indirect` クライアントモードを使用し、ロードバランサーの IP アドレスが `192.168.10.1` の場合、クライアントを次のように設定できます。 + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:192.168.10.1 +``` + +または、エンドポイントの名前空間を `ns`、エンドポイント名を `scalardb-cluster` として `direct-kubernetes` クライアントモードを使用する場合は、次のようにクライアントを設定できます。 + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=direct-kubernetes:ns/scalardb-cluster +``` + +ScalarDB JDBC の設定方法の詳細については、[JDBC 接続 URL](../scalardb-sql/jdbc-guide.mdx#jdbc-接続-url) を参照してください。 + +Spring Data JDBC for ScalarDB の設定方法の詳細については、[設定](../scalardb-sql/spring-data-guide.mdx#設定) を参照してください。 + +### SQL CLI + +他の SQL データベースと同様に、ScalarDB SQL にも、コマンドラインシェルで対話的に SQL ステートメントを発行できる CLI ツールが用意されています。 + +Cluster 用の SQL CLI は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで SQL CLI を実行できます。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config +``` + +#### 使用方法 + +CLI の使用方法は、次のように `-h` オプションを使用して確認できます。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar -h +Usage: scalardb-sql-cli [-hs] -c=PROPERTIES_FILE [-e=COMMAND] [-f=FILE] + [-l=LOG_FILE] [-o=] [-p=PASSWORD] + [-u=USERNAME] +Starts ScalarDB SQL CLI. + -c, --config=PROPERTIES_FILE + A configuration file in properties format. + -e, --execute=COMMAND A command to execute. + -f, --file=FILE A script file to execute. + -h, --help Display this help message. + -l, --log=LOG_FILE A file to write output. + -o, --output-format= + Format mode for result display. You can specify + table/vertical/csv/tsv/xmlattrs/xmlelements/json/a + nsiconsole. + -p, --password=PASSWORD A password to connect. + -s, --silent Reduce the amount of informational messages + displayed. + -u, --username=USERNAME A username to connect. +``` + +## 参考資料 + +Java 以外のプログラミング言語で ScalarDB Cluster を使用する場合は、ScalarDB Cluster gRPC API を使用できます。 +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +* [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +* [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) + +Javadocs も利用可能です: + +* [ScalarDB Cluster Java Client SDK](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-java-client-sdk/3.15.4/index.html) +* [ScalarDB Cluster Common](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-common/3.15.4/index.html) +* [ScalarDB Cluster RPC](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-rpc/3.15.4/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/encrypt-data-at-rest.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/encrypt-data-at-rest.mdx new file mode 100644 index 00000000..fc93bd83 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/encrypt-data-at-rest.mdx @@ -0,0 +1,328 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 保存データの暗号化 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; + + + +このドキュメントでは、ScalarDB に保存されているデータを暗号化する方法について説明します。 + +## 概要 + +ScalarDB は、それを介して保存されたデータを暗号化できます。暗号化機能は、主要なデータベースシステムの透過的データ暗号化 (TDE) に似ているため、アプリケーションに対して透過的です。ScalarDB は、バックエンドデータベースに書き込む前にデータを暗号化し、そこから読み取るときに復号します。 + +現在、ScalarDB は列レベルの暗号化をサポートしており、テーブル内の特定の列を暗号化できます。 + +## 設定 + +暗号化機能を有効にするには、ScalarDB Cluster ノード設定ファイルで `scalar.db.cluster.encryption.enabled` を `true` に設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|----------------------------------------|-----------------------------------------|---------| +| `scalar.db.cluster.encryption.enabled` | ScalarDB が保存データを暗号化するかどうか。 | `false` | + +:::note + +暗号化はクライアントに対して透過的であるため、クライアントの設定を変更する必要はありません。 + +::: + +:::note + +暗号化機能を有効にする場合は、内部的にパーティション間スキャンを実行するため、システム名前空間 (デフォルトでは `scalardb`) の `scalar.db.cross_partition_scan.enabled` を `true` に設定する必要もあります。 + +::: + +その他の設定は、選択した暗号化実装によって異なります。現在、ScalarDB は次の暗号化実装をサポートしています。 + +- HashiCorp Vault 暗号化 +- 自己暗号化 + +次のセクションでは、各暗号化実装の設定方法について説明します。 + +### HashiCorp Vault 暗号化 + +HashiCorp Vault 暗号化では、ScalarDB は HashiCorp Vault の [encryption as a service](https://developer.hashicorp.com/vault/tutorials/encryption-as-a-service/eaas-transit) を使用してデータを暗号化および復号します。この実装では、ScalarDB は暗号化キーの管理とデータの暗号化および復号を HashiCorp Vault に委任します。 + +HashiCorp Vault 暗号化を使用するには、ScalarDB Cluster ノード設定ファイルでプロパティ `scalar.db.cluster.encryption.type` を `vault` に設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|-------------------------------------|-------------------------------------------------------------|---------| +| `scalar.db.cluster.encryption.type` | HashiCorp Vault 暗号化を使用するには、`vault` に設定する必要があります。 | | + +次のプロパティも設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------| +| `scalar.db.cluster.encryption.vault.key_type` | キーの種類。現在、`aes128-gcm96`、`aes256-gcm96`、`chacha20-poly1305` がサポートされています。キーの種類の詳細については、[Key types](https://developer.hashicorp.com/vault/docs/secrets/transit#key-types) を参照してください。 | `aes128-gcm96` | +| `scalar.db.cluster.encryption.vault.associated_data_required` | AEAD 暗号化に関連データが必要かどうか。 | `false` | +| `scalar.db.cluster.encryption.vault.address` | HashiCorp Vault サーバーのアドレス。 | | +| `scalar.db.cluster.encryption.vault.token` | HashiCorp Vault で認証するためのトークン。 | | +| `scalar.db.cluster.encryption.vault.namespace` | HashiCorp Vault の名前空間。この設定はオプションです。 | | +| `scalar.db.cluster.encryption.vault.transit_secrets_engine_path` | トランジットシークレットエンジンのパス。 | `transit` | +| `scalar.db.cluster.encryption.vault.column_batch_size` | HashiCorp Vault サーバーへの単一のリクエストに含まれる列の数。 | `64` | + +### 自己暗号化 + +自己暗号化では、ScalarDB がデータ暗号化キー (DEK) を管理し、暗号化と復号を実行します。ScalarDB はテーブルの作成時にテーブルごとに DEK を生成し、Kubernetes Secrets に保存します。 + +自己暗号化を使用するには、ScalarDB Cluster ノード設定ファイルでプロパティ `scalar.db.cluster.encryption.type` を `self` に設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|-------------------------------------|-------------------------------------------------|---------| +| `scalar.db.cluster.encryption.type` | 自己暗号化を使用するには `self` に設定する必要があります。 | | + +次のプロパティも設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|-------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| +| `scalar.db.cluster.encryption.self.key_type` | キーの種類。現在、`AES128_GCM`、`AES256_GCM`、`AES128_EAX`、`AES256_EAX`、`AES128_CTR_HMAC_SHA256`、`AES256_CTR_HMAC_SHA256`、`CHACHA20_POLY1305`、および `XCHACHA20_POLY1305` がサポートされています。キーの種類の詳細については、[キータイプの選択](https://developers.google.com/tink/aead?hl=ja#choose_a_key_type)を参照してください。 | `AES128_GCM` | +| `scalar.db.cluster.encryption.self.associated_data_required` | AEAD 暗号化に関連データが必要かどうか。 | `false` | +| `scalar.db.cluster.encryption.self.kubernetes.secret.namespace_name` | Kubernetes Secrets の名前空間名。 | `default` | +| `scalar.db.cluster.encryption.self.data_encryption_key_cache_expiration_time` | DEK キャッシュの有効期限(ミリ秒単位)。 | `60000` (60秒) | + +### テーブルを削除するときに DEK を削除する + +デフォルトでは、ScalarDB はテーブルを削除しても、テーブルに関連付けられたデータ暗号化キー (DEK) を削除しません。ただし、テーブルを削除するときに DEK を削除するように ScalarDB を設定できます。これを有効にするには、ScalarDB Cluster ノード設定ファイルでプロパティ `scalar.db.cluster.encryption.delete_data_encryption_key_on_drop_table.enabled` を `true` に設定します。 + +| 名前 | 説明 | デフォルト | +|---------------------------------------------------------------------------------|-------------------------------------------|----------| +| `scalar.db.cluster.encryption.delete_data_encryption_key_on_drop_table.enabled` | テーブルを削除するときに DEK を削除するかどうか。 | `false` | + +## 制限事項 + +暗号化機能にはいくつかの制限事項があります: + +- 主キー列 (パーティションキー列とクラスタリングキー列) は暗号化できません。 +- セカンダリインデックス列は暗号化できません。 +- 暗号化された列は WHERE 句または ORDER BY 句で指定できません。 +- 暗号化された列は、基になるデータベースに BLOB 型として保存されるため、BLOB 型の最大サイズより大きい暗号化された列は保存できません。BLOB 型の最大サイズについては、[ScalarDB と他のデータベース間のデータ型マッピング](../schema-loader.mdx#scalardb-と他のデータベース間のデータ型マッピング)を参照してください。 + +## ワイヤ暗号化 + +暗号化機能を有効にする場合は、データを保護するために本番環境でワイヤ暗号化を有効にすることを強くお勧めします。ワイヤ暗号化の詳細については、[ScalarDB Cluster ワイヤ暗号化](encrypt-wire-communications.mdx)を参照してください。 + +## チュートリアル - HashiCorp Vault 暗号化を設定してデータを暗号化する + +このチュートリアルでは、HashiCorp Vault 暗号化を使用して ScalarDB で保存されたデータを暗号化する方法について説明します。 + +## 前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10以降と [Docker Compose](https://docs.docker.com/compose/install/) V2以降 + +:::note + +このチュートリアルは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../requirements.mdx)を参照してください。 + +::: + + + +### ステップ 1. HashiCorp Vault をインストールします + +HashiCorp の公式ドキュメント [Install Vault](https://developer.hashicorp.com/vault/tutorials/getting-started/getting-started-install) を参照して、HashiCorp Vault をインストールします。 + +### ステップ 2. ScalarDB Cluster 設定ファイルを作成します + +次の設定ファイルを `scalardb-cluster-node.properties` として作成し、`` と `` を ScalarDB ライセンスキーとライセンスチェック証明書の値に置き換えます。ライセンスキーと証明書の詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + +```properties +scalar.db.storage=jdbc +scalar.db.contact_points=jdbc:postgresql://postgresql:5432/postgres +scalar.db.username=postgres +scalar.db.password=postgres +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.cross_partition_scan.enabled=true +scalar.db.sql.enabled=true + +# Encryption configurations +scalar.db.cluster.encryption.enabled=true +scalar.db.cluster.encryption.type=vault +scalar.db.cluster.encryption.vault.address=http://vault:8200 +scalar.db.cluster.encryption.vault.token=root + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +### ステップ 3. Docker Compose 設定ファイルを作成する + +次の設定ファイルを `docker-compose.yaml` として作成します。 + +```yaml +services: + vault: + container_name: "vault" + image: "hashicorp/vault:1.17.3" + ports: + - 8200:8200 + environment: + - VAULT_DEV_ROOT_TOKEN_ID=root + - VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200 + cap_add: + - IPC_LOCK + + postgresql: + container_name: "postgresql" + image: "postgres:15" + ports: + - 5432:5432 + environment: + - POSTGRES_PASSWORD=postgres + healthcheck: + test: ["CMD-SHELL", "pg_isready || exit 1"] + interval: 1s + timeout: 10s + retries: 60 + start_period: 30s + + scalardb-cluster-standalone: + container_name: "scalardb-cluster-node" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + ports: + - 60053:60053 + - 9080:9080 + volumes: + - ./scalardb-cluster-node.properties:/scalardb-cluster/node/scalardb-cluster-node.properties + depends_on: + postgresql: + condition: service_healthy +``` + +### ステップ 4. HashiCorp Vault サーバーを起動します + +次のコマンドを実行して、HashiCorp Vault サーバーを開発モードで起動します。 + +```console +docker compose up vault -d +``` + +HashiCorp Vault サーバーが実行したら、次のコマンドを実行して環境変数を設定します。 + +```console +export VAULT_ADDR="http://127.0.0.1:8200" +export VAULT_TOKEN=root +``` + +### ステップ 5. HashiCorp Vault サーバーでトランジットシークレットエンジンを有効にする + +次のコマンドを実行して、HashiCorp Vault サーバーでトランジットシークレットエンジンを有効にします。 + +```console +vault secrets enable transit +``` + +### ステップ 6. PostgreSQL と ScalarDB Cluster を起動する + +次のコマンドを実行して、PostgreSQL と ScalarDB Cluster をスタンドアロンモードで起動します。 + +```console +docker compose up postgresql scalardb-cluster-standalone -d +``` + +ScalarDB Cluster が完全に起動するまでに数分かかる場合があります。 + +### ステップ 7. ScalarDB Cluster に接続する + +ScalarDB Cluster に接続するために、このチュートリアルでは、ScalarDB Cluster に接続して SQL クエリを実行するツールである SQL CLI を使用します。SQL CLI は、[ScalarDB Releases ページ](https://github.com/scalar-labs/scalardb/releases)からダウンロードできます。 + +`scalardb-cluster-sql-cli.properties` という名前の設定ファイルを作成します。このファイルは、SQL CLI を使用して ScalarDB Cluster に接続するために使用されます。 + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost +``` + +次に、次のコマンドを実行して SQL CLI を起動します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +まず、ScalarDB トランザクション実行に必要な Coordinator テーブルを作成します。 + +```sql +CREATE COORDINATOR TABLES IF NOT EXISTS; +``` + +これで、ScalarDB Cluster で暗号化機能を有効にしたデータベースを使用する準備が整いました。 + +### ステップ 8. テーブルを作成する + +テーブルを作成する前に、名前空間を作成する必要があります。 + +```sql +CREATE NAMESPACE ns; +``` + +次に、テーブルを作成します。 + +```sql +CREATE TABLE ns.tbl ( + id INT PRIMARY KEY, + col1 TEXT ENCRYPTED, + col2 INT ENCRYPTED, + col3 INT); +``` + +`ENCRYPTED` キーワードを使用すると、指定された列のデータが暗号化されます。この例では、`col1` と `col2` のデータが暗号化されます。 + +### ステップ 9. テーブルにデータを挿入する + +テーブルにデータを挿入するには、次の SQL クエリを実行します。 + +```sql +INSERT INTO ns.tbl (id, col1, col2, col3) VALUES (1, 'data1', 123, 456); +``` + +挿入されたデータを確認するには、次の SQL クエリを実行します。 + +```sql +SELECT * FROM ns.tbl; +``` + +```console ++----+-------+------+------+ +| id | col1 | col2 | col3 | ++----+-------+------+------+ +| 1 | data1 | 123 | 456 | ++----+-------+------+------+ +``` + +### ステップ 10. データの暗号化を確認する + +データが暗号化されていることを確認するには、PostgreSQL に直接接続してデータをチェックします。 + +:::warning + +ScalarDB では、バックエンドデータベースからのデータの直接読み取りまたは書き込みはサポートされていません。このような場合、ScalarDB はデータの一貫性を保証できません。このガイドでは、テスト目的でバックエンドデータベースに直接アクセスしますが、実稼働環境ではこれを行うことはできません。 + +::: + +PostgreSQL に接続するには、次のコマンドを実行します。 + +```console +docker exec -it postgresql psql -U postgres +``` + +次に、次の SQL クエリを実行してテーブル内のデータを確認します。 + +```sql +SELECT id, col1, col2, col3 FROM ns.tbl; +``` + +以下のような出力が表示され、`col1` と `col2` のデータが暗号化されていることが確認されます。 + +```console + id | col1 | col2 | col3 +----+--------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------+------ + 1 | \x7661756c743a76313a6b6f76455062316a676e6a4a596b643743765539315a49714d625564545a61697152666c7967367837336e66 | \x7661756c743a76313a4b6244543162764678676d44424b526d7037794f5176423569616e615635304c473079664354514b3866513d | 456 +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/encrypt-wire-communications.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/encrypt-wire-communications.mdx new file mode 100644 index 00000000..6e178d16 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/encrypt-wire-communications.mdx @@ -0,0 +1,68 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ワイヤ通信の暗号化 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster は、トランスポート層セキュリティ (TLS) を使用したワイヤ暗号化をサポートしています。このドキュメントでは、ScalarDB Cluster でのワイヤ暗号化の設定について説明します。 + +ワイヤ暗号化機能では、次のものが暗号化されます: + +* ScalarDB Cluster ノードとクライアント間の通信。 +* すべての ScalarDB Cluster ノード間の通信 (クラスターの内部通信)。 + +この機能では、gRPC の TLS サポートが使用されます。詳細については、公式の gRPC [Security Policy](https://github.com/grpc/grpc-java/blob/master/SECURITY.md) を参照してください。 + +:::note + +実稼働環境では、ScalarDB Cluster ノードと基盤となるデータベース間のワイヤ暗号化を有効にすることを強くお勧めします。ScalarDB Cluster ノードと基盤となるデータベース間のワイヤ暗号化を有効にする方法については、基盤となるデータベースの製品ドキュメントを参照してください。 + +::: + +## 設定 + +このセクションでは、ワイヤ暗号化に使用できる設定について説明します。 + +### ScalarDB Cluster ノードの設定 + +ワイヤ暗号化を有効にするには、`scalar.db.cluster.tls.enabled` を `true` に設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|---------------------------------|--------------------------------|-----------| +| `scalar.db.cluster.tls.enabled` | ワイヤ暗号化 (TLS) が有効かどうか。 | `false` | + +次の設定も設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|-----------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------| +| `scalar.db.cluster.tls.ca_root_cert_pem` | TLS 通信用のカスタム CA ルート証明書 (PEM データ)。 | | +| `scalar.db.cluster.tls.ca_root_cert_path` | TLS 通信用のカスタム CA ルート証明書 (ファイルパス)。 | | +| `scalar.db.cluster.tls.override_authority` | TLS 通信のカスタム権限。これは、実際に接続しているホストを変更するものではありません。これはテスト用ですが、DNS オーバーライドの代替としてテスト以外でも安全に使用できます。たとえば、`scalar.db.cluster.node.tls.cert_chain_path` に設定した証明書チェーンファイルで提示されるホスト名を指定できます。 | | +| `scalar.db.cluster.node.tls.cert_chain_path` | TLS 通信に使用される証明書チェーンファイル。 | | +| `scalar.db.cluster.node.tls.private_key_path` | TLS 通信に使用される秘密鍵ファイル。 | | + +証明機関 (CA) ルート証明書を指定するには、`scalar.db.cluster.tls.ca_root_cert_pem` または `scalar.db.cluster.tls.ca_root_cert_path` のいずれかを設定する必要があります。両方を設定すると、`scalar.db.cluster.tls.ca_root_cert_pem` が使用されます。 + +### ScalarDB Cluster Java Client SDK 設定 + +クライアント側でワイヤ暗号化を有効にするには、`scalar.db.cluster.tls.enabled` を `true` に設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|---------------------------------|--------------------------------|-----------| +| `scalar.db.cluster.tls.enabled` | ワイヤ暗号化 (TLS) が有効かどうか。 | `false` | + +次の設定も設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|--------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------| +| `scalar.db.cluster.tls.ca_root_cert_pem` | TLS 通信用のカスタム CA ルート証明書 (PEM データ)。 | | +| `scalar.db.cluster.tls.ca_root_cert_path` | TLS 通信用のカスタム CA ルート証明書 (ファイルパス)。 | | +| `scalar.db.cluster.tls.override_authority` | TLS 通信のカスタム権限。これは、実際に接続しているホストを変更するものではありません。これはテスト用ですが、DNS オーバーライドの代替としてテスト以外でも安全に使用できます。たとえば、`scalar.db.cluster.node.tls.cert_chain_path` に設定した証明書チェーンファイルで提示されるホスト名を指定できます。 | | + +CA ルート証明書を指定するには、`scalar.db.cluster.tls.ca_root_cert_pem` または `scalar.db.cluster.tls.ca_root_cert_path` のいずれかを設定する必要があります。両方を設定すると、`scalar.db.cluster.tls.ca_root_cert_pem` が使用されます。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-dotnet.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-dotnet.mdx new file mode 100644 index 00000000..89d3617c --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-dotnet.mdx @@ -0,0 +1,443 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# .NET を使って ScalarDB Cluster をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、.NET API 経由で [ScalarDB Cluster](./index.mdx) を使用するサンプルアプリケーションを作成する方法について説明します。 + +## 概要 + +このチュートリアルでは、.NET API 経由で ScalarDB Cluster を使用して、与信枠を使用してアイテムを注文し、支払いを行うことができるサンプル電子商取引アプリケーションを作成するプロセスについて説明します。 + +:::note + +サンプルアプリケーションの焦点は ScalarDB の使用方法を示すことにあるため、アプリケーション固有のエラー処理、認証処理、および同様の機能はサンプルアプリケーションには含まれていません。ScalarDB での例外処理の詳細については、[ScalarDB Cluster .NET Client SDK での例外処理](../scalardb-cluster-dotnet-client-sdk/exception-handling.mdx)を参照してください。 + +::: + +次の図は、サンプルアプリケーションのシステムアーキテクチャを示しています。 + +```mermaid +stateDiagram-v2 + state ".NET API を使用したサンプルアプリケーション" as SA + state "Kubernetes クラスター" as KC + state "サービス (Envoy)" as SE + state "ポッド" as P1 + state "ポッド" as P2 + state "ポッド" as P3 + state "Envoy" as E1 + state "Envoy" as E2 + state "Envoy" as E3 + state "サービス (ScalarDB Cluster)" as SSC + state "ScalarDB Cluster" as SC1 + state "ScalarDB Cluster" as SC2 + state "ScalarDB Cluster" as SC3 + state "PostgreSQL" as PSQL + SA --> SE + state KC { + SE --> E1 + SE --> E2 + SE --> E3 + state P1 { + E1 --> SSC + E2 --> SSC + E3 --> SSC + } + SSC --> SC1 + SSC --> SC2 + SSC --> SC3 + state P2 { + SC1 --> PSQL + SC1 --> SC2 + SC1 --> SC3 + SC2 --> PSQL + SC2 --> SC1 + SC2 --> SC3 + SC3 --> PSQL + SC3 --> SC1 + SC3 --> SC2 + } + state P3 { + PSQL + } + } +``` + +### このサンプルアプリケーションで実行できること + +サンプルアプリケーションは、次の種類のトランザクションをサポートしています: + +- 顧客情報を取得します。 +- 信用枠を使用して注文を行います。 + - 注文のコストが顧客の信用限度額を下回っているかどうかを確認します。 + - チェックが成功した場合は、注文履歴を記録し、顧客が支払った金額を更新します。 +- 注文 ID で注文情報を取得します。 +- 顧客 ID で注文情報を取得します。 +- 支払いを行います。 + - 顧客が支払った金額を減らします。 + +## このサンプルアプリケーションの前提条件 + +- [.NET SDK 8.0](https://dotnet.microsoft.com/ja-jp/download/dotnet/8.0) +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx)の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + +:::note + +.NET SDK 8.0 は、このサンプルアプリケーションの作成に使用されたバージョンです。サポートされているすべてのバージョンについては、[要件](../requirements.mdx#net)を参照してください。 + +::: + +## ScalarDB Cluster のセットアップ + +次のセクションでは、サンプルの電子商取引アプリケーションをセットアップする方法について説明します。 + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル**を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、以下のコマンドを実行して、サンプルアプリケーションが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sample +``` + +### ScalarDB.Client パッケージの参照バージョンを更新する + +ScalarDB Cluster を使用するには、お好みのテキストエディターで `ScalarDbClusterSample.csproj` を開きます。その後、参照されている `ScalarDB.Client` パッケージのバージョンを、デプロイされている ScalarDB Cluster のバージョンに合わせて `.` を置き換えて更新します。 + +```xml + +``` + +### `scalardb-options.json` を変更する + +ScalarDB Cluster に接続するには、`scalardb-options.json` も変更する必要があります。ただし、その前に、Envoy サービスリソース (`scalardb-cluster-envoy`) の `EXTERNAL-IP` アドレスを取得する必要があります。サービスリソースを取得するには、次のコマンドを実行します。 + +```console +kubectl get svc scalardb-cluster-envoy +``` + +以下のような出力が表示されます(実際に表示される `CLUSTER-IP`、`PORT(S)`、`AGE` の値は異なります)。 + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +次のコマンドを実行して `scalardb-options.json` を開きます。 + +```console +vim scalardb-options.json +``` + +次に、`database.properties` を次のように変更します。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053" + } +} +``` + +### 初期データをロードする + +サンプルアプリケーションを実行する前に、次のコマンドを実行して初期データをロードする必要があります。 + +```console +dotnet run LoadInitialData +``` + +#### スキーマの詳細 + +上記のコマンドを実行すると、スキーマも適用されます。すべてのテーブルは `sample` 名前空間に作成されます。 + +- `sample.customers`: 顧客情報を管理するテーブル + - `credit_limit`: 貸し手が顧客に信用枠から支出を許可する最大金額 + - `credit_total`: 顧客が信用枠から支出した金額 +- `sample.orders`: 注文情報を管理するテーブル +- `sample.statements`: 注文明細情報を管理するテーブル +- `sample.items`: 注文するアイテムの情報を管理するテーブル + +スキーマのエンティティ関係図は次のとおりです。 + +![ERD](images/getting-started-ERD.png) + +#### 初期データ + +初期データがロードされたら、次のレコードがテーブルに保存されます。 + +**`sample.customers` テーブル** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` テーブル** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションでトランザクションを実行し、データを取得する + +次のセクションでは、サンプル電子商取引アプリケーションでトランザクションを実行し、データを取得する方法について説明します。 + +### 顧客情報を取得する + +次のコマンドを実行して、ID が `1` である顧客に関する情報を取得することから始めます。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 0 +} +``` + +### 注文する + +次に、以下のコマンドを実行して、顧客 ID `1` にリンゴ3個とオレンジ2個を注文してもらいます。 + +:::note + +このコマンドの注文形式は `dotnet run PlaceOrder :,:,..."` です。 + +::: + +```console +dotnet run PlaceOrder 1 1:3,2:2 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b" +} +``` + +### 注文の詳細を確認する + +次のコマンドを実行して注文の詳細を確認します。`` は、前のコマンドを実行した後に表示される `order_id` の UUID に置き換えてください。 + +```console +dotnet run GetOrder +``` + +`order_id` と `timestamp` の UUID が異なる、以下のような出力が表示されます。 + +```console +{ + "order": { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + } +} +``` + +### 別の注文をする + +次のコマンドを実行して、顧客 ID `1` の `credit_total` の残額を使用してメロン1個を注文します。 + +```console +dotnet run PlaceOrder 1 5:1 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8" +} +``` + +### 注文履歴を確認する + +次のコマンドを実行して、顧客 ID `1` のすべての注文履歴を取得します。 + +```console +dotnet run GetOrders 1 +``` + +`order_id` と `timestamp` の UUID が異なる以下のような出力が表示されます。これは、顧客 ID `1` のすべての注文履歴をタイムスタンプの降順で表示します。 + +```console +{ + "orders": [ + { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + }, + { + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8", + "timestamp": 1743143505436, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 5, + "item_name": "Melon", + "price": 3000, + "count": 1, + "total": 3000 + } + ], + "total": 3000 + } + ] +} +``` + +### クレジット合計の確認 + +次のコマンドを実行して、顧客 ID `1` のクレジット合計を取得します。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。これは、顧客 ID `1` が `credit_total` の `credit_limit` に達しており、これ以上注文できないことを示しています。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 10000 +} +``` + +次のコマンドを実行して、ブドウ1個とマンゴー1個を注文してみます。 + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +次の出力が表示されます。これは、`credit_total` 金額が `credit_limit` 金額を超えたために注文が失敗したことを示しています。 + +```console +Unhandled exception: System.Exception: Credit limit exceeded (17500 > 10000) + at ScalarDbClusterSample.Sample.PlaceOrder(Int32 customerId, IReadOnlyDictionary`2 itemCounts) in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sample/Sample.cs:line 254 + at ScalarDbClusterSample.Commands.PlaceOrderCommand.<>c.<b__6_0>d.MoveNext() in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/PlaceOrderCommand.cs:line 47 +--- End of stack trace from previous location --- +... +``` + +### 支払いを行う + +注文を続行するには、顧客 ID `1` が支払いを行って `credit_total` の金額を減らす必要があります。 + +次のコマンドを実行して支払いを行います。 + +```console +dotnet run Repayment 1 8000 +``` + +次に、以下のコマンドを実行して、顧客 ID `1` の `credit_total` 金額を確認します。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。これは、顧客 ID `1` に支払いが適用され、`credit_total` の金額が減ったことを示しています。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 2000 +} +``` + +顧客 ID `1` が支払いを済ませたので、次のコマンドを実行してブドウ1個とメロン1個を注文します。 + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "ecd68f46-e248-4f2e-b581-620e9019bf5b" +} +``` + +## 参照 + +.NET API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [ScalarDB Cluster .NET Client SDK の概要](../scalardb-cluster-dotnet-client-sdk/index.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx new file mode 100644 index 00000000..d6d1695b --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx @@ -0,0 +1,324 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster GraphQL をはじめよう + +import JavadocLink from '/src/theme/JavadocLink.js'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +## 前提条件 + +- 以下のいずれかの Java Development Kit (JDK): + - [Oracle JDK](https://www.oracle.com/java/technologies/downloads/) LTS バージョン (8、11、17、または 21) + - [OpenJDK](https://openjdk.org/install/) LTS バージョン (8、11、17、または 21) +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx) の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + +## サンプルアプリケーション + +このチュートリアルでは、口座間で資金を移動できる電子マネーアプリケーションを作成するプロセスについて説明します。 + +次の図は、サンプルアプリケーションのシステムアーキテクチャを示しています。 + +``` + +-----------------------------------------------------------------------------------------------------------------------------------------+ + | [Kubernetes クラスター] | + | | + | [ポッド] [ポッド] [ポッド] | + | | + | +-------+ | + | +---> | Envoy | ---+ | + | | +-------+ | | + | | | | + +------------------------+ | +---------+ | +-------+ | +--------------------+ | + | Schema Loader | --+-> | サービス | ---+---> | Envoy | ---+---------> | サービス | ---+ | + | (間接クライアントモード) | | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | | + +------------------------+ | +---------+ | | +--------------------+ | +------------------------+ | + | | +-------+ | | +---> | ScalarDB Cluster ノード | ---+ | + | +---> | Envoy | ---+ | | +------------------------+ | | + | +-------+ | | | | + | | | +------------------------+ | +------------+ | + | +---+---> | ScalarDB Cluster ノード | ---+---> | PostgreSQL | | + | | | +------------------------+ | +------------+ | + | | | | | + | | | +------------------------+ | | + | | +---> | ScalarDB Cluster ノード | ---+ | + | | +------------------------+ | + +------------+ | +----------------------------+ | | + | ブラウザ | ------+---------------------------------------> | サービス | ---+ | + | (GraphiQL) | | | (ScalarDB Cluster GraphQL) | | + +------------+ | +----------------------------+ | + | | + +-----------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ステップ 1. `schema.json` を作成する + +以下は簡単なサンプルスキーマです。 + +`schema.json` を作成し、ファイルに次の内容を追加します。 + +```json +{ + "emoney.account": { + "transaction": true, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } +} +``` + +## ステップ 2. `database.properties` を作成する + +ScalarDB Cluster の Schema Loader 用に `database.properties` を作成する必要があります。 + +ただし、まず Envoy (`scalardb-cluster-envoy`) のサービスリソースの `EXTERNAL-IP` アドレスを取得する必要があります。 + +`EXTERNAL-IP` アドレスを確認するには、次のコマンドを実行します。 + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +次に、`database.properties` を作成し、ファイルに次の内容を追加します。 + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:localhost +``` + +ScalarDB Cluster に接続するには、`scalar.db.transaction_manager` プロパティに `cluster` を指定する必要があります。 + +また、このチュートリアルでは `indirect` クライアントモードを使用して Envoy のサービスリソースに接続します。 + +クライアントモードの詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) を参照してください。 + +## ステップ 3. スキーマをロードする + +ScalarDB Cluster 経由でスキーマをロードするには、ScalarDB Cluster 専用の Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Cluster 用の Schema Loader は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Cluster 用の Schema Loader を実行できます。 + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +``` + +## ステップ 4. GraphiQL から操作を実行する + +ScalarDB Cluster では、`scalar.db.graphql.graphiql` プロパティが `true` に設定されている場合 (`true` がデフォルト値)、GraphiQL IDE が使用可能になります。 + +ScalarDB Cluster GraphQL (`scalardb-cluster-graphql`) のサービスリソースの `EXTERNAL-IP` アドレスを取得するには、次のコマンドを実行します。 + +```console +kubectl get svc scalardb-cluster-graphql +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-graphql LoadBalancer 10.105.74.214 localhost 8080:30514/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost`、GraphiQL IDE のエンドポイント URL は `http://localhost:8080/graphql` です。 +Web ブラウザでその URL を開くと、GraphiQL 画面が表示されます。 + +最初のレコードを挿入してみましょう。左ペインに次のミューテーションを貼り付け、ウィンドウ上部の三角形の `Execute Query` ボタンを押します。 + +```graphql +mutation PutUser1 { + account_put(put: {key: {id: "user1"}, values: {balance: 1000}}) +} +``` + +ScalarDB GraphQL は常にトランザクションを使用してクエリを実行します。上記のクエリは新しいトランザクションを開始し、ScalarDB Put コマンドを実行し、実行の最後にトランザクションをコミットします。 + +GraphQL サーバーからの次の応答が右側のペインに表示されます。 + +```json +{ + "data": { + "account_put": true + } +} +``` + +`"data"` フィールドには実行結果が含まれます。この応答は、ミューテーションの `account_put` フィールドが成功したことを示しています。ミューテーションの結果タイプは `Boolean!` で、操作が成功したかどうかを示します。 + +次に、挿入したレコードを取得しましょう。左ペインの前のミューテーションの横に次のクエリを貼り付けて、`Execute Query` ボタンをクリックします。上記の `mutation PutUser1` を削除していないため、ボタンの下にプルダウンメニューが表示され、実行する操作を選択できます。 以下に示すように、`GetUser1` を選択します。 + +```graphql +query GetUser1 { + account_get(get: {key: {id: "user1"}}) { + account { + id + balance + } + } +} +``` + +右側のペインに次の結果が表示されます。 + +```json +{ + "data": { + "account_get": { + "account": { + "id": "user1", + "balance": 1000 + } + } + } +} +``` + +### GraphQL API と ScalarDB Java API 間のマッピング + +自動的に生成された GraphQL スキーマは、クエリ、ミューテーション、および入出力のオブジェクトタイプを定義し、ターゲット名前空間内のすべてのテーブルに対して CRUD 操作を実行できるようにします。これらの操作は、 インターフェースで定義されている ScalarDB API と一致するように設計されています。 + +名前空間に `account` テーブルがあると仮定すると、次のクエリとミューテーションが生成されます。 + +| ScalarDB API | GraphQL ルートタイプ | GraphQL フィールド | +|--------------------------------------------------------|-------------------|------------------------------------------------------------------------------------| +| `get(Get get)` | `Query` | `account_get(get: account_GetInput!): account_GetPayload` | +| `scan(Scan scan)` | `Query` | `account_scan(scan: account_ScanInput!): account_ScanPayload` | +| `put(Put put)` | `Mutation` | `account_put(put: account_PutInput!): Boolean!` | +| `put(java.util.List puts)` | `Mutation` | `account_bulkPut(put: [account_PutInput!]!): Boolean!` | +| `delete(Delete delete)` | `Mutation` | `account_delete(delete: account_DeleteInput!): Boolean!` | +| `delete(java.util.List deletes)` | `Mutation` | `account_bulkDelete(delete: [account_DeleteInput!]!): Boolean!` | +| `mutate(java.util.List mutations)` | `Mutation` | `account_mutate(put: [account_PutInput!]delete: [account_DeleteInput!]): Boolean!` | + +クラスタリングキーのないテーブルでは、`scan` フィールドは生成されないことに注意してください。これが、この電子マネーサンプルアプリケーションで `account_scan` フィールドが使用できない理由です。 + +生成されたすべての GraphQL タイプは、GraphiQL のドキュメントエクスプローラー (左上隅の `< Docs` リンク) で確認できます。 + +## ステップ 5. GraphiQL からの複数のリクエストにまたがるトランザクションを実行する + +複数の GraphQL リクエストにまたがるトランザクションを実行してみましょう。 + +生成されたスキーマには、トランザクションを識別できる `@transaction` ディレクティブが用意されています。このディレクティブは、クエリとミューテーションの両方で使用できます。 + +トランザクションを開始する前に、次のミューテーションを使用して必要なレコードを挿入する必要があります。 + +```graphql +mutation PutUser2 { + account_put(put: {key: {id: "user2"}, values: {balance: 1000}}) +} +``` + +### 操作を実行する前にトランザクションを開始する + +以下を実行して、クエリまたはミューテーションに引数のない `@transaction` ディレクティブを追加すると、実行時に新しいトランザクションが開始されます。 + +```graphql +query GetAccounts @transaction { + user1: account_get(get: {key: {id: "user1"}}) { + account { balance } + } + user2: account_get(get: {key: {id: "user2"}}) { + account { balance } + } +} +``` + +上記のコマンドを実行すると、`extensions` フィールドにトランザクション ID が入った結果が返されます。extensions の `id` 値は、リクエスト内の操作が実行されたトランザクション ID です。この場合、リクエストによって開始されたトランザクションの新しい ID は次のとおりです。 + +```json +{ + "data": { + "user1": { + "account": { + "balance": 1000 + } + }, + "user2": { + "account": { + "balance": 1000 + } + } + }, + "extensions": { + "transaction": { + "id": "c88da8a6-a13f-4857-82fe-45f1ab4150f9" + } + } +} +``` + +### 継続トランザクションで操作を実行する + +開始したトランザクションで次のクエリまたはミューテーションを実行するには、トランザクション ID を `@transaction` の `id` 引数として指定します。次の例では、同じトランザクションで user1 のアカウントから user2 のアカウントに残高を転送することにより、前の例で取得した2つのアカウントを更新します。 + +```graphql +mutation Transfer @transaction(id: "c88da8a6-a13f-4857-82fe-45f1ab4150f9") { + user1: account_put(put: {key: {id: "user1"}, values: {balance: 750}}) + user2: account_put(put: {key: {id: "user2"}, values: {balance: 1250}}) +} +``` + +GraphQL で開始されたトランザクションには1分のタイムアウト (デフォルト) があり、タイムアウトを超えると自動的にアボートされることに注意してください。 + +### トランザクションをコミットする + +継続中のトランザクションをコミットするには、`@transaction` ディレクティブの引数として `id` と `commit: true` フラグの両方を指定します。 + +```graphql +query GetAndCommit @transaction(id: "c88da8a6-a13f-4857-82fe-45f1ab4150f9", commit: true) { + user1: account_get(get: {key: {id: "user1"}}) { + account { balance } + } + user2: account_get(get: {key: {id: "user2"}}) { + account { balance } + } +} +``` + +**注:** `@transaction(commit: true)` のように `id` 引数なしで `commit: true` フラグを指定すると、新しいトランザクションが開始され、1つの操作に対してのみコミットされます。この動作は、GraphiQL を使用した上記の例で見られるように、`@transaction` ディレクティブを指定しない場合とまったく同じです。つまり、`@transaction(commit: true)` が指定されている場合は、ディレクティブ自体を省略できます。 + +### トランザクションをアボートまたはロールバックする + +トランザクションを明示的にアボートまたはロールバックする必要がある場合は、`abort` または `rollback` ミューテーションフィールドを互換的に使用できます (どちらも効果と使用方法は同じです)。これらのフィールドを他の操作と混在させることはできないため、次のように `abort` または `rollback` ミューテーションフィールドのみを指定する必要があります。 + +```graphql +mutation AbortTx @transaction(id: "c88da8a6-a13f-4857-82fe-45f1ab4150f9") { + abort +} +``` + +または: + +```graphql +mutation RollbackTx @transaction(id: "c88da8a6-a13f-4857-82fe-45f1ab4150f9") { + rollback +} +``` + +## 参照 + +その他の ScalarDB Cluster チュートリアルについては、以下を参照してください。 + +- [ScalarDB Cluster をはじめよう](getting-started-with-scalardb-cluster.mdx) +- [JDBC 経由の ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [ScalarDB Cluster での Go をはじめよう](getting-started-with-using-go-for-scalardb-cluster.mdx) +- [ScalarDB Cluster での Python をはじめよう](getting-started-with-using-python-for-scalardb-cluster.mdx) + +Java API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-dotnet.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-dotnet.mdx new file mode 100644 index 00000000..687c3fef --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-dotnet.mdx @@ -0,0 +1,443 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# .NET を使って ScalarDB Cluster SQL をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、.NET API を使用して [ScalarDB Cluster](./index.mdx) SQL を使用するサンプルアプリケーションを作成する方法について説明します。 + +## 概要 + +このチュートリアルでは、ScalarDB を使用して、商品を注文し、与信枠を使用して支払うことができるサンプルの電子商取引アプリケーションを作成するプロセスを説明します。 + +:::note + +このサンプルアプリケーションの目的は ScalarDB を使用する方法を示すことにあるため、アプリケーション固有のエラーハンドリング、認証処理、および類似の機能はサンプルアプリケーションには含まれていません。例外処理の詳細については、[ScalarDB Cluster .NET Client SDK における例外処理](../scalardb-cluster-dotnet-client-sdk/exception-handling.mdx)を参照してください。 + +::: + +以下の図は、サンプルアプリケーションのシステムアーキテクチャを示しています。 + +```mermaid +stateDiagram-v2 + state ".NET API を使用したサンプルアプリケーション" as SA + state "Kubernetes クラスター" as KC + state "サービス (Envoy)" as SE + state "ポッド" as P1 + state "ポッド" as P2 + state "ポッド" as P3 + state "Envoy" as E1 + state "Envoy" as E2 + state "Envoy" as E3 + state "サービス (ScalarDB Cluster)" as SSC + state "ScalarDB Cluster" as SC1 + state "ScalarDB Cluster" as SC2 + state "ScalarDB Cluster" as SC3 + state "PostgreSQL" as PSQL + SA --> SE + state KC { + SE --> E1 + SE --> E2 + SE --> E3 + state P1 { + E1 --> SSC + E2 --> SSC + E3 --> SSC + } + SSC --> SC1 + SSC --> SC2 + SSC --> SC3 + state P2 { + SC1 --> PSQL + SC1 --> SC2 + SC1 --> SC3 + SC2 --> PSQL + SC2 --> SC1 + SC2 --> SC3 + SC3 --> PSQL + SC3 --> SC1 + SC3 --> SC2 + } + state P3 { + PSQL + } + } +``` + +### このサンプルアプリケーションで実行できること + +サンプルアプリケーションは、次の種類のトランザクションをサポートしています: + +- 顧客情報を取得します。 +- 信用枠を使用して注文を行います。 + - 注文のコストが顧客の信用限度額を下回っているかどうかを確認します。 + - チェックが成功した場合は、注文履歴を記録し、顧客が支払った金額を更新します。 +- 注文 ID で注文情報を取得します。 +- 顧客 ID で注文情報を取得します。 +- 支払いを行います。 + - 顧客が支払った金額を減らします。 + +## このサンプルアプリケーションの前提条件 + +- [.NET SDK 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx)の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + +:::note + +.NET SDK 8.0 は、このサンプルアプリケーションの作成に使用されたバージョンです。サポートされているすべてのバージョンについては、[要件](../requirements.mdx#net)を参照してください。 + +::: + +## ScalarDB Cluster のセットアップ + +次のセクションでは、サンプルの電子商取引アプリケーションをセットアップする方法について説明します。 + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル**を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、以下のコマンドを実行して、サンプルアプリケーションが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sql-sample +``` + +### ScalarDB.Client パッケージの参照バージョンを更新する + +ScalarDB Cluster を使用するには、お好みのテキストエディターで `ScalarDbClusterSample.csproj` を開きます。その後、参照されている `ScalarDB.Client` パッケージのバージョンを、デプロイされている ScalarDB Cluster のバージョンに合わせて `.` を置き換えて更新します。 + +```xml + +``` + +### `scalardb-options.json` を変更する + +ScalarDB Cluster に接続するには、`scalardb-options.json` も変更する必要があります。ただし、その前に、Envoy サービスリソース (`scalardb-cluster-envoy`) の `EXTERNAL-IP` アドレスを取得する必要があります。サービスリソースを取得するには、次のコマンドを実行します。 + +```console +kubectl get svc scalardb-cluster-envoy +``` + +以下のような出力が表示されます(実際に表示される `CLUSTER-IP`、`PORT(S)`、`AGE` の値は異なります)。 + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +次のコマンドを実行して `scalardb-options.json` を開きます。 + +```console +vim scalardb-options.json +``` + +その後、以下のように `scalardb-options.json` を修正します。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053" + } +} +``` + +### 初期データをロードする + +サンプルアプリケーションを実行する前に、次のコマンドを実行して初期データをロードする必要があります。 + +```console +dotnet run LoadInitialData +``` + +#### スキーマの詳細 + +上記のコマンドを実行すると、スキーマも適用されます。すべてのテーブルは `sample` 名前空間に作成されます。 + +- `sample.customers`: 顧客情報を管理するテーブル + - `credit_limit`: 貸し手が顧客に信用枠から支出を許可する最大金額 + - `credit_total`: 顧客が信用枠から支出した金額 +- `sample.orders`: 注文情報を管理するテーブル +- `sample.statements`: 注文明細情報を管理するテーブル +- `sample.items`: 注文するアイテムの情報を管理するテーブル + +スキーマのエンティティ関係図は次のとおりです。 + +![ERD](images/getting-started-ERD.png) + +#### 初期データ + +初期データがロードされたら、次のレコードがテーブルに保存されます。 + +**`sample.customers` テーブル** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` テーブル** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションでトランザクションを実行し、データを取得する + +次のセクションでは、サンプル電子商取引アプリケーションでトランザクションを実行し、データを取得する方法について説明します。 + +### 顧客情報を取得する + +次のコマンドを実行して、ID が `1` である顧客に関する情報を取得することから始めます。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 0 +} +``` + +### 注文する + +次に、以下のコマンドを実行して、顧客 ID `1` にリンゴ3個とオレンジ2個を注文してもらいます。 + +:::note + +このコマンドの注文形式は `dotnet run PlaceOrder :,:,..."` です。 + +::: + +```console +dotnet run PlaceOrder 1 1:3,2:2 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b" +} +``` + +### 注文の詳細を確認する + +次のコマンドを実行して注文の詳細を確認します。`` は、前のコマンドを実行した後に表示される `order_id` の UUID に置き換えてください。 + +```console +dotnet run GetOrder +``` + +`order_id` と `timestamp` の UUID が異なる、以下のような出力が表示されます。 + +```console +{ + "order": { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + } +} +``` + +### 別の注文をする + +次のコマンドを実行して、顧客 ID `1` の `credit_total` の残額を使用してメロン1個を注文します。 + +```console +dotnet run PlaceOrder 1 5:1 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8" +} +``` + +### 注文履歴を確認する + +次のコマンドを実行して、顧客 ID `1` のすべての注文履歴を取得します。 + +```console +dotnet run GetOrders 1 +``` + +`order_id` と `timestamp` の UUID が異なる以下のような出力が表示されます。これは、顧客 ID `1` のすべての注文履歴をタイムスタンプの降順で表示します。 + +```console +{ + "orders": [ + { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + }, + { + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8", + "timestamp": 1743143505436, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 5, + "item_name": "Melon", + "price": 3000, + "count": 1, + "total": 3000 + } + ], + "total": 3000 + } + ] +} +``` + +### クレジット合計の確認 + +次のコマンドを実行して、顧客 ID `1` のクレジット合計を取得します。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。これは、顧客 ID `1` が `credit_total` の `credit_limit` に達しており、これ以上注文できないことを示しています。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 10000 +} +``` + +次のコマンドを実行して、ブドウ1個とマンゴー1個を注文してみます。 + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +次の出力が表示されます。これは、`credit_total` 金額が `credit_limit` 金額を超えたために注文が失敗したことを示しています。 + +```console +Unhandled exception: System.Exception: Credit limit exceeded (17500 > 10000) + at ScalarDbClusterSqlSample.Sample.PlaceOrder(Int32 customerId, IReadOnlyDictionary`2 itemCounts) in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sql-sample/Sample.cs:line 237 + at ScalarDbClusterSqlSample.Commands.PlaceOrderCommand.<>c.<b__6_0>d.MoveNext() in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sql-sample/Commands/PlaceOrderCommand.cs:line 47 +--- End of stack trace from previous location --- +... +``` + +### 支払いを行う + +注文を続行するには、顧客 ID `1` が支払いを行って `credit_total` の金額を減らす必要があります。 + +次のコマンドを実行して支払いを行います。 + +```console +dotnet run Repayment 1 8000 +``` + +次に、以下のコマンドを実行して、顧客 ID `1` の `credit_total` 金額を確認します。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。これは、顧客 ID `1` に支払いが適用され、`credit_total` の金額が減ったことを示しています。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 2000 +} +``` + +顧客 ID `1` が支払いを済ませたので、次のコマンドを実行してブドウ1個とメロン1個を注文します。 + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "ecd68f46-e248-4f2e-b581-620e9019bf5b" +} +``` + +## 参照 + +.NET API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [ScalarDB Cluster .NET Client SDK の概要](../scalardb-cluster-dotnet-client-sdk/index.mdx) +- [ScalarDB Cluster .NET Client SDK での分散 SQL トランザクションをはじめよう](../scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx new file mode 100644 index 00000000..3a17c976 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx @@ -0,0 +1,231 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# JDBC 経由の ScalarDB Cluster SQL をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、JDBC 経由で ScalarDB Cluster SQL を使用してサンプルアプリケーションを作成する方法について説明します。 + +## このサンプルアプリケーションの前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx) の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../requirements.mdx)を参照してください。 + +::: + +## サンプルアプリケーション + +このチュートリアルでは、ScalarDB JDBC を使用して、クレジットラインでアイテムを注文し、支払いを行うことができるサンプル電子商取引アプリケーションを作成するプロセスについて説明します。 + +次の図は、サンプルアプリケーションのシステムアーキテクチャを示しています。 + +``` + +------------------------------------------------------------------------------------------------------------------------------+ + | [Kubernetes クラスター] | + | | + | [ポッド] [ポッド] [ポッド] | + +------------------------+ | | + | SQL CLI | | +-------+ +-----------------------+ | + | (間接クライアントモード) | --+ | +---> | Envoy | ---+ +---> | ScalarDB Cluster ノード | ---+ | + +------------------------+ | | | +-------+ | | +-----------------------+ | | + | | | | | | | + | | +---------+ | +-------+ | +--------------------+ | +-----------------------+ | +------------+ | + +--+-> | サービス | ---+---> | Envoy | ---+---> | サービス | ---+---> | ScalarDB Cluster ノード | ---+---> | PostgreSQL | | + | | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | +-----------------------+ | +------------+ | + +-------------------------+ | | +---------+ | | +--------------------+ | | | + | ScalarDB JDBC の | | | | +-------+ | | +-----------------------+ | | + | サンプルアプリケーション | --+ | +---> | Envoy | ---+ +---> | ScalarDB Cluster ノード | ---+ | + | (間接クライアントモード) | | +-------+ +-----------------------+ | + +-------------------------+ | | + +------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ステップ 1. ScalarDB サンプルリポジトリをクローンする + +```console +git clone https://github.com/scalar-labs/scalardb-samples.git +cd scalardb-samples/scalardb-sql-jdbc-sample +``` + +## ステップ 2. `scalardb-sql.properties` を変更する + +ScalarDB Cluster に接続するには、`scalardb-sql.properties` も変更する必要があります。ただし、その前に、次のように Envoy (`scalardb-cluster-envoy`) のサービスリソースの `EXTERNAL-IP` アドレスを取得する必要があります。 + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +次に、`scalardb-sql.properties` を開きます。 + +```console +vim scalardb-sql.properties +``` + +次に、`scalardb-sql.properties` を次のように変更します。 + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost +``` + +ScalarDB Cluster に接続するには、`scalar.db.sql.connection_mode` プロパティに `cluster` を指定する必要があります。また、このチュートリアルでは `indirect` クライアントモードを使用して Envoy のサービスリソースに接続します。クライアントモードの詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) を参照してください。 + +## ステップ 3. スキーマをロードする + +スキーマをロードするには、[SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli) を使用する必要があります。SQL CLI は [ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドを実行して Cluster 用の SQL CLI を使用できます。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-sql.properties --file schema.sql +``` + +## ステップ 4. 初期データをロードする + +サンプルアプリケーションを実行する前に、次のコマンドを実行して初期データをロードする必要があります。 + +```console +./gradlew run --args="LoadInitialData" +``` + +初期データがロードされた後、次のレコードがテーブルに保存されます: + +- `sample.customers` テーブルの場合: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +- `sample.items` テーブルの場合: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## ステップ 5. サンプルアプリケーションを実行する + +まず、ID が `1` である顧客に関する情報を取得します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 0} +... +``` + +次に、顧客 ID `1` を使用して、リンゴ3個とオレンジ2個を注文します。注文形式は `:,:,...` であることに注意してください。 + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +... +{"order_id": "454f9c97-f456-44fd-96da-f527187fe39b"} +... +``` + +このコマンドを実行すると、注文 ID が表示されます。 + +注文 ID を使用して注文の詳細を確認してみましょう。 + +```console +./gradlew run --args="GetOrder 454f9c97-f456-44fd-96da-f527187fe39b" +... +{"order": {"order_id": "454f9c97-f456-44fd-96da-f527187fe39b","timestamp": 1685602722821,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1, "name": "Apple", "price": 1000, "count": 3},{"item_id": 2, "name": "Orange", "price": 2000, "count": 2}],"total": 7000}} +... +``` + +次に、別の注文を出して、顧客 ID `1` の注文履歴を取得しましょう。 + +```console +./gradlew run --args="PlaceOrder 1 5:1" +... +{"order_id": "3f40c718-59ec-48aa-a6fe-2fdaf12ad094"} +... +./gradlew run --args="GetOrders 1" +... +{"order": [{"order_id": "454f9c97-f456-44fd-96da-f527187fe39b","timestamp": 1685602722821,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1, "name": "Apple", "price": 1000, "count": 3},{"item_id": 2, "name": "Orange", "price": 2000, "count": 2}],"total": 7000},{"order_id": "3f40c718-59ec-48aa-a6fe-2fdaf12ad094","timestamp": 1685602811718,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5, "name": "Melon", "price": 3000, "count": 1}],"total": 3000}]} +... +``` + +この注文履歴は、タイムスタンプの降順で表示されます。 + +顧客の現在の `credit_total` は `10000` です。顧客は、情報を取得したときに表示された `credit_limit` に達したため、これ以上注文することはできません。 + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +java.lang.RuntimeException: Credit limit exceeded + at sample.Sample.placeOrder(Sample.java:184) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:32) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:8) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.command.SampleCommand.main(SampleCommand.java:35) +... +``` + +支払いが完了すると、顧客は再度注文できるようになります。 + +```console +./gradlew run --args="Repayment 1 8000" +... +./gradlew run --args="GetCustomerInfo 1" +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 2000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +{"order_id": "fb71279d-88ea-4974-a102-0ec4e7d65e25"} +... +``` + +## サンプルアプリケーションのソースコード + +ScalarDB Cluster SQL JDBC の詳細については、[サンプルアプリケーションのソースコード](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sql-jdbc-sample/src/main/java/sample) を参照してください。 + +## 参照 + +その他の ScalarDB Cluster チュートリアルについては、以下を参照してください。 + +- [ScalarDB Cluster をはじめよう](getting-started-with-scalardb-cluster.mdx) +- [ScalarDB Cluster GraphQL をはじめよう](getting-started-with-scalardb-cluster-graphql.mdx) +- [Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [ScalarDB Cluster での Go をはじめよう](getting-started-with-using-go-for-scalardb-cluster.mdx) +- [ScalarDB Cluster での Python をはじめよう](getting-started-with-using-python-for-scalardb-cluster.mdx) + +Java API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-linq.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-linq.mdx new file mode 100644 index 00000000..cfb46cdd --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-linq.mdx @@ -0,0 +1,443 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# .NET と LINQ を使って ScalarDB Cluster SQL をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、[ScalarDB Cluster](./index.mdx) SQL を LINQ 経由で使用するサンプルアプリケーションを作成する方法について説明します。 + +## 概要 + +このチュートリアルでは、ScalarDB を使用して、商品を注文し、与信枠を使用して支払うことができるサンプルの電子商取引アプリケーションを作成するプロセスを説明します。 + +:::note + +このサンプルアプリケーションの目的は ScalarDB を使用する方法を示すことにあるため、アプリケーション固有のエラーハンドリング、認証処理、および類似の機能はサンプルアプリケーションには含まれていません。例外処理の詳細については、[ScalarDB Cluster .NET Client SDK における例外処理](../scalardb-cluster-dotnet-client-sdk/exception-handling.mdx)を参照してください。 + +::: + +以下の図は、サンプルアプリケーションのシステムアーキテクチャを示しています。 + +```mermaid +stateDiagram-v2 + state ".NET API を使用したサンプルアプリケーション" as SA + state "Kubernetes クラスター" as KC + state "サービス (Envoy)" as SE + state "ポッド" as P1 + state "ポッド" as P2 + state "ポッド" as P3 + state "Envoy" as E1 + state "Envoy" as E2 + state "Envoy" as E3 + state "サービス (ScalarDB Cluster)" as SSC + state "ScalarDB Cluster" as SC1 + state "ScalarDB Cluster" as SC2 + state "ScalarDB Cluster" as SC3 + state "PostgreSQL" as PSQL + SA --> SE + state KC { + SE --> E1 + SE --> E2 + SE --> E3 + state P1 { + E1 --> SSC + E2 --> SSC + E3 --> SSC + } + SSC --> SC1 + SSC --> SC2 + SSC --> SC3 + state P2 { + SC1 --> PSQL + SC1 --> SC2 + SC1 --> SC3 + SC2 --> PSQL + SC2 --> SC1 + SC2 --> SC3 + SC3 --> PSQL + SC3 --> SC1 + SC3 --> SC2 + } + state P3 { + PSQL + } + } +``` + +### このサンプルアプリケーションで実行できること + +サンプルアプリケーションは、次の種類のトランザクションをサポートしています: + +- 顧客情報を取得します。 +- 信用枠を使用して注文を行います。 + - 注文のコストが顧客の信用限度額を下回っているかどうかを確認します。 + - チェックが成功した場合は、注文履歴を記録し、顧客が支払った金額を更新します。 +- 注文 ID で注文情報を取得します。 +- 顧客 ID で注文情報を取得します。 +- 支払いを行います。 + - 顧客が支払った金額を減らします。 + +## このサンプルアプリケーションの前提条件 + +- [.NET SDK 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [Kubernetes 上での ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx)の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + +:::note + +.NET SDK 8.0 は、このサンプルアプリケーションの作成に使用されたバージョンです。サポートされているすべてのバージョンについては、[要件](../requirements.mdx#net)を参照してください。 + +::: + +## ScalarDB Cluster のセットアップ + +次のセクションでは、サンプルの電子商取引アプリケーションをセットアップする方法について説明します。 + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル**を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、以下のコマンドを実行して、サンプルアプリケーションが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-linq-sample +``` + +### ScalarDB.Client パッケージの参照バージョンを更新する + +ScalarDB Cluster を使用するには、お好みのテキストエディターで `ScalarDbClusterSample.csproj` を開きます。その後、参照されている `ScalarDB.Client` パッケージのバージョンを、デプロイされている ScalarDB Cluster のバージョンに合わせて `.` を置き換えて更新します。 + +```xml + +``` + +### `scalardb-options.json` を変更する + +ScalarDB Cluster に接続するには、`scalardb-options.json` も変更する必要があります。ただし、その前に、Envoy サービスリソース (`scalardb-cluster-envoy`) の `EXTERNAL-IP` アドレスを取得する必要があります。サービスリソースを取得するには、次のコマンドを実行します。 + +```console +kubectl get svc scalardb-cluster-envoy +``` + +以下のような出力が表示されます(実際に表示される `CLUSTER-IP`、`PORT(S)`、`AGE` の値は異なります)。 + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +次のコマンドを実行して `scalardb-options.json` を開きます。 + +```console +vim scalardb-options.json +``` + +次に、`database.properties` を次のように変更します。 + +```json +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053" + } +} +``` + +### 初期データをロードする + +サンプルアプリケーションを実行する前に、次のコマンドを実行して初期データをロードする必要があります。 + +```console +dotnet run LoadInitialData +``` + +#### スキーマの詳細 + +上記のコマンドを実行すると、スキーマも適用されます。すべてのテーブルは `sample` 名前空間に作成されます。 + +- `sample.customers`: 顧客情報を管理するテーブル + - `credit_limit`: 貸し手が顧客に信用枠から支出を許可する最大金額 + - `credit_total`: 顧客が信用枠から支出した金額 +- `sample.orders`: 注文情報を管理するテーブル +- `sample.statements`: 注文明細情報を管理するテーブル +- `sample.items`: 注文するアイテムの情報を管理するテーブル + +スキーマのエンティティ関係図は次のとおりです。 + +![ERD](images/getting-started-ERD.png) + +#### 初期データ + +初期データがロードされたら、次のレコードがテーブルに保存されます。 + +**`sample.customers` テーブル** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` テーブル** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションでトランザクションを実行し、データを取得する + +次のセクションでは、サンプル電子商取引アプリケーションでトランザクションを実行し、データを取得する方法について説明します。 + +### 顧客情報を取得する + +次のコマンドを実行して、ID が `1` である顧客に関する情報を取得することから始めます。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 0 +} +``` + +### 注文する + +次に、以下のコマンドを実行して、顧客 ID `1` にリンゴ3個とオレンジ2個を注文してもらいます。 + +:::note + +このコマンドの注文形式は `dotnet run PlaceOrder :,:,..."` です。 + +::: + +```console +dotnet run PlaceOrder 1 1:3,2:2 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b" +} +``` + +### 注文の詳細を確認する + +次のコマンドを実行して注文の詳細を確認します。`` は、前のコマンドを実行した後に表示される `order_id` の UUID に置き換えてください。 + +```console +dotnet run GetOrder +``` + +`order_id` と `timestamp` の UUID が異なる、以下のような出力が表示されます。 + +```console +{ + "order": { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + } +} +``` + +### 別の注文をする + +次のコマンドを実行して、顧客 ID `1` の `credit_total` の残額を使用してメロン1個を注文します。 + +```console +dotnet run PlaceOrder 1 5:1 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8" +} +``` + +### 注文履歴を確認する + +次のコマンドを実行して、顧客 ID `1` のすべての注文履歴を取得します。 + +```console +dotnet run GetOrders 1 +``` + +`order_id` と `timestamp` の UUID が異なる以下のような出力が表示されます。これは、顧客 ID `1` のすべての注文履歴をタイムスタンプの降順で表示します。 + +```console +{ + "orders": [ + { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + }, + { + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8", + "timestamp": 1743143505436, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 5, + "item_name": "Melon", + "price": 3000, + "count": 1, + "total": 3000 + } + ], + "total": 3000 + } + ] +} +``` + +### クレジット合計の確認 + +次のコマンドを実行して、顧客 ID `1` のクレジット合計を取得します。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。これは、顧客 ID `1` が `credit_total` の `credit_limit` に達しており、これ以上注文できないことを示しています。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 10000 +} +``` + +次のコマンドを実行して、ブドウ1個とマンゴー1個を注文してみます。 + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +次の出力が表示されます。これは、`credit_total` 金額が `credit_limit` 金額を超えたために注文が失敗したことを示しています。 + +```console +Unhandled exception: System.Exception: Credit limit exceeded (17500 > 10000) + at ScalarDbClusterLinqSample.Sample.PlaceOrder(Int32 customerId, IReadOnlyDictionary`2 itemCounts) in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Sample.cs:line 145 + at ScalarDbClusterLinqSample.Commands.PlaceOrderCommand.<>c.<b__6_0>d.MoveNext() in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/PlaceOrderCommand.cs:line 47 +--- End of stack trace from previous location --- +... +``` + +### 支払いを行う + +注文を続行するには、顧客 ID `1` が支払いを行って `credit_total` の金額を減らす必要があります。 + +次のコマンドを実行して支払いを行います。 + +```console +dotnet run Repayment 1 8000 +``` + +次に、以下のコマンドを実行して、顧客 ID `1` の `credit_total` 金額を確認します。 + +```console +dotnet run GetCustomerInfo 1 +``` + +次の出力が表示されます。これは、顧客 ID `1` に支払いが適用され、`credit_total` の金額が減ったことを示しています。 + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 2000 +} +``` + +顧客 ID `1` が支払いを済ませたので、次のコマンドを実行してブドウ1個とメロン1個を注文します。 + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +{ + "order_id": "ecd68f46-e248-4f2e-b581-620e9019bf5b" +} +``` + +## 参照 + +.NET API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [ScalarDB Cluster .NET Client SDK 概要](../scalardb-cluster-dotnet-client-sdk/index.mdx) +- [ScalarDB Cluster .NET Client SDK での LINQ をはじめよう](../scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx new file mode 100644 index 00000000..4bb1053f --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx @@ -0,0 +1,272 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、Spring Data JDBC for ScalarDB を介して ScalarDB Cluster SQL を使用してサンプルアプリケーションを作成する方法について説明します。 + +## このサンプルアプリケーションの前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx) の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../requirements.mdx)を参照してください。 + +::: + +## サンプルアプリケーション + +このチュートリアルでは、Spring Data JDBC for ScalarDB を使用して、クレジットラインでアイテムを注文して支払うことができるサンプル電子商取引アプリケーションを作成するプロセスについて説明します。 + +次の図は、サンプルアプリケーションのシステムアーキテクチャを示しています。 + +``` + +------------------------------------------------------------------------------------------------------------------------------+ + | [Kubernetes クラスター] | + | | + | [ポッド] [ポッド] [ポッド] | + +------------------------+ | | + | SQL CLI | | +-------+ +------------------------+ | + | (間接クライアントモード) | --+ | +---> | Envoy | ---+ +---> | ScalarDB Cluster ノード | ---+ | + +------------------------+ | | | +-------+ | | +------------------------+ | | + | | | | | | | + | | +---------+ | +-------+ | +--------------------+ | +-----------------------+ | +------------+ | + +--+-> | サービス | ---+---> | Envoy | ---+---> | サービス | ---+---> | ScalarDB Cluster ノード | ---+---> | PostgreSQL | | + +------------------------+ | | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | +-----------------------+ | +------------+ | + | Spring Data JDBC for | | | +---------+ | | +--------------------+ | | | + | ScalarDB の | | | | +-------+ | | +------------------------+ | | + | サンプルアプリケーション | --+ | +---> | Envoy | ---+ +---> | ScalarDB Cluster ノード | ---+ | + | (間接クライアントモード) | | +-------+ +-----------------------+ | + +------------------------+ | | + +------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ステップ 1. ScalarDB サンプルリポジトリをクローンする + +```console +git clone https://github.com/scalar-labs/scalardb-samples.git +cd scalardb-samples/spring-data-sample +``` + +## ステップ 2. `scalardb-sql.properties` を変更する + +ScalarDB Cluster に接続するには、`scalardb-sql.properties` も変更する必要があります。ただし、その前に、次のように Envoy (`scalardb-cluster-envoy`) のサービスリソースの `EXTERNAL-IP` アドレスを取得する必要があります。 + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +次に、`scalardb-sql.properties` を開きます。 + +```console +vim scalardb-sql.properties +``` + +次に、`scalardb-sql.properties` を次のように変更します。 + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost +``` + +ScalarDB Cluster に接続するには、`scalar.db.sql.connection_mode` プロパティに `cluster` を指定する必要があります。 + +また、このチュートリアルでは `indirect` クライアントモードを使用して Envoy のサービスリソースに接続します。 + +クライアントモードの詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx)を参照してください。 + +## ステップ 3. スキーマをロードする + +スキーマをロードするには、[SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli) を使用する必要があります。SQL CLI は [ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドを実行して Cluster 用の SQL CLI を使用できます。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-sql.properties --file schema.sql +``` + +## ステップ 4.`application.properties`を変更する + +次に、ScalarDB Cluster に接続するために `application.properties` も変更する必要があります。 + +```console +vim src/main/resources/application.properties +``` + +`scalardb-sql.properties` と同様に、`scalar.db.sql.connection_mode` プロパティに `cluster` を指定し、`indirect` クライアントモードを使用する必要があります。そのためには、`application.properties` を次のように変更します。 + +```properties +spring.datasource.driver-class-name=com.scalar.db.sql.jdbc.SqlJdbcDriver +spring.datasource.url=jdbc:scalardb:\ +?scalar.db.sql.connection_mode=cluster\ +&scalar.db.sql.cluster_mode.contact_points=indirect:localhost\ +&scalar.db.consensus_commit.isolation_level=SERIALIZABLE\ +&scalar.db.sql.default_namespace_name=sample +``` + +## ステップ 5. 初期データをロードする + +サンプルアプリケーションを実行する前に、次のコマンドを実行して初期データをロードする必要があります。 + +```console +./gradlew run --args="LoadInitialData" +``` + +初期データがロードされた後、次のレコードがテーブルに保存される必要があります。 + +- `sample.customers` テーブルの場合: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +- `sample.items` テーブルの場合: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## ステップ 6. サンプルアプリケーションを実行する + +まず、ID が `1` である顧客に関する情報を取得します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":0} +... +``` + +次に、顧客 ID `1` を使用して、リンゴ3個とオレンジ2個を注文します。注文形式は `:,:,...` であることに注意してください。 + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +... +{"order_id":"2358ab35-5819-4f8f-acb1-12e73d97d34e","customer_id":1,"timestamp":1677478005400} +... +``` + +このコマンドを実行すると、注文 ID が表示されます。 + +注文 ID を使用して注文の詳細を確認してみましょう。 + +```console +./gradlew run --args="GetOrder 2358ab35-5819-4f8f-acb1-12e73d97d34e" +... +{"order_id":"2358ab35-5819-4f8f-acb1-12e73d97d34e","timestamp":1677478005400,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":1,"item_name":"Apple","price":1000,"count":3,"total":3000},{"item_id":2,"item_name":"Orange","price":2000,"count":2,"total":4000}],"total":7000} +... +``` + +次に、別の注文を出して、顧客 ID `1` の注文履歴を取得しましょう。 + +```console +./gradlew run --args="PlaceOrder 1 5:1" +... +{"order_id":"46062b16-b71b-46f9-a9ff-dc6b0991259b","customer_id":1,"timestamp":1677478201428} +... +./gradlew run --args="GetOrders 1" +... +[{"order_id":"46062b16-b71b-46f9-a9ff-dc6b0991259b","timestamp":1677478201428,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":5,"item_name":"Melon","price":3000,"count":1,"total":3000}],"total":3000},{"order_id":"2358ab35-5819-4f8f-acb1-12e73d97d34e","timestamp":1677478005400,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":1,"item_name":"Apple","price":1000,"count":3,"total":3000},{"item_id":2,"item_name":"Orange","price":2000,"count":2,"total":4000}],"total":7000}] +... +``` + +この注文履歴は、タイムスタンプの降順で表示されます。 + +顧客の現在の `credit_total` は `10000` です。顧客は、情報を取得したときに表示された `credit_limit` に達したため、これ以上注文することはできません。 + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +java.lang.RuntimeException: Credit limit exceeded. limit:10000, total:17500 + at sample.SampleService.placeOrder(SampleService.java:102) + at sample.SampleService$$FastClassBySpringCGLIB$$1123c447.invoke() + at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793) + at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) + at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) + at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) + at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) + at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) + at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708) + at sample.SampleService$$EnhancerBySpringCGLIB$$a94e1d9.placeOrder() + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:37) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:13) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.SampleApp.run(SampleApp.java:26) + at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:768) + at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:752) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) + at sample.SampleApp.main(SampleApp.java:35) +... +``` + +支払いが完了すると、顧客は再度注文できるようになります。 + +```console +./gradlew run --args="Repayment 1 8000" +... +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":2000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +{"order_id":"0350947a-9003-46f2-870e-6aa4b2df0f1f","customer_id":1,"timestamp":1677478728134} +... +``` + +## サンプルアプリケーションのソースコード + +Spring Data JDBC for ScalarDB の詳細については、[サンプルアプリケーションのソースコード](https://github.com/scalar-labs/scalardb-samples/tree/main/spring-data-sample/src/main)を確認してください。 + +## 参照 + +その他の ScalarDB Cluster チュートリアルについては、以下を参照してください。 + +- [ScalarDB Cluster をはじめよう](getting-started-with-scalardb-cluster.mdx) +- [ScalarDB Cluster GraphQL をはじめよう](getting-started-with-scalardb-cluster-graphql.mdx) +- [JDBC 経由の ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [ScalarDB Cluster での Go をはじめよう](getting-started-with-using-go-for-scalardb-cluster.mdx) +- [ScalarDB Cluster での Python をはじめよう](getting-started-with-using-python-for-scalardb-cluster.mdx) + +Java API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster.mdx new file mode 100644 index 00000000..9471668e --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster.mdx @@ -0,0 +1,409 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、Java API を通じて [ScalarDB Cluster](./index.mdx) を使用するサンプルアプリケーションを作成する方法について説明します。 + +## 概要 + +このチュートリアルでは、ScalarDB を使用して商品を注文し、信用枠で支払いを行うことができるサンプルの電子商取引アプリケーションを作成するプロセスについて説明します。 + +:::note + +サンプルアプリケーションの焦点は ScalarDB の使用方法を示すことにあるため、アプリケーション固有のエラー処理、認証処理、および同様の機能はサンプルアプリケーションには含まれていません。ScalarDB での例外処理の詳細については、[例外の処理](../api-guide.mdx#例外の処理)を参照してください。 + +::: + +次の図は、サンプルアプリケーションのシステムアーキテクチャを示しています。 + +```mermaid +stateDiagram-v2 + state "Schema Loader
(間接クライアントモード)" as SL + state "Java API を使用したサンプルアプリケーション
(間接クライアントモード)" as SA + state "Kubernetes クラスタ" as KC + state "サービス (Envoy)" as SE + state "ポッド" as P1 + state "ポッド" as P2 + state "ポッド" as P3 + state "Envoy" as E1 + state "Envoy" as E2 + state "Envoy" as E3 + state "サービス (ScalarDB Cluster)" as SSC + state "ScalarDB Cluster" as SC1 + state "ScalarDB Cluster" as SC2 + state "ScalarDB Cluster" as SC3 + state "PostgreSQL" as PSQL + SL --> SE + SA --> SE + state KC { + SE --> E1 + SE --> E2 + SE --> E3 + state P1 { + E1 --> SSC + E2 --> SSC + E3 --> SSC + } + SSC --> SC1 + SSC --> SC2 + SSC --> SC3 + state P2 { + SC1 --> PSQL + SC1 --> SC2 + SC1 --> SC3 + SC2 --> PSQL + SC2 --> SC1 + SC2 --> SC3 + SC3 --> PSQL + SC3 --> SC1 + SC3 --> SC2 + } + state P3 { + PSQL + } + } +``` + +### このサンプルアプリケーションで実行できること + +サンプルアプリケーションは、次の種類のトランザクションをサポートしています: + +- 顧客情報を取得します。 +- 信用枠を使用して注文を行います。 + - 注文のコストが顧客の信用限度額を下回っているかどうかを確認します。 + - チェックが成功した場合は、注文履歴を記録し、顧客が支払った金額を更新します。 +- 注文 ID で注文情報を取得します。 +- 顧客 ID で注文情報を取得します。 +- 支払いを行います。 + - 顧客が支払った金額を減らします。 + +## このサンプルアプリケーションの前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx) の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../requirements.mdx)を参照してください。 + +::: + +## ScalarDB Cluster のセットアップ + +次のセクションでは、サンプルの電子商取引アプリケーションをセットアップする方法について説明します。 + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、サンプルアプリケーションが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-sample +``` + +### `build.gradle` を変更する + +ScalarDB Cluster を使用するには、任意のテキストエディターで `build.gradle` を開きます。次に、`dependencies` セクションから `com.scalar-labs:scalardb` の既存の依存関係を削除し、`dependencies` セクションに次の依存関係を追加します。 + +```gradle +dependencies { + ... + + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' +} +``` + +### `database.properties` を変更する + +ScalarDB Cluster に接続するには、`database.properties` も変更する必要があります。ただし、その前に、Envoy サービスリソース (`scalardb-cluster-envoy`) の `EXTERNAL-IP` アドレスを取得する必要があります。サービスリソースを取得するには、次のコマンドを実行します。 + +```console +kubectl get svc scalardb-cluster-envoy +``` + +`CLUSTER-IP`、`PORT(S)`、`AGE` の値がそれぞれ異なる、以下のような出力が表示されます。 + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +`database.properties` では、`scalar.db.transaction_manager` プロパティに `cluster` を指定し、`scalar.db.contact_points` が Envoy サービスリソースに接続するためのクライアントモードとして `indirect` を使用する必要があります。 + +次のコマンドを実行して `database.properties` を開きます。 + +```console +vim database.properties +``` + +次に、`database.properties` を次のように変更します。 + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:localhost +``` + +:::note + +クライアントモードの詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +::: + +### スキーマをロードする + +サンプルアプリケーションのデータベーススキーマ (データを整理する方法) は、[`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sample/schema.json) ですでに定義されています。 + +スキーマを適用するには、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4)に移動し、ScalarDB Cluster Schema Loader を `scalardb-samples/scalardb-sample` フォルダーにダウンロードします。 + +次に、次のコマンドを実行します。 + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +``` + +#### スキーマの詳細 + +サンプルアプリケーションの [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sample/schema.json) に示されているように、すべてのテーブルは `sample` 名前空間に作成されます。 + +- `sample.customers`: 顧客情報を管理するテーブル + - `credit_limit`: 貸し手が顧客に信用枠から支出を許可する最大金額 + - `credit_total`: 顧客が信用枠から支出した金額 +- `sample.orders`: 注文情報を管理するテーブル +- `sample.statements`: 注文明細情報を管理するテーブル +- `sample.items`: 注文するアイテムの情報を管理するテーブル + +スキーマのエンティティ関係図は次のとおりです。 + +![ERD](images/getting-started-ERD.png) + +### 初期データをロードする + +サンプルアプリケーションを実行する前に、次のコマンドを実行して初期データをロードする必要があります。 + +```console +./gradlew run --args="LoadInitialData" +``` + +初期データがロードされたら、次のレコードがテーブルに保存されます。 + +**`sample.customers` テーブル** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` テーブル** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションでトランザクションを実行し、データを取得する + +次のセクションでは、サンプル電子商取引アプリケーションでトランザクションを実行し、データを取得する方法について説明します。 + +### 顧客情報を取得する + +次のコマンドを実行して、ID が `1` である顧客に関する情報を取得することから始めます。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 0} +... +``` + +### 注文する + +次に、次のコマンドを実行して、顧客 ID `1` にリンゴ3個とオレンジ2個を注文してもらいます。 + +:::note + +このコマンドの注文形式は `./gradlew run --args="PlaceOrder :,:,..."` です。 + +::: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +... +{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e"} +... +``` + +### 注文の詳細を確認する + +次のコマンドを実行して注文の詳細を確認します。`` は、前のコマンドを実行した後に表示される `order_id` の UUID に置き換えます。 + +```console +./gradlew run --args="GetOrder " +``` + +`order_id` と `timestamp` の UUID が異なる、以下のような出力が表示されます。 + +```console +... +{"order": {"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +### 別の注文をする + +次のコマンドを実行して、顧客 ID `1` の `credit_total` の残額を使用してメロン1個を注文します。 + +```console +./gradlew run --args="PlaceOrder 1 5:1" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +... +{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d"} +... +``` + +### 注文履歴を確認する + +次のコマンドを実行して、顧客 ID `1` のすべての注文履歴を取得します。 + +```console +./gradlew run --args="GetOrders 1" +``` + +`order_id` と `timestamp` の UUID が異なる以下のような出力が表示されます。これは、顧客 ID `1` のすべての注文履歴をタイムスタンプの降順で表示します。 + +```console +... +{"order": [{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000},{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d","timestamp": 1650948412766,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000}]} +... +``` + +### クレジット合計の確認 + +次のコマンドを実行して、顧客 ID `1` のクレジット合計を取得します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。これは、顧客 ID `1` が `credit_total` の `credit_limit` に達しており、これ以上注文できないことを示しています。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +``` + +次のコマンドを実行して、ブドウ1個とマンゴー1個を注文してみます。 + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +次の出力が表示されます。これは、`credit_total` 金額が `credit_limit` 金額を超えたために注文が失敗したことを示しています。 + +```console +... +java.lang.RuntimeException: Credit limit exceeded + at sample.Sample.placeOrder(Sample.java:205) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:33) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:8) + at picocli.CommandLine.executeUserObject(CommandLine.java:1783) + at picocli.CommandLine.access$900(CommandLine.java:145) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2141) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2108) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:1975) + at picocli.CommandLine.execute(CommandLine.java:1904) + at sample.command.SampleCommand.main(SampleCommand.java:35) +... +``` + +### 支払いを行う + +注文を続行するには、顧客 ID `1` が支払いを行って `credit_total` の金額を減らす必要があります。 + +次のコマンドを実行して支払いを行います。 + +```console +./gradlew run --args="Repayment 1 8000" +``` + +次に、次のコマンドを実行して、顧客 ID `1` の `credit_total` 金額を確認します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。これは、顧客 ID `1` に支払いが適用され、`credit_total` の金額が減ったことを示しています。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 2000} +... +``` + +顧客 ID `1` が支払いを済ませたので、次のコマンドを実行してブドウ1個とメロン1個を注文します。 + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す類似の出力が表示されます。 + +```console +... +{"order_id": "8911cab3-1c2b-4322-9386-adb1c024e078"} +... +``` + +## 参照 + +その他の ScalarDB Cluster チュートリアルについては、以下を参照してください。 + +- [ScalarDB Cluster GraphQL をはじめよう](getting-started-with-scalardb-cluster-graphql.mdx) +- [JDBC 経由の ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [ScalarDB Cluster での Go をはじめよう](getting-started-with-using-go-for-scalardb-cluster.mdx) +- [ScalarDB Cluster での Python をはじめよう](getting-started-with-using-python-for-scalardb-cluster.mdx) + +Java API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx new file mode 100644 index 00000000..75267990 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx @@ -0,0 +1,444 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster での Go をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; + + + +このドキュメントでは、Go を使用して ScalarDB Cluster の gRPC クライアントコードを記述する方法について説明します。 + +## 前提条件 + +- [Go](https://go.dev/dl/) (最新の3つのメジャーリリースのいずれか) +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx)の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + + + +## サンプルアプリケーション + +このチュートリアルでは、口座間で送金できる電子マネーアプリケーションを作成するプロセスについて説明します。 + +## ステップ 1. `schema.json` を作成する + +以下は簡単なサンプルスキーマです。 + +`schema.json` を作成し、ファイルに次の内容を追加します。 + +```json +{ + "emoney.account": { + "transaction": true, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } +} +``` + +## ステップ 2. `database.properties` を作成する + +ScalarDB Cluster の Schema Loader 用に `database.properties` を作成する必要があります。ただし、まず `LoadBalancer` サービス (`scalardb-cluster-envoy`) のサービスリソースの `EXTERNAL-IP` アドレスを取得する必要があります。 + +`EXTERNAL-IP` アドレスを確認するには、次のコマンドを実行します。 + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +次に、`database.properties` を作成し、ファイルに次の内容を追加します。 + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:localhost +``` + +ScalarDB Cluster に接続するには、`scalar.db.transaction_manager` プロパティに `cluster` を指定する必要があります。また、このチュートリアルでは `indirect` クライアントモードを使用して Envoy のサービスリソースに接続します。クライアントモードの詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx)を参照してください。 + +## ステップ 3. スキーマをロードする + +ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Schema Loader for Cluster は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Schema Loader for Cluster を実行できます。 + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +``` + +## ステップ 4. Go 環境をセットアップする + +gRPC クイックスタートドキュメントの [Prerequisites](https://grpc.io/docs/languages/go/quickstart/#prerequisites) セクションに従って、次のコンポーネントをインストールします。 + +- Go +- プロトコルバッファコンパイラ、`protoc`、バージョン3.15以降 +- プロトコルコンパイラ用の Go プラグイン + +## ステップ 5. ScalarDB Cluster gRPC のスタブコードを生成する + +ScalarDB Cluster の gRPC サーバーと通信するには、proto ファイルからスタブコードを生成する必要があります。 + +まず、新しい作業ディレクトリに、次のコマンドを実行して、gRPC コードの生成に使用する `scalardb-cluster` という名前のディレクトリを作成します。 + +```console +mkdir scalardb-cluster +``` + +次に、`scalardb-cluster.proto` ファイルをダウンロードし、作成したディレクトリに保存します。商用ライセンスをお持ちの ScalarDB Cluster ユーザーで、`scalardb-cluster.proto` ファイルが必要な場合は、[お問い合わせ](https://www.scalar-labs.com/support)ください。 + +次のコマンドを実行して gRPC コードを生成します。 + +```console +protoc --go_out=. --go_opt=paths=source_relative \ + --go_opt=Mscalardb-cluster/scalardb-cluster.proto=example.com/scalardb-cluster \ + --go-grpc_out=. --go-grpc_opt=paths=source_relative \ + --go-grpc_opt=Mscalardb-cluster/scalardb-cluster.proto=example.com/scalardb-cluster \ + scalardb-cluster/scalardb-cluster.proto +``` + +コマンドを実行すると、`scalardb-cluster` サブディレクトリに `scalardb-cluster.pb.go` と `scalardb-cluster_grpc.pb.go` という2つのファイルが表示されます。 + +## ステップ 6. サンプルアプリケーションの作成 + +以下は、gRPC コードを使用するプログラムです。これを作業ディレクトリに `main.go` として保存します。このプログラムは、[ScalarDB をはじめよう](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb/)の `ElectronicMoney.java` プログラムと同じことを行います。環境内の ScalarDB Cluster `LoadBalancer` サービスの `EXTERNAL-IP` 値に基づいて `SERVER_ADDRESS` の値を更新する必要があることに注意してください。 + +```go +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log" + "os" + "time" + + pb "emoney/scalardb-cluster" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +const ( + SERVER_ADDRESS = "localhost:60053" + NAMESPACE = "emoney" + TABLENAME = "account" + ID = "id" + BALANCE = "balance" +) + +var requestHeader = pb.RequestHeader{HopLimit: 10} + +type TxFn func(ctx context.Context, client pb.DistributedTransactionClient, transactionId string) error + +func withTransaction(fn TxFn) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + // Set up a connection to the server. + conn, err := grpc.Dial(SERVER_ADDRESS, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return err + } + defer conn.Close() + + client := pb.NewDistributedTransactionClient(conn) + + // Begin a transaction + beginResponse, err := client.Begin(ctx, &pb.BeginRequest{RequestHeader: &requestHeader}) + if err != nil { + return err + } + transactionId := beginResponse.TransactionId + + // Execute the function + err = fn(ctx, client, transactionId) + if err != nil { + // Rollback the transaction if there is an error + client.Rollback(ctx, &pb.RollbackRequest{TransactionId: transactionId}) + return err + } + + // Commit the transaction + _, err = client.Commit(ctx, &pb.CommitRequest{RequestHeader: &requestHeader, TransactionId: transactionId}) + return err +} + +func charge(ctx context.Context, client pb.DistributedTransactionClient, transactionId string, id string, amount int) error { + partitionKey := pb.Key{Columns: []*pb.Column{{Name: ID, Value: &pb.Column_TextValue_{TextValue: &pb.Column_TextValue{Value: &id}}}}} + + // Retrieve the current balance for id + get := pb.Get{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &partitionKey, ClusteringKey: nil, + GetType: pb.Get_GET_TYPE_GET, + } + getResponse, err := client.Get(ctx, &pb.GetRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Get: &get}) + if err != nil { + return err + } + + // Calculate the balance + balance := int32(amount) + if result := getResponse.GetResult(); result != nil { + for _, column := range result.GetColumns() { + if column.Name == BALANCE { + balance += column.GetIntValue().GetValue() + break + } + } + } + + // Update the balance + put := pb.Put{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &partitionKey, ClusteringKey: nil, + Columns: []*pb.Column{ + {Name: BALANCE, Value: &pb.Column_IntValue_{IntValue: &pb.Column_IntValue{Value: &balance}}}, + }, + } + _, err = client.Put(ctx, &pb.PutRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Puts: []*pb.Put{&put}}) + return err +} + +func pay(ctx context.Context, client pb.DistributedTransactionClient, transactionId string, fromId string, toId string, amount int) error { + fromPartitionKey := pb.Key{Columns: []*pb.Column{{Name: ID, Value: &pb.Column_TextValue_{TextValue: &pb.Column_TextValue{Value: &fromId}}}}} + toPartitionKey := pb.Key{Columns: []*pb.Column{{Name: ID, Value: &pb.Column_TextValue_{TextValue: &pb.Column_TextValue{Value: &toId}}}}} + + // Retrieve the current balances for ids + fromGet := pb.Get{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &fromPartitionKey, ClusteringKey: nil, + GetType: pb.Get_GET_TYPE_GET, + } + fromGetResponse, err := client.Get(ctx, &pb.GetRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Get: &fromGet}) + if err != nil { + return err + } + toGet := pb.Get{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &toPartitionKey, ClusteringKey: nil, + GetType: pb.Get_GET_TYPE_GET, + } + toGetResponse, err := client.Get(ctx, &pb.GetRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Get: &toGet}) + if err != nil { + return err + } + + // Calculate the balances (it assumes that both accounts exist) + var ( + fromBalance int32 + toBalance int32 + ) + for _, column := range fromGetResponse.GetResult().GetColumns() { + if column.Name == BALANCE { + fromBalance = column.GetIntValue().GetValue() + break + } + } + for _, column := range toGetResponse.GetResult().GetColumns() { + if column.Name == BALANCE { + toBalance = column.GetIntValue().GetValue() + break + } + } + newFromBalance := fromBalance - int32(amount) + newToBalance := toBalance + int32(amount) + + if newFromBalance < 0 { + return errors.New(fromId + " doesn't have enough balance.") + } + + // Update the balances + fromPut := pb.Put{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &fromPartitionKey, ClusteringKey: nil, + Columns: []*pb.Column{ + {Name: BALANCE, Value: &pb.Column_IntValue_{IntValue: &pb.Column_IntValue{Value: &newFromBalance}}}, + }, + } + toPut := pb.Put{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &toPartitionKey, ClusteringKey: nil, + Columns: []*pb.Column{ + {Name: BALANCE, Value: &pb.Column_IntValue_{IntValue: &pb.Column_IntValue{Value: &newToBalance}}}, + }, + } + _, err = client.Put(ctx, &pb.PutRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Puts: []*pb.Put{&fromPut, &toPut}}) + return err +} + +func getBalance(ctx context.Context, client pb.DistributedTransactionClient, transactionId string, id string) (int, error) { + // Retrieve the current balance for id + get := pb.Get{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &pb.Key{Columns: []*pb.Column{{Name: ID, Value: &pb.Column_TextValue_{TextValue: &pb.Column_TextValue{Value: &id}}}}}, + ClusteringKey: nil, + GetType: pb.Get_GET_TYPE_GET, + } + getResponse, err := client.Get(ctx, &pb.GetRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Get: &get}) + if err != nil { + return 0, err + } + if getResponse.GetResult() == nil || len(getResponse.GetResult().GetColumns()) == 0 { + return 0, errors.New("Account " + id + " doesn't exist.") + } + + var balance int + for _, column := range getResponse.GetResult().GetColumns() { + if column.Name == BALANCE { + balance = int(column.GetIntValue().GetValue()) + break + } + } + return balance, nil +} + +func main() { + var ( + action = flag.String("action", "", "Action to perform: charge / pay / getBalance") + fromId = flag.String("from", "", "From account (needed for pay)") + toId = flag.String("to", "", "To account (needed for charge and pay)") + id = flag.String("id", "", "Account id (needed for getBalance)") + ) + var amount int + flag.IntVar(&amount, "amount", 0, "Amount to transfer (needed for charge and pay)") + flag.Parse() + + if *action == "charge" { + if *toId == "" || amount < 0 { + printUsageAndExit() + } + err := withTransaction(func(ctx context.Context, client pb.DistributedTransactionClient, txId string) error { + return charge(ctx, client, txId, *toId, amount) + }) + if err != nil { + log.Fatalf("error: %v", err) + } + } else if *action == "pay" { + if *toId == "" || *fromId == "" || amount < 0 { + printUsageAndExit() + } + err := withTransaction(func(ctx context.Context, client pb.DistributedTransactionClient, txId string) error { + return pay(ctx, client, txId, *fromId, *toId, amount) + }) + if err != nil { + log.Fatalf("error: %v", err) + } + } else if *action == "getBalance" { + if *id == "" { + printUsageAndExit() + } + var balance int + err := withTransaction(func(ctx context.Context, client pb.DistributedTransactionClient, txId string) error { + var err error + balance, err = getBalance(ctx, client, txId, *id) + return err + }) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Println(balance) + } else { + fmt.Fprintln(os.Stderr, "Unknown action "+*action) + printUsageAndExit() + } +} + +func printUsageAndExit() { + flag.Usage() + os.Exit(1) +} +``` + +`main.go` ファイルを作成した後、次のコマンドを実行して `go.mod` ファイルを作成する必要があります。 + +```console +go mod init emoney +go mod tidy +``` + +これで、ディレクトリ構造は次のようになります。 + +```text +. +├── go.mod +├── go.sum +├── main.go +└── scalardb-cluster + ├── scalardb-cluster.pb.go + ├── scalardb-cluster.proto + └── scalardb-cluster_grpc.pb.go +``` + +その後、次のようにプログラムを実行できます: + +- `user1` に `1000` を請求します: + + ```console + go run main.go -action charge -amount 1000 -to user1 + ``` + +- `merchant1` に `0` を請求します (`merchant1` のアカウントを作成するだけです): + + ```console + go run main.go -action charge -amount 0 -to merchant1 + ``` + +- `user1` から `merchant1` に `100` を支払います: + + ```console + go run main.go -action pay -amount 100 -from user1 -to merchant1 + ``` + +- `user1` の残高を取得します。 + + ```console + go run main.go -action getBalance -id user1 + ``` + +- `merchant1` の残高を取得します。 + + ```console + go run main.go -action getBalance -id merchant1 + ``` + +`go build` を使用してバイナリを取得してから実行することもできます。 + +```console +go build +./emoney -action getBalance -id user1 +``` + +## 参照 + +その他の ScalarDB Cluster チュートリアルについては、以下を参照してください。 + +- [ScalarDB Cluster をはじめよう](getting-started-with-scalardb-cluster.mdx) +- [ScalarDB Cluster GraphQL をはじめよう](getting-started-with-scalardb-cluster-graphql.mdx) +- [JDBC 経由の ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [ScalarDB Cluster での Python をはじめよう](getting-started-with-using-python-for-scalardb-cluster.mdx) + +Java API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx new file mode 100644 index 00000000..9d5bec16 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx @@ -0,0 +1,487 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster での Python をはじめよう + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; + + + +このドキュメントでは、Python を使用して ScalarDB Cluster の gRPC クライアントコードを記述する方法について説明します。 + +## 前提条件 + +- [Python](https://www.python.org/downloads) 3.7以降 +- Kubernetes クラスターで実行されている ScalarDB Cluster + - [ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx)の手順に従ってデプロイした Kubernetes クラスターで ScalarDB Cluster が実行されていることを前提としています。 + + + +## サンプルアプリケーション + +このチュートリアルでは、口座間で送金できる電子マネーアプリケーションを作成するプロセスについて説明します。 + +## ステップ 1. `schema.json` を作成する + +以下は簡単なサンプルスキーマです。 + +`schema.json` を作成し、ファイルに次の内容を追加します。 + +```json +{ + "emoney.account": { + "transaction": true, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } +} +``` + +## ステップ 2. `database.properties` を作成する + +ScalarDB Cluster の Schema Loader 用に `database.properties` を作成する必要があります。ただし、まず `LoadBalancer` サービス (`scalardb-cluster-envoy`) のサービスリソースの `EXTERNAL-IP` アドレスを取得する必要があります。 + +`EXTERNAL-IP` アドレスを確認するには、次のコマンドを実行します。 + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +この場合、`EXTERNAL-IP` アドレスは `localhost` です。 + +次に、`database.properties` を作成し、ファイルに次の内容を追加します。 + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:localhost +``` + +ScalarDB Cluster に接続するには、`scalar.db.transaction_manager` プロパティに `cluster` を指定する必要があります。また、このチュートリアルでは `indirect` クライアントモードを使用して Envoy のサービスリソースに接続します。クライアントモードの詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx)を参照してください。 + +## ステップ 3. スキーマをロードする + +ScalarDB Cluster 経由でスキーマをロードするには、専用の ScalarDB Cluster 用 Schema Loader (Schema Loader for Cluster) を使用する必要があります。Schema Loader for Cluster の使用方法は、JAR ファイルの名前が異なることを除いて、[Schema Loader for ScalarDB](../schema-loader.mdx) の使用方法と基本的に同じです。Schema Loader for Cluster は、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4)からダウンロードできます。JAR ファイルをダウンロードしたら、次のコマンドで Schema Loader for Cluster を実行できます。 + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +``` + +## ステップ 4. Python 環境をセットアップする + +Python 環境の管理方法は自由に選択できます。このガイドでは、Python アプリケーションが `venv` を使用して環境で実行されていることを前提としています。 + +任意の場所に作業ディレクトリを作成し、そこに移動します。次に、次のコマンドを実行して `venv` をアクティブ化します。 + +```console +python3 -m venv venv +source venv/bin/activate +``` + +`pip` コマンドを使用して gRPC パッケージをインストールしましょう。 + +```console +pip install grpcio grpcio-tools +``` + +## ステップ 5. ScalarDB Cluster gRPC のスタブコードを生成する + +ScalarDB Cluster の gRPC サーバーと通信するには、proto ファイルからスタブコードを生成する必要があります。 + +まず、`scalardb-cluster.proto` ファイルをダウンロードし、作業ディレクトリに保存します。商用ライセンスをお持ちの ScalarDB Cluster ユーザーで、`scalardb-cluster.proto` ファイルが必要な場合は、[お問い合わせ](https://www.scalar-labs.com/support)ください。 + +次のコマンドを実行すると、スタブコードを生成できます。 + +```console +python -m grpc_tools.protoc -I . --python_out=. --pyi_out=. --grpc_python_out=. scalardb-cluster.proto +``` + +次のファイルが生成されます: + +- `scalardb_cluster_pb2.py` +- `scalardb_cluster_pb2.pyi` +- `scalardb_cluster_pb2_grpc.py` + +## ステップ 6. サンプルアプリケーションの作成 + +以下は、スタブコードを使用するサンプル Python アプリケーション (`electronic_money.py`) です。このプログラムは、[ScalarDB をはじめよう](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb/) の `ElectronicMoney.java` プログラムと同じことを行います。環境内の ScalarDB Cluster `LoadBalancer` サービスの `EXTERNAL-IP` 値に基づいて `SERVER_ADDRESS` の値を更新する必要があることに注意してください。 + +```python +import argparse +from typing import Optional + +import grpc + +import scalardb_cluster_pb2_grpc +from scalardb_cluster_pb2 import ( + BeginRequest, + BeginResponse, + Column, + CommitRequest, + Get, + GetRequest, + GetResponse, + Key, + Put, + PutRequest, + RequestHeader, + RollbackRequest, +) + +SERVER_ADDRESS = "localhost:60053" +NAMESPACE = "emoney" +TABLENAME = "account" +ID = "id" +BALANCE = "balance" + +request_header = RequestHeader(hop_limit=10) + + +def charge(id: str, amount: int) -> None: + with grpc.insecure_channel(SERVER_ADDRESS) as channel: + stub = scalardb_cluster_pb2_grpc.DistributedTransactionStub(channel) + + begin_response: BeginResponse = stub.Begin( + BeginRequest(request_header=request_header) + ) + + transaction_id = begin_response.transaction_id + + try: + pkey = Key( + columns=[ + Column( + name=ID, + text_value=Column.TextValue(value=id), + ) + ] + ) + + # Retrieve the current balance for id + get = Get( + namespace_name=NAMESPACE, + table_name=TABLENAME, + get_type=Get.GetType.GET_TYPE_GET, + partition_key=pkey, + ) + get_response: GetResponse = stub.Get( + GetRequest( + request_header=request_header, + transaction_id=transaction_id, + get=get, + ) + ) + + # Calculate the balance + balance = amount + if get_response.result.columns: + balance_column = next( + c for c in get_response.result.columns if c.name == BALANCE + ) + current = balance_column.int_value.value + balance += current + + # Update the balance + put = Put( + namespace_name=NAMESPACE, + table_name=TABLENAME, + partition_key=pkey, + columns=[ + Column(name=BALANCE, int_value=Column.IntValue(value=balance)) + ], + ) + stub.Put( + PutRequest( + request_header=request_header, + transaction_id=transaction_id, + puts=[put], + ) + ) + + # Commit the transaction + stub.Commit( + CommitRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + except Exception as e: + # Rollback the transaction + stub.Rollback( + RollbackRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + raise e + + +def pay(from_id: str, to_id: str, amount: int) -> None: + with grpc.insecure_channel(SERVER_ADDRESS) as channel: + stub = scalardb_cluster_pb2_grpc.DistributedTransactionStub(channel) + + begin_response: BeginResponse = stub.Begin( + BeginRequest(request_header=request_header) + ) + + transaction_id = begin_response.transaction_id + + try: + from_pkey = Key( + columns=[ + Column( + name=ID, + text_value=Column.TextValue(value=from_id), + ) + ] + ) + to_pkey = Key( + columns=[ + Column( + name=ID, + text_value=Column.TextValue(value=to_id), + ) + ] + ) + + # Retrieve the current balances for ids + from_get = Get( + namespace_name=NAMESPACE, + table_name=TABLENAME, + get_type=Get.GetType.GET_TYPE_GET, + partition_key=from_pkey, + ) + from_get_response: GetResponse = stub.Get( + GetRequest( + request_header=request_header, + transaction_id=transaction_id, + get=from_get, + ) + ) + to_get = Get( + namespace_name=NAMESPACE, + table_name=TABLENAME, + get_type=Get.GetType.GET_TYPE_GET, + partition_key=to_pkey, + ) + to_get_response: GetResponse = stub.Get( + GetRequest( + request_header=request_header, + transaction_id=transaction_id, + get=to_get, + ) + ) + + # Calculate the balances (it assumes that both accounts exist) + new_from_balance = ( + next( + c for c in from_get_response.result.columns if c.name == BALANCE + ).int_value.value + - amount + ) + new_to_balance = ( + next( + c for c in to_get_response.result.columns if c.name == BALANCE + ).int_value.value + + amount + ) + + if new_from_balance < 0: + raise RuntimeError(from_id + " doesn't have enough balance.") + + # Update the balances + from_put = Put( + namespace_name=NAMESPACE, + table_name=TABLENAME, + partition_key=from_pkey, + columns=[ + Column( + name=BALANCE, int_value=Column.IntValue(value=new_from_balance) + ) + ], + ) + to_put = Put( + namespace_name=NAMESPACE, + table_name=TABLENAME, + partition_key=to_pkey, + columns=[ + Column( + name=BALANCE, int_value=Column.IntValue(value=new_to_balance) + ) + ], + ) + stub.Put( + PutRequest( + request_header=request_header, + transaction_id=transaction_id, + puts=[from_put, to_put], + ) + ) + + # Commit the transaction (records are automatically recovered in case of failure) + stub.Commit( + CommitRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + except Exception as e: + # Rollback the transaction + stub.Rollback( + RollbackRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + raise e + + +def get_balance(id: str) -> Optional[int]: + with grpc.insecure_channel(SERVER_ADDRESS) as channel: + stub = scalardb_cluster_pb2_grpc.DistributedTransactionStub(channel) + + begin_response: BeginResponse = stub.Begin( + BeginRequest(request_header=request_header) + ) + + transaction_id = begin_response.transaction_id + + try: + # Retrieve the current balance for id + get = Get( + namespace_name=NAMESPACE, + table_name=TABLENAME, + get_type=Get.GetType.GET_TYPE_GET, + partition_key=Key( + columns=[ + Column( + name=ID, + text_value=Column.TextValue(value=id), + ) + ] + ), + ) + get_response: GetResponse = stub.Get( + GetRequest( + request_header=request_header, + transaction_id=transaction_id, + get=get, + ) + ) + + balance = None + if get_response.result.columns: + balance_column = next( + c for c in get_response.result.columns if c.name == BALANCE + ) + balance = balance_column.int_value.value + + # Commit the transaction + stub.Commit( + CommitRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + + return balance + + except Exception as e: + # Rollback the transaction + stub.Rollback( + RollbackRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + raise e + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(required=True) + + parser_charge = subparsers.add_parser("charge") + parser_charge.add_argument("-amount", type=int, required=True) + parser_charge.add_argument("-to", type=str, required=True, dest="to_id") + parser_charge.set_defaults(func=lambda args: charge(args.to_id, args.amount)) + + parser_pay = subparsers.add_parser("pay") + parser_pay.add_argument("-amount", type=int, required=True) + parser_pay.add_argument("-from", type=str, required=True, dest="from_id") + parser_pay.add_argument("-to", type=str, required=True, dest="to_id") + parser_pay.set_defaults( + func=lambda args: pay(args.from_id, args.to_id, args.amount) + ) + + parser_get_balance = subparsers.add_parser("get-balance") + parser_get_balance.add_argument("-id", type=str, required=True) + parser_get_balance.set_defaults(func=lambda args: print(get_balance(args.id))) + + args = parser.parse_args() + args.func(args) + +``` + +その後、次のようにプログラムを実行できます: + +- `user1` に `1000` を請求します: + + ```console + python electronic_money.py charge -amount 1000 -to user1 + ``` + +- `merchant1` に `0` を請求します (`merchant1` のアカウントを作成するだけです): + + ```console + python electronic_money.py charge -amount 0 -to merchant1 + ``` + +- `user1` から `merchant1` に `100` を支払います: + + ```console + python electronic_money.py pay -amount 100 -from user1 -to merchant1 + ``` + +- `user1` の残高を取得します。 + + ```console + python electronic_money.py get-balance -id user1 + ``` + +- `merchant1` の残高を取得します。 + + ```console + python electronic_money.py get-balance -id merchant1 + ``` + +## 参照 + +その他の ScalarDB Cluster チュートリアルについては、以下を参照してください。 + +- [ScalarDB Cluster をはじめよう](getting-started-with-scalardb-cluster.mdx) +- [ScalarDB Cluster GraphQL をはじめよう](getting-started-with-scalardb-cluster-graphql.mdx) +- [JDBC 経由の ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [ScalarDB Cluster での Go をはじめよう](getting-started-with-using-go-for-scalardb-cluster.mdx) + +Java API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +- [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +- [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-vector-search.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-vector-search.mdx new file mode 100644 index 00000000..c5a38590 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/getting-started-with-vector-search.mdx @@ -0,0 +1,467 @@ +--- +tags: + - Enterprise Premium + - Private Preview +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster でベクトル検索をはじめよう + +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster は、アプリケーションがベクトルストアと統一された方法で対話できるように、ベクトルストアの抽象化を提供します。このページでは、この機能の概要と、それがユーザーにとってなぜ有益であるかについて説明します。 + +## ベクトルストアの抽象化とは何ですか? + +ScalarDB Cluster は、リレーショナルデータベース、NoSQL データベース、NewSQL データベースを含むさまざまなデータベースを抽象化するのと同様に、さまざまなベクトルストアを抽象化します。このベクトルストアの抽象化を使用すると、特定のベクトルストアの実装に依存せず、移植性を確保しながら、ベクトルストアと統一された方法で対話するアプリケーションを開発できます。さらに、ベクトルストアの統合が ScalarDB Cluster に組み込まれているため、アプリケーションはそのスケーラビリティを活用できます。 + +ベクトルストアの抽象化の現在の実装は [LangChain4j](https://docs.langchain4j.dev/) を活用し、次のベクトルストアと埋め込みモデルをサポートしています。 + +ベクトルストア: +- In-memory +- OpenSearch +- Azure Cosmos DB NoSQL +- Azure AI Search +- pgvector + +埋め込みモデル: +- In-process +- Amazon Bedrock +- Azure OpenAI +- Google Vertex AI +- OpenAI + +## ベクトルストアの抽象化を使用する理由 + +生成 AI の時代において、大規模言語モデル (LLM) を導入する際に組織が直面する課題の1つは、これらのモデルが企業データを理解できるようにすることです。検索拡張生成 (RAG) は、特定の企業知識で LLM を強化するために使用される重要な手法です。たとえば、LLM を搭載したチャットボットが正確で適切な応答を提供できるようにするために、企業は RAG を使用してユーザーマニュアルやサポートドキュメントからドメイン固有の情報を統合します。 + +RAG はベクトルストアに依存しています。ベクトルストアは通常、データベースからデータを抽出し、そのデータをベクトルに変換してから、それらのベクトルをロードすることによって作成されます。ScalarDB Cluster でベクトルストアとデータベースの抽象化を使用すると、プロセス全体をシームレスに実装できます。このアプローチにより、ワークフローとコードが大幅に簡素化され、特定のベクトルストアとデータベースに依存する複雑なアプリケーションを作成する必要がなくなります。 + +## チュートリアル + +このチュートリアルでは、ScalarDB Cluster でベクトル検索を実行する方法を説明します。 + +### 前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10 以降と [Docker Compose](https://docs.docker.com/compose/install/) V2 以降 + +:::note + +このチュートリアルは Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体はさまざまなベンダーの JDK ディストリビューションでテストされています。ScalarDB の要件、互換性のある JDK ディストリビューションを含む詳細については、[要件](../requirements.mdx) を参照してください。 + +::: + + + +### 1. ScalarDB Cluster の設定ファイルを作成する + +以下の設定ファイルを `scalardb-cluster-node.properties` として作成し、`` と `` を ScalarDB ライセンスキーとライセンスチェック証明書の値に置き換えてください。ライセンスキーと証明書の詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + +```yaml +scalar.db.transaction.enabled=false + +# Enable the standalone mode +scalar.db.cluster.node.standalone_mode.enabled=true + +# Enable the embedding feature +scalar.db.embedding.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +さらに、使用する埋め込みストアと埋め込みモデルに応じて、設定ファイルにプロパティを追加する必要があります。 + +使用する埋め込みストアを選択し、それに応じた設定手順に従ってください。 + + + + インメモリ埋め込みストアは基本的なインメモリ実装です。この埋め込みストアは、迅速なプロトタイピングやシンプルなユースケースに役立ちます。 + + インメモリ埋め込みストアを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.store.type=in-memory + ``` + + + OpenSearch 埋め込みストアは、バックエンドとして OpenSearch を使用する埋め込みストアです。 + + OpenSearch の実装がローカルで実行されているか、AWS で実行されているかを選択し、それに応じた設定手順に従ってください。 + + + + ネットワーク上で到達可能なローカルで実行されている OpenSearch クラスターの場合、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.store.type=opensearch + + # OpenSearch Server URL. + scalar.db.embedding.store.opensearch.server_url= + + # OpenSearch API key (optional). + scalar.db.embedding.store.opensearch.api_key= + + # OpenSearch username (optional). + scalar.db.embedding.store.opensearch.user_name= + + # OpenSearch password (optional). + scalar.db.embedding.store.opensearch.password= + + # OpenSearch index name. + scalar.db.embedding.store.opensearch.index_name= + ``` + + + AWS でフルマネージドサービスとして実行されている OpenSearch クラスターの場合、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.store.type=opensearch + + # OpenSearch Server URL. + scalar.db.embedding.store.opensearch.server_url= + + # The AWS signing service name, one of `es` (Amazon OpenSearch) or `aoss` (Amazon OpenSearch Serverless). + scalar.db.embedding.store.opensearch.service_name= + + # The AWS region for which requests will be signed. This should typically match the region in `server_url`. + scalar.db.embedding.store.opensearch.region= + + # The AWS access key ID. + scalar.db.embedding.store.opensearch.access_key_id= + + # The AWS secret access key. + scalar.db.embedding.store.opensearch.secret_access_key= + + # OpenSearch index name. + scalar.db.embedding.store.opensearch.index_name= + ``` + + + + + Azure Cosmos DB for NoSQL 埋め込みストアは、バックエンドとして Azure Cosmos DB を使用する埋め込みストアです。 + + Azure Cosmos DB for NoSQL 埋め込みストアを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.store.type=azure-cosmos-nosql + + # The Azure Cosmos DB endpoint that the SDK will connect to. + scalar.db.embedding.store.azure-cosmos-nosql.endpoint= + + # A master key used to perform authentication for accessing resources. A read-only key can also be used only for read-only operations. + scalar.db.embedding.store.azure-cosmos-nosql.key= + + # The database name to be used. + scalar.db.embedding.store.azure-cosmos-nosql.database_name= + + # The container name to be used. + scalar.db.embedding.store.azure-cosmos-nosql.container_name= + ``` + + + Azure AI Search 埋め込みストアは、バックエンドとして Azure AI Search を使用する埋め込みストアです。 + + Azure AI Search 埋め込みストアを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.store.type=azure-ai-search + # The Azure AI Search endpoint. + scalar.db.embedding.store.azure-ai-search.endpoint= + + # The Azure AI Search API key. + scalar.db.embedding.store.azure-ai-search.api_key= + + # The name of the index to be used. If no index is provided, the name of the default index to be used. + scalar.db.embedding.store.azure-ai-search.index_name= + ``` + + + pgvector 埋め込みストアは、バックエンドとしてベクトル類似検索用の Postgres 拡張機能である pgvector を使用する埋め込みストアです。 + + pgvector 埋め込みストアを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.store.type=pgvector + + # The database host. + scalar.db.embedding.store.pgvector.host= + + # The database port. + scalar.db.embedding.store.pgvector.port= + + # The database user. + scalar.db.embedding.store.pgvector.user= + + # The database password. + scalar.db.embedding.store.pgvector.password= + + # The database name. + scalar.db.embedding.store.pgvector.database= + + # The table name. + scalar.db.embedding.store.pgvector.table= + ``` + + + +使用する埋め込みモデルを選択し、それに応じた設定手順に従ってください。 + + + + In-process 埋め込みモデルは、[ONNX runtime](https://onnxruntime.ai/docs/get-started/with-java.html) によって提供され、ScalarDB Cluster プロセス内で実行されるローカル埋め込みモデルです。この埋め込みモデルは、迅速なプロトタイピングやシンプルなユースケースに役立ちます。 + + In-process 埋め込みモデルを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.model.type=in-process + ``` + + + Amazon Bedrock 埋め込みモデルは、バックエンドとして Amazon Bedrock を使用する埋め込みモデルです。 + + Amazon Bedrock 埋め込みモデルを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.model.type=bedrock-titan + + # The AWS region for which requests will be signed. + scalar.db.embedding.model.bedrock-titan.region= + + # The AWS access key ID. + scalar.db.embedding.model.bedrock-titan.access_key_id= + + # The AWS secret access key. + scalar.db.embedding.model.bedrock-titan.secret_access_key= + + # The model. Either `amazon.titan-embed-text-v1` or `amazon.titan-embed-text-v2:0`. + scalar.db.embedding.model.bedrock-titan.model= + + # The dimensions. + scalar.db.embedding.model.bedrock-titan.dimensions= + ``` + + + Azure OpenAI 埋め込みモデルは、バックエンドとして Azure OpenAI を使用する埋め込みモデルです。 + + Azure OpenAI 埋め込みモデルを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.model.type=azure-open-ai + + # The Azure OpenAI endpoint. + scalar.db.embedding.model.azure-open-ai.endpoint= + + # The Azure OpenAI API key. + scalar.db.embedding.model.azure-open-ai.api_key= + + # The deployment name in Azure OpenAI. + scalar.db.embedding.model.azure-open-ai.deployment_name= + + # The dimensions. + scalar.db.embedding.model.azure-open-ai.dimensions= + ``` + + + Google Vertex AI 埋め込みモデルは、バックエンドとして Google Vertex AI を使用する埋め込みモデルです。 + + Google Vertex AI 埋め込みモデルを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.model.type=vertex-ai + + # The Google Cloud project. + scalar.db.embedding.model.vertex-ai.project= + + # The Google Cloud location. + scalar.db.embedding.model.vertex-ai.location= + + # The endpoint. + scalar.db.embedding.model.vertex-ai.endpoint= + + # The publisher. + scalar.db.embedding.model.vertex-ai.publisher= + + # The model name. + scalar.db.embedding.model.vertex-ai.model_name= + + # The output dimensionality. + scalar.db.embedding.model.vertex-ai.output_dimensionality= + ``` + + + OpenAI 埋め込みモデルは、バックエンドとして OpenAI を使用する埋め込みモデルです。 + + OpenAI 埋め込みモデルを使用するには、設定ファイルに次のプロパティを追加します。 + + ```properties + scalar.db.embedding.model.type=open-ai + + # The OpenAI API key. + scalar.db.embedding.model.open-ai.api_key= + + # The model name. + scalar.db.embedding.model.open-ai.model_name= + + # The base URL. + scalar.db.embedding.model.open-ai.base_url= + + # The organization ID. + scalar.db.embedding.model.open-ai.organization_id= + + # The dimensions. + scalar.db.embedding.model.open-ai.dimensions= + + # The user. + scalar.db.embedding.model.open-ai.user= + ``` + + + +### 2. Docker Compose ファイルを作成する + +以下の設定ファイルを `docker-compose.yaml` として作成してください。 + +```yaml +services: + + scalardb-cluster-standalone: + container_name: "scalardb-cluster-node" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + ports: + - 60053:60053 + - 9080:9080 + volumes: + - ./scalardb-cluster-node.properties:/scalardb-cluster/node/scalardb-cluster-node.properties +``` + +### 3. ScalarDB Cluster を起動する + +以下のコマンドを実行して、スタンドアロンモードで ScalarDB Cluster を起動します。 + +```console +docker compose up -d +``` + +ScalarDB Cluster が完全に起動するまで数分かかる場合があります。 + +### 4. 埋め込みストア抽象化用の Java Client SDK をプロジェクトに追加する + +ScalarDB Cluster Embedding Java Client SDK ライブラリは [Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-cluster-embedding-java-client-sdk) で利用可能です。Gradle または Maven を使用してアプリケーションにライブラリをビルド依存関係として追加できます。 + +ビルドツールを選択し、ScalarDB Cluster Embedding Java Client SDK をアプリケーションに追加する手順に従ってください。 + + + + ScalarDB Cluster Embedding Java Client SDK のビルド依存関係を Gradle を使用して追加するには、アプリケーションの `build.gradle` に次の内容を追加します。 + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb-cluster-embedding-java-client-sdk:3.15.4' + } + ``` + + + ScalarDB Cluster Embedding Java Client SDK のビルド依存関係を Maven を使用して追加するには、アプリケーションの `pom.xml` に次の内容を追加します。 + + ```xml + + com.scalar-labs + scalardb-cluster-embedding-java-client-sdk + 3.15.4 + + ``` + + + +### 5. サンプルコードを実行する + +新しい Java クラスを作成し、以下のコードを追加してサンプルコードを実行してください。 + +```java +try (ScalarDbEmbeddingClientFactory scalarDbEmbeddingClientFactory = + ScalarDbEmbeddingClientFactory.builder() + .withProperty("scalar.db.embedding.client.contact_points", "indirect:localhost") + .build()) { + // Create an embedding store and an embedding model. + EmbeddingStore scalarDbEmbeddingStore = + scalarDbEmbeddingClientFactory.createEmbeddingStore(); + EmbeddingModel scalarDbEmbeddingModel = scalarDbEmbeddingClientFactory.createEmbeddingModel(); + + // Add embeddings to the embedding store. + TextSegment segment1 = TextSegment.from("I like football."); + Embedding embedding1 = scalarDbEmbeddingModel.embed(segment1).content(); + scalarDbEmbeddingStore.add(embedding1, segment1); + + TextSegment segment2 = TextSegment.from("The weather is good today."); + Embedding embedding2 = scalarDbEmbeddingModel.embed(segment2).content(); + scalarDbEmbeddingStore.add(embedding2, segment2); + + // Search for embeddings. + Embedding queryEmbedding = + scalarDbEmbeddingModel.embed("What is your favourite sport?").content(); + EmbeddingSearchResult result = + scalarDbEmbeddingStore.search( + EmbeddingSearchRequest.builder() + .queryEmbedding(queryEmbedding) + .maxResults(1) + .build()); + + // Print the search result. + List> matches = result.matches(); + EmbeddingMatch embeddingMatch = matches.get(0); + System.out.println(embeddingMatch.embedded().text()); + System.out.println(embeddingMatch.score()); +} +``` + +このサンプルコードは、埋め込みストアと埋め込みモデルを作成し、埋め込みを埋め込みストアに追加し、埋め込みを検索する方法を示しています。 + +コードの埋め込みストアと埋め込みモデルを作成する部分を除いて、使用方法は LangChain4j と同じです。LangChain4j の詳細については、以下を参照してください: +- [LangChain4j](https://docs.langchain4j.dev/) +- [埋め込みモデル](https://docs.langchain4j.dev/tutorials/rag#embedding-model) +- [埋め込みストア](https://docs.langchain4j.dev/tutorials/rag#embedding-store) + +#### `ScalarDbEmbeddingClientFactory` について + +コードスニペットに示されているように、`ScalarDbEmbeddingClientFactory` クラスはファクトリのインスタンスを作成するためのビルダーを提供します。ビルダーを使用すると、ファクトリのプロパティを設定できます。この例では、`withProperty()` メソッドを使用して、以下のようにファクトリの接続ポイントを設定しています: + +```java +ScalarDbEmbeddingClientFactory scalarDbEmbeddingClientFactory = ScalarDbEmbeddingClientFactory.builder() + .withProperty("scalar.db.embedding.client.contact_points", "indirect:localhost") + .build(); +``` + +また、`withPropertiesFile()` メソッドを使用してプロパティファイルを設定することもできます。 + +その後、以下のようにファクトリを使用して埋め込みストアと埋め込みモデルを作成できます: + +```java +EmbeddingStore scalarDbEmbeddingStore = + scalarDbEmbeddingClientFactory.createEmbeddingStore(); +EmbeddingModel scalarDbEmbeddingModel = scalarDbEmbeddingClientFactory.createEmbeddingModel(); +``` + +これらのクラスのメソッドは内部的に ScalarDB Cluster に接続し、設定で指定された埋め込みストアと埋め込みモデルを使用して対話します。 + +アプリケーション内でベクトルストアと対話するには、`scalarDbEmbeddingStore` と `scalarDbEmbeddingModel` のインスタンスを再利用する必要があります。 + +:::note + +`ScalarDbEmbeddingClientFactory` インスタンスは、使用後に接続を解放するために閉じる必要があります。 + +::: + +## 追加の詳細 + +ベクター検索機能は現在、プライベートプレビュー中です。詳細については、[お問い合わせ](https://www.scalar-labs.com/contact)いただくか、この機能が将来のバージョンで一般公開されるまでお待ちください。 + +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-embedding-java-client-sdk/3.15.4/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/direct-kubernetes-client-mode.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/direct-kubernetes-client-mode.png new file mode 100644 index 00000000..13df52e6 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/direct-kubernetes-client-mode.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/getting-started-ERD.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/getting-started-ERD.png new file mode 100644 index 00000000..1a6d13c5 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/getting-started-ERD.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/indirect-client-mode.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/indirect-client-mode.png new file mode 100644 index 00000000..4e96108f Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/indirect-client-mode.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/scalardb-cluster-architecture.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/scalardb-cluster-architecture.png new file mode 100644 index 00000000..24a0a50d Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/scalardb-cluster-architecture.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/scalardb-deployment-patterns.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/scalardb-deployment-patterns.png new file mode 100644 index 00000000..6098c910 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/images/scalardb-deployment-patterns.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/index.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/index.mdx new file mode 100644 index 00000000..0ebc4806 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/index.mdx @@ -0,0 +1,75 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB Cluster は、[ScalarDB](../overview.mdx) のクラスタリングソリューションであり、一連のクラスターノードで構成され、各ノードは ScalarDB 機能を提供します。各クラスターノードには、トランザクション要求をクラスター内の適切なクラスターノードに転送するルーティングメカニズムがあります。 + +## ScalarDB Cluster を使用する理由 + +マイクロサービストランザクションなど、複数のクライアント要求にまたがるトランザクションを実行する場合、トランザクション処理のステートフルな性質のため、トランザクションのすべての要求は同じサーバーで処理する必要があります。ただし、分散環境では、スケーラビリティと可用性のためにサービスは通常複数のサーバー (またはホスト) で実行されるため、同じサーバーに要求をルーティングするのは簡単ではありません。このシナリオでは、トランザクション内のすべての要求を同じサーバーにルーティングする必要があり、負荷分散を確実にするために異なるトランザクションを分散する必要があります。 + +この課題に対処するには、セッションアフィニティ (スティッキーセッションとも呼ばれます) などのルーティングメカニズムを設定する必要があります。この戦略により、トランザクション内のリクエストが一貫して同じサーバーにルーティングされるようになります。または、gRPC を使用して双方向ストリーミング RPC を活用することもできます。ただし、これらの構成を実現するには通常、かなりの時間と労力が必要であることに注意してください。さらに、使用しているロードバランサー製品によっては、特定の設定調整が必要になる場合があります。 + +このトピックの詳細については、[2フェーズコミットインターフェイスを使用したトランザクションでのリクエストルーティング](../two-phase-commit-transactions.mdx#2フェーズコミットインターフェイスを使用したトランザクションでのリクエストルーティング) を参照してください。 + +ScalarDB Cluster は、リクエストをクラスター内の適切なクラスターノードに転送できるルーティングメカニズムを提供することで、この問題に対処します。したがって、クラスターノードがリクエストを受信すると、ノードはそのリクエストをクラスター内の正しいクラスターノードにルーティングできます。 + +## アーキテクチャ + +ScalarDB Cluster は、それぞれ ScalarDB 機能を備えた一連のクラスターノードで構成されています。このソリューションを使用することで、各クラスターノードは独立してトランザクションを実行できます。 + +ScalarDB Cluster の注目すべき機能は、ルーティングメカニズムを使用してトランザクション要求を分散することです。クラスターノードが要求を受信すると、ノードは要求を処理するのに適切なクラスターノードであるかどうかを判断します。適切なノードでない場合、ノードは要求をクラスター内の適切なクラスターノードにルーティングします。適切なクラスターノードを判断するために、ScalarDB Cluster はコンシステントハッシュアルゴリズムを使用します。 + +メンバーシップ管理は、ScalarDB Cluster で重要な役割を果たします。クラスターノードがクラスターに参加または離脱すると、クラスターの構成が自動的に調整され、この変更が反映されます。ScalarDB Cluster は現在、Kubernetes API を使用してメンバーシップ情報を取得します。 + +:::note + +現在、ScalarDB Cluster は Kubernetes 上での実行のみをサポートしています。 + +::: + +![ScalarDB Cluster アーキテクチャ](images/scalardb-cluster-architecture.png) + +## はじめに + +チュートリアルを開始する前に、ScalarDB Cluster をセットアップする必要があります。ScalarDB Cluster をセットアップするには、[ScalarDB Cluster をローカルにデプロイする方法](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx) を参照してください。 + +ScalarDB Cluster の使用開始に関するチュートリアルについては、以下を参照してください。 + +* [ScalarDB Cluster をはじめよう](getting-started-with-scalardb-cluster.mdx) +* [ScalarDB Cluster GraphQL をはじめよう](getting-started-with-scalardb-cluster-graphql.mdx) +* [JDBC 経由の ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +* [Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +* [.NET を使って ScalarDB Cluster をはじめよう](getting-started-with-scalardb-cluster-dotnet.mdx) +* [.NET を使って ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-dotnet.mdx) +* [.NET と LINQ を使って ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-linq.mdx) + +## 参考資料 + +ScalarDB Cluster Helm Chart の詳細については、以下を参照してください。 + +* [ScalarDB Cluster Helm Chart](https://github.com/scalar-labs/helm-charts/tree/main/charts/scalardb-cluster) +* [Scalar Helm Chart を使用して Scalar 製品をデプロイする](../helm-charts/how-to-deploy-scalar-products.mdx) +* [ScalarDB Cluster のデプロイする方法](../helm-charts/how-to-deploy-scalardb-cluster.mdx) + +For details about the configurations for ScalarDB Cluster, refer to the following: + +* [ScalarDB Cluster の設定](scalardb-cluster-configurations.mdx) + +Java API で ScalarDB Cluster を使用するアプリケーションの開発の詳細については、以下を参照してください。 + +* [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +ScalarDB Cluster gRPC API の詳細については、以下を参照してください。 + +* [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +* [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx new file mode 100644 index 00000000..e568f104 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx @@ -0,0 +1,314 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster を通じて非トランザクションストレージ操作を実行する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + +このガイドでは、ScalarDB Cluster を介して非トランザクションストレージ操作を実行する方法について説明します。 + +:::warning + +ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) が必要です。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。 + +::: + +## 準備 + +このガイドでは、ScalarDB サンプルリポジトリのサンプルを使用して、データベースと ScalarDB Cluster をスタンドアロンモードでセットアップします。 + +:::note + +スタンドアロンモードの ScalarDB Cluster は、主に開発とテストを目的としています。 + +::: + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、必要なファイルが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode +``` + +## データベースをセットアップする + +データベースを選択し、指示に従って ScalarDB Cluster 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](../requirements.mdx#データベース)を参照してください。 + + + +

MySQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB Local を実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントがない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを構成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル** を **強力** に設定します。 + +

ScalarDB Cluster を設定する

+ + 次の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。説明に従って、`scalar.db.contact_points` と `scalar.db.password` の値を必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d cassandra + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +ScalarDB の設定の包括的なリストについては、[ScalarDB の設定](../configurations.mdx)を参照してください。 + +## スタンドアロンモードで ScalarDB Cluster を設定する + +スタンドアロンモードで ScalarDB Cluster を設定するには、非トランザクションストレージ操作を実行するように ScalarDB Cluster を設定し、ライセンスキーを設定してから、ScalarDB Cluster を起動する必要があります。 + +### 非トランザクションストレージ操作を実行するように ScalarDB Cluster を設定する + +非トランザクションストレージ操作を実行するには、設定ファイル `scalardb-cluster-node.properties` で `scalar.db.transaction_manager` プロパティを `single-crud-operation` に設定する必要があります。 + +```properties +scalar.db.transaction_manager=single-crud-operation +``` + +### ライセンスキーの設定 + +プロパティファイルで ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) を設定します。詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + +### スタンドアロンモードで ScalarDB Cluster を起動 + +スタンドアロンモードで ScalarDB Cluster を起動するには、次のコマンドを実行します。 + +:::note + +ScalarDB Cluster のその他の設定を変更する場合は、以下のコマンドを実行する前に `scalardb-cluster-node.properties` ファイルを更新してください。 + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## スキーマを作成またはインポートする + +ScalarDB には、実装固有のデータモデルとスキーマにマップされる独自のデータモデルとスキーマがあります。 + +- **データベーススキーマを作成する必要がありますか?** [クラスター用 Schema Loader](developer-guide-for-scalardb-cluster-with-java-api.mdx#クラスター用-schema-loader) を参照してください。 +- **既存のデータベースをインポートする必要がありますか?** [ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](../schema-loader-import.mdx)を参照してください。 + +## Java アプリケーションを作成する + +このセクションでは、ScalarDB Cluster Java Client SDK をプロジェクトに追加する方法と、Java を使用して非トランザクションストレージ操作を実行するようにプロジェクトを設定する方法について説明します。 + +### ScalarDB Cluster Java Client SDK をビルドに追加する + +ScalarDB Cluster Java Client SDK は、[Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-cluster-java-client-sdk) で入手できます。Gradle または Maven を使用して、SDK をビルド依存関係としてアプリケーションに追加できます。 + +ビルドツールを選択し、手順に従って ScalarDB Cluster Java Client SDK のビルド依存関係をアプリケーションに追加します。 + + + + Gradle を使用して ScalarDB Cluster Java Client SDK のビルド依存関係を追加するには、アプリケーションの `build.gradle` に以下を追加します。 + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + } + ``` + + + Maven を使用して ScalarDB Cluster Java Client SDK のビルド依存関係を追加するには、アプリケーションの `pom.xml` に以下を追加します。 + + ```xml + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + ``` + + + +### ScalarDB Cluster Java SDK を設定する + +ScalarDB Cluster Java SDK の設定の詳細については、[クライアント設定](developer-guide-for-scalardb-cluster-with-java-api.mdx#クライアント設定)を参照してください。 + +### Java API を使用する + +Java API の詳細については、[ScalarDB Java API ガイド](../api-guide.mdx)を参照してください。 + +:::note + +非トランザクションストレージ操作には、次の制限が適用されます: + +- トランザクションの開始はサポートされていません。詳細については、[トランザクションを開始または開始せずにトランザクションを実行する](../api-guide.mdx#トランザクションを開始または開始せずにトランザクションを実行する)を参照してください。 +- 1つのトランザクションで複数のミューテーションを実行することはサポートされていません。 + +::: + +### 詳細 + +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.15.4/index.html) +- [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx new file mode 100644 index 00000000..01e0d1e6 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx @@ -0,0 +1,395 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# SQL インターフェースを介して非トランザクションストレージ操作を実行する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + +このガイドでは、ScalarDB Cluster の SQL インターフェースを通じて非トランザクションストレージ操作を実行する方法について説明します。 + +:::warning + +ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) が必要です。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。 + +::: + +## 準備 + +このガイドでは、ScalarDB サンプルリポジトリのサンプルを使用して、データベースと ScalarDB Cluster をスタンドアロンモードでセットアップします。 + +:::note + +スタンドアロンモードの ScalarDB Cluster は、主に開発とテストを目的としています。 + +::: + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、必要なファイルが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode +``` + +## データベースをセットアップする + +データベースを選択し、指示に従って ScalarDB Cluster 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](../requirements.mdx#データベース)を参照してください。 + + + +

MySQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB Local を実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントがない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを構成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル** を **強力** に設定します。 + +

ScalarDB Cluster を設定する

+ + 次の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。説明に従って、`scalar.db.contact_points` と `scalar.db.password` の値を必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d cassandra + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +ScalarDB の設定の包括的なリストについては、[ScalarDB の設定](../configurations.mdx)を参照してください。 + +## スタンドアロンモードで ScalarDB Cluster を設定する + +スタンドアロンモードで ScalarDB Cluster を設定するには、非トランザクションストレージ操作を実行するように ScalarDB Cluster を設定し、ライセンスキーを設定してから、ScalarDB Cluster を起動する必要があります。 + +### 非トランザクションストレージ操作を実行するように ScalarDB Cluster を設定する + +非トランザクションストレージ操作を実行するには、設定ファイル `scalardb-cluster-node.properties` で `scalar.db.transaction_manager` プロパティを `single-crud-operation` に設定する必要があります。 + +```properties +scalar.db.transaction_manager=single-crud-operation +``` + +### ライセンスキーの設定 + +プロパティファイルで ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) を設定します。詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + +### スタンドアロンモードで ScalarDB Cluster を起動 + +スタンドアロンモードで ScalarDB Cluster を起動するには、次のコマンドを実行します。 + +:::note + +ScalarDB Cluster のその他の設定を変更する場合は、以下のコマンドを実行する前に `scalardb-cluster-node.properties` ファイルを更新してください。 + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## スキーマを作成またはインポートする + +ScalarDB には、実装固有のデータモデルとスキーマにマップされる独自のデータモデルとスキーマがあります。 + +- **データベーススキーマを作成する必要がありますか?** [クラスター用 Schema Loader](developer-guide-for-scalardb-cluster-with-java-api.mdx#クラスター用-schema-loader) を参照してください。 +- **既存のデータベースをインポートする必要がありますか?** [ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](../schema-loader-import.mdx)を参照してください。 + +また、サポートされている DDL のリストについては、[ScalarDB SQL 文法](../scalardb-sql/grammar.mdx)を参照してください。 + +## アプリケーションを作成する + + + +

JDBC アプリケーションを設定する

+ + このセクションでは、ScalarDB JDBC ドライバーをプロジェクトに追加する方法と、Java を使用して非トランザクションストレージ操作を実行するように設定する方法について説明します。 + +

ScalarDB JDBC ドライバーをプロジェクトに追加する

+ + Gradle または Maven を使用して、ScalarDB JDBC ドライバーをビルド依存関係としてアプリケーションに追加できます。 + + ビルドツールを選択し、手順に従って ScalarDB JDBC ドライバーのビルド依存関係をアプリケーションに追加します。 + + + + Gradle を使用して ScalarDB JDBC ドライバーのビルド依存関係を追加するには、アプリケーションの `build.gradle` に以下を追加します。 + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb-sql-jdbc:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + } + ``` + + + Maven を使用して ScalarDB SQL API のビルド依存関係を追加するには、アプリケーションの `pom.xml` に以下を追加します。 + + ```xml + + + com.scalar-labs + scalardb-sql-jdbc + 3.15.4 + + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + + ``` + + + +

SQL インターフェース用に ScalarDB Cluster Java SDK を設定する

+ + SQL インターフェース用に ScalarDB Cluster Java SDK を設定する方法の詳細については、[ScalarDB Cluster SQL クライアント設定](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +

JDBC API を使用する

+ + JDBC API の詳細については、[ScalarDB JDBC ガイド](../scalardb-sql/jdbc-guide.mdx)を参照してください。 + +:::note + +非トランザクションストレージ操作には、次の制限が適用されます: + +- トランザクションの開始はサポートされていません。 +- 単一の SQL ステートメントで複数のミューテーションを実行することはサポートされていません。 +- 分離レベルは常に `READ_COMMITTED` です。 + +::: + +

詳細

+ + - [Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) + - [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) +
+ +

Java アプリケーションを設定する

+ + このセクションでは、ScalarDB SQL API をプロジェクトに追加する方法と、Java を使用して非トランザクションストレージ操作を実行するように設定する方法について説明します。 + +

ScalarDB SQL API をプロジェクトに追加する

+ + Gradle または Maven を使用して、ScalarDB SQL API をビルド依存関係としてアプリケーションに追加できます。 + + ビルドツールを選択し、手順に従って ScalarDB SQL API のビルド依存関係をアプリケーションに追加します。 + + + + Gradle を使用して ScalarDB SQL API のビルド依存関係を追加するには、アプリケーションの `build.gradle` に以下を追加します。 + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb-sql:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + } + ``` + + + Maven を使用して ScalarDB SQL API のビルド依存関係を追加するには、アプリケーションの `pom.xml` に以下を追加します。 + + ```xml + + + com.scalar-labs + scalardb-sql + 3.15.4 + + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + + ``` + + + +

SQL インターフェース用に ScalarDB Cluster Java SDK を設定する

+ + SQL インターフェース用に ScalarDB Cluster Java SDK を設定する方法の詳細については、[ScalarDB Cluster SQL クライアント設定](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +

Java API を使用する

+ + SQL API の詳細については、[ScalarDB SQL API ガイド](../scalardb-sql/sql-api-guide.mdx)を参照してください。 + +:::note + +非トランザクションストレージ操作には、次の制限が適用されます: + +- トランザクションの開始はサポートされていません。 +- 単一の SQL ステートメントで複数のミューテーションを実行することはサポートされていません。 +- 分離レベルは常に `READ_COMMITTED` です。 + +::: + +

詳細

+ + - [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.15.4/index.html) + +
+
diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx new file mode 100644 index 00000000..0a83ca11 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx @@ -0,0 +1,301 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster SQL を介してトランザクションを実行する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + +このガイドでは、ScalarDB プロパティファイルを設定する方法と、ScalarDB Cluster SQL を使用して1フェーズまたは2フェーズのコミットインターフェイスを介してトランザクションを実行するためのスキーマを作成する方法について説明します。 + +:::warning + +ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) が必要です。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。 + +::: + +## 準備 + +このガイドでは、ScalarDB サンプルリポジトリのサンプルを使用して、データベースと ScalarDB Cluster をスタンドアロンモードでセットアップします。 + +:::note + +スタンドアロンモードの ScalarDB Cluster は、主に開発とテストを目的としています。 + +::: + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、必要なファイルが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode +``` + +## データベースをセットアップする + +データベースを選択し、指示に従って ScalarDB Cluster 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](../requirements.mdx#データベース)を参照してください。 + + + +

MySQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB Local を実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントがない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを構成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル** を **強力** に設定します。 + +

ScalarDB Cluster を設定する

+ + 次の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。説明に従って、`scalar.db.contact_points` と `scalar.db.password` の値を必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d cassandra + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +ScalarDB Cluster SQL の設定の包括的なリストについては、[ScalarDB Cluster SQL クライアント設定](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +## スタンドアロンモードで ScalarDB Cluster を設定する + +スタンドアロンモードで ScalarDB Cluster を設定するには、ライセンスキーを設定してから ScalarDB Cluster を起動する必要があります。 + +### ライセンスキーの設定 + +プロパティファイルで ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) を設定します。詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + +### スタンドアロンモードで ScalarDB Cluster を起動 + +スタンドアロンモードで ScalarDB Cluster を起動するには、次のコマンドを実行します。 + +:::note + +ScalarDB Cluster のその他の設定を変更する場合は、以下のコマンドを実行する前に `scalardb-cluster-node.properties` ファイルを更新してください。 + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## スキーマを作成またはインポートする + +ScalarDB には、実装固有のデータモデルとスキーマにマップされる独自のデータモデルとスキーマがあります。 + +- **データベーススキーマを作成する必要がありますか?** [クラスター用 Schema Loader](developer-guide-for-scalardb-cluster-with-java-api.mdx#クラスター用-schema-loader) を参照してください。 +- **既存のデータベースをインポートする必要がありますか?** [ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](../schema-loader-import.mdx)を参照してください。 + +## トランザクションを実行する + +1フェーズまたは2フェーズのコミットインターフェースを使用してトランザクションを実行できます。トランザクションを実行する方法を選択します。 + + + +

1フェーズコミットインターフェース

+ + 1フェーズコミットインターフェースを使用してトランザクションを実行する方法の詳細については、[ScalarDB SQL JDBC ガイド](../scalardb-sql/jdbc-guide.mdx)を参照してください。 + +:::note + +2フェーズコミットインターフェースでトランザクションを実行する方法に関するドキュメントは近日公開予定です。 + +::: +
+ +

1フェーズコミットインターフェース

+ + 1フェーズコミットインターフェースを使用してトランザクションを実行する方法の詳細については、[ScalarDB SQL API ガイド](../scalardb-sql/sql-api-guide.mdx)を参照してください。 + +:::note + +2フェーズコミットインターフェースでトランザクションを実行する方法に関するドキュメントは近日公開予定です。 + +::: + +

詳細

+ + ScalarDB Cluster SQL を使用してトランザクションを実行する方法の詳細については、以下を参照してください。 + + - [ScalarDB Cluster SQL gRPC API ガイド](scalardb-cluster-sql-grpc-api-guide.mdx) +
+ +

1フェーズまたは2フェーズコミットインターフェイス

+ + 1フェーズまたは2フェーズコミットインターフェイスを使用してトランザクションを実行する方法の詳細については、[ScalarDB Cluster .NET Client SDK での LINQ をはじめよう](../scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx#トランザクションの管理)を参照してください。 +
+ +

1フェーズコミットインターフェース

+ + 1フェーズコミットインターフェイスを使用してトランザクションを実行する方法の詳細については、[ScalarDB Cluster .NET Client SDK での分散 SQL トランザクションをはじめよう](../scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx)を参照してください。 + +:::note + +2フェーズコミットインターフェースでトランザクションを実行する方法に関するドキュメントは近日公開予定です。今のところは、[ScalarDB Cluster .NET Client SDK の2フェーズコミットインターフェイスを使用した分散トランザクションをはじめよう](../scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx) を参照してください。 + +::: +
+
diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx new file mode 100644 index 00000000..fde07fa1 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx @@ -0,0 +1,307 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster を介してトランザクションを実行する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + +このガイドでは、ScalarDB プロパティファイルを設定し、ScalarDB Cluster を使用して1フェーズまたは2フェーズのコミットインターフェイスを介してトランザクションを実行するためのスキーマを作成する方法について説明します。 + +:::warning + +ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) が必要です。ライセンスキーをお持ちでない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。 + +::: + +## 準備 + +このガイドでは、ScalarDB サンプルリポジトリのサンプルを使用して、データベースと ScalarDB Cluster をスタンドアロンモードでセットアップします。 + +:::note + +スタンドアロンモードの ScalarDB Cluster は、主に開発とテストを目的としています。 + +::: + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、必要なファイルが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode +``` + +## データベースをセットアップする + +データベースを選択し、指示に従って ScalarDB Cluster 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](../requirements.mdx#データベース)を参照してください。 + + + +

MySQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB Local を実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントがない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを構成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル** を **強力** に設定します。 + +

ScalarDB Cluster を設定する

+ + 次の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。説明に従って、`scalar.db.contact_points` と `scalar.db.password` の値を必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d cassandra + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +ScalarDB Cluster の設定の包括的なリストについては、[ScalarDB Cluster の設定](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定) を参照してください。 + +## スタンドアロンモードで ScalarDB Cluster を設定する + +スタンドアロンモードで ScalarDB Cluster を設定するには、ライセンスキーを設定してから ScalarDB Cluster を起動する必要があります。 + +### ライセンスキーの設定 + +プロパティファイルで ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) を設定します。詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + +### スタンドアロンモードで ScalarDB Cluster を起動 + +スタンドアロンモードで ScalarDB Cluster を起動するには、次のコマンドを実行します。 + +:::note + +ScalarDB Cluster のその他の設定を変更する場合は、以下のコマンドを実行する前に `scalardb-cluster-node.properties` ファイルを更新してください。 + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## スキーマを作成またはインポートする + +ScalarDB には、実装固有のデータモデルとスキーマにマップされる独自のデータモデルとスキーマがあります。 + +- **データベーススキーマを作成する必要がありますか?** [ScalarDB Schema Loader](../schema-loader.mdx) を参照してください。 +- **既存のデータベースをインポートする必要がありますか?** [ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](../schema-loader-import.mdx)を参照してください。 + +## トランザクションを実行する + +1フェーズまたは2フェーズのコミットインターフェースを使用してトランザクションを実行できます。トランザクションを実行する方法を選択してください。 + + +:::note + +モノリシックなアプリケーションを構築する場合は、1フェーズコミットインターフェースを使用してください。一方、マイクロサービスアプリケーションを構築する場合は、[マイクロサービスにおける ScalarDB Cluster のデプロイパターン](./deployment-patterns-for-microservices.mdx)を読んで、どちらを使用するかを決定してください。 + +::: + + + +

1フェーズコミットインターフェース

+ + 1フェーズコミットインターフェイスを使用してトランザクションを実行する方法の詳細については、[ScalarDB Java API ガイド](../api-guide.mdx#transactional-api)を参照してください。 + +:::note + +1フェーズコミットインターフェースを使用してトランザクションを実行するには、次のサンプルチュートリアルを参照してください。 + +- [マルチストレージトランザクションをサポートするサンプルアプリケーションを作成する](../scalardb-samples/multi-storage-transaction-sample/README.mdx) +- [マルチストレージトランザクションを備えた Spring Data JDBC for ScalarDB のサンプルアプリケーション](../scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx) + +::: + +

2フェーズコミットインターフェース

+ + 2フェーズコミットインターフェイスを使用してトランザクションを実行する方法の詳細については、[2フェーズコミットインターフェイスを使用したトランザクション](../two-phase-commit-transactions.mdx)を参照してください。 + +:::note + +2フェーズコミットインターフェースを使用してトランザクションを実行するには、次のサンプルチュートリアルを参照してください。 + +- [マイクロサービストランザクションをサポートするサンプルアプリケーションを作成する](../scalardb-samples/microservice-transaction-sample/README.mdx) +- [マイクロサービストランザクションを使用した Spring Data JDBC for ScalarDB のサンプルアプリケーション](../scalardb-samples/spring-data-microservice-transaction-sample/README.mdx) + +::: + +

詳細

+ + ScalarDB Cluster を使用してトランザクションを実行する方法の詳細については、以下を参照してください。 + + - [ScalarDB Cluster gRPC API ガイド](scalardb-cluster-grpc-api-guide.mdx) +
+ +

1フェーズコミットインターフェース

+ + 1フェーズコミットインターフェイスを使用してトランザクションを実行する方法の詳細については、[ScalarDB Cluster .NET Client SDK での分散トランザクションをはじめよう](../scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions.mdx)を参照してください。 + +

2フェーズコミットインターフェース

+ + 2フェーズコミットインターフェイスを使用してトランザクションを実行する方法の詳細については、[ScalarDB Cluster .NET Client SDK の2フェーズコミットインターフェイスを使用した分散トランザクションをはじめよう](../scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx)を参照してください。 +
+
diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-abac-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-abac-status-codes.mdx new file mode 100644 index 00000000..7236722d --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-abac-status-codes.mdx @@ -0,0 +1,730 @@ +--- +tags: + - Enterprise Premium Option + - Private Preview +displayed_sidebar: docsJapanese +--- + +# 属性ベースのアクセス制御エラーコード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、属性ベースのアクセス制御に関連するエラーコードの一覧を示します。 + +## エラーコードのクラスと説明 + +| クラス | 説明 | +|:----------------|:--------------------------| +| `DB-ABAC-1xxxx` | ユーザーエラーカテゴリのエラー | +| `DB-ABAC-2xxxx` | 同時実行エラーカテゴリのエラー | +| `DB-ABAC-3xxxx` | 内部エラーカテゴリのエラー | + +## `DB-ABAC-1xxxx` ステータスコード + +以下は、ユーザーエラーカテゴリのステータスコードとメッセージです。 + +### `DB-ABAC-10000` + +**メッセージ** + +```markdown +The put operation is not supported. Use insert, upsert, or update instead +``` + +### `DB-ABAC-10001` + +**メッセージ** + +```markdown +The default level must be less than or equal to the level. Default-level short name: %s; Default-level number: %d; Level short name: %s; Level number: %d +``` + +### `DB-ABAC-10002` + +**メッセージ** + +```markdown +The row level must be less than or equal to the level. Row-level short name: %s; Row-level number: %d; Level short name: %s; Level number: %d +``` + +### `DB-ABAC-10003` + +**メッセージ** + +```markdown +The operation does not have the target namespace or table name. Operation: %s +``` + +### `DB-ABAC-10004` + +**メッセージ** + +```markdown +The policy does not exist. Policy: %s +``` + +### `DB-ABAC-10005` + +**メッセージ** + +```markdown +The level does not exist. Policy: %s; Level short name: %s +``` + +### `DB-ABAC-10006` + +**メッセージ** + +```markdown +The compartment does not exist. Policy: %s; Compartment short name: %s +``` + +### `DB-ABAC-10007` + +**メッセージ** + +```markdown +The group does not exist. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-10008` + +**メッセージ** + +```markdown +The policy already exists. Policy: %s +``` + +### `DB-ABAC-10009` + +**メッセージ** + +```markdown +The data tag column name is already in use in the policy %s. Policy: %s; Data tag column name: %s +``` + +### `DB-ABAC-10010` + +**メッセージ** + +```markdown +The level already exists. Policy: %s; Level short name: %s +``` + +### `DB-ABAC-10011` + +**メッセージ** + +```markdown +The compartment already exists. Policy: %s; Compartment short name: %s +``` + +### `DB-ABAC-10012` + +**メッセージ** + +```markdown +The group already exists. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-10013` + +**メッセージ** + +```markdown +The parent group does not exist. Policy: %s; Group short name: %s; Parent-group short name: %s +``` + +### `DB-ABAC-10014` + +**メッセージ** + +```markdown +The parent group is the same as the child group. Policy: %s; Group short name: %s; Parent-group short name: %s +``` + +### `DB-ABAC-10015` + +**メッセージ** + +```markdown +The group has child groups. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-10016` + +**メッセージ** + +```markdown +The compartment cannot be a row compartment for read-only access mode. Policy: %s; User: %s; Compartment short name: %s +``` + +### `DB-ABAC-10017` + +**メッセージ** + +```markdown +The compartment is already assigned to the user. Policy: %s; User: %s; Compartment short name: %s +``` + +### `DB-ABAC-10018` + +**メッセージ** + +```markdown +The group cannot be a row group for read-only access mode. Policy: %s; User: %s; Group short name: %s +``` + +### `DB-ABAC-10019` + +**メッセージ** + +```markdown +The group is already assigned to the user. Policy: %s; User: %s; Group short name: %s +``` + +### `DB-ABAC-10020` + +**メッセージ** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-ABAC-10021` + +**メッセージ** + +```markdown +The namespace policy already exists. NamespacePolicy: %s +``` + +### `DB-ABAC-10022` + +**メッセージ** + +```markdown +The namespace policy does not exist. NamespacePolicy: %s +``` + +### `DB-ABAC-10023` + +**メッセージ** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-ABAC-10024` + +**メッセージ** + +```markdown +The table policy already exists. TablePolicy: %s +``` + +### `DB-ABAC-10025` + +**メッセージ** + +```markdown +The table policy does not exist. TablePolicy: %s +``` + +### `DB-ABAC-10026` + +**メッセージ** + +```markdown +The short name must not be empty. Short name: %s +``` + +### `DB-ABAC-10027` + +**メッセージ** + +```markdown +The short name must be 30 characters or less. Short name: %s +``` + +### `DB-ABAC-10028` + +**メッセージ** + +```markdown +The short name must not contain a colon. Short name: %s +``` + +### `DB-ABAC-10029` + +**メッセージ** + +```markdown +The short name must not contain a comma. Short name: %s +``` + +### `DB-ABAC-10030` + +**メッセージ** + +```markdown +The data tag is invalid. Data tag: %s +``` + +### `DB-ABAC-10031` + +**メッセージ** + +```markdown +The level must be specified in the data tag. Data tag: %s +``` + +### `DB-ABAC-10032` + +**メッセージ** + +```markdown +The user tag is invalid. User tag: %s +``` + +### `DB-ABAC-10033` + +**メッセージ** + +```markdown +The level must be specified in the user tag. User tag: %s +``` + +### `DB-ABAC-10034` + +**メッセージ** + +```markdown +The specified user tag is not allowed. User tag: %s +``` + +### `DB-ABAC-10035` + +**メッセージ** + +```markdown +The data tag column type should be TEXT. Policy: %s; Data tag column: %s +``` + +### `DB-ABAC-10036` + +**メッセージ** + +```markdown +The specified data tag is not allowed. Data tag: %s +``` + +### `DB-ABAC-10037` + +**メッセージ** + +```markdown +The data tag column cannot be used in conditions. Operation: %s; Data tag column: %s +``` + +### `DB-ABAC-10038` + +**メッセージ** + +```markdown +The operation is not allowed for the policy. Policy: %s; Operation: %s +``` + +### `DB-ABAC-10039` + +**メッセージ** + +```markdown +Access denied: Invalid auth token +``` + +### `DB-ABAC-10040` + +**メッセージ** + +```markdown +The authentication and authorization feature must be enabled to use the attribute-based access control feature +``` + +### `DB-ABAC-10041` + +**メッセージ** + +```markdown +The single CRUD operation transaction manager does not support the attribute-based access control feature +``` + +### `DB-ABAC-10042` + +**メッセージ** + +```markdown +The data tag column cannot be used in ordering. Operation: %s; Data tag column: %s +``` + +### `DB-ABAC-10043` + +**メッセージ** + +```markdown +The namespace policy for the policy and namespace already exists. Policy: %s; Namespace: %s +``` + +### `DB-ABAC-10044` + +**メッセージ** + +```markdown +The table policy for the policy and table already exists. Policy: %s; Table: %s +``` + +## `DB-ABAC-2xxxx` ステータスコード + +以下は、同時実行エラーカテゴリのステータスコードとメッセージです。 + +### `DB-ABAC-20000` + +**メッセージ** + +```markdown +The record does not exist, so the %s condition is not satisfied +``` + +## `DB-ABAC-3xxxx` ステータスコード + +以下は、内部エラーカテゴリのステータスコードとメッセージです。 + +### `DB-ABAC-30000` + +**メッセージ** + +```markdown +Creating a policy failed. Policy: %s; Data tag column: %s +``` + +### `DB-ABAC-30001` + +**メッセージ** + +```markdown +Enabling the policy failed. Policy: %s +``` + +### `DB-ABAC-30002` + +**メッセージ** + +```markdown +Disabling the policy failed. Policy: %s +``` + +### `DB-ABAC-30003` + +**メッセージ** + +```markdown +Getting the policy failed. Policy: %s +``` + +### `DB-ABAC-30004` + +**メッセージ** + +```markdown +Getting the policies failed +``` + +### `DB-ABAC-30005` + +**メッセージ** + +```markdown +Creating a level failed. Policy: %s; Level short name: %s; Level long name: %s; Level number: %d +``` + +### `DB-ABAC-30006` + +**メッセージ** + +```markdown +Dropping the level failed. Policy: %s; Level short name: %s +``` + +### `DB-ABAC-30007` + +**メッセージ** + +```markdown +Getting the level failed. Policy: %s; Level short name: %s +``` + +### `DB-ABAC-30008` + +**メッセージ** + +```markdown +Getting the levels failed. Policy: %s +``` + +### `DB-ABAC-30009` + +**メッセージ** + +```markdown +Creating a compartment failed. Policy: %s; Compartment short name: %s; Compartment long name: %s +``` + +### `DB-ABAC-30010` + +**メッセージ** + +```markdown +Dropping the compartment failed. Policy: %s; Compartment short name: %s +``` + +### `DB-ABAC-30011` + +**メッセージ** + +```markdown +Getting the compartment failed. Policy: %s; Compartment short name: %s +``` + +### `DB-ABAC-30012` + +**メッセージ** + +```markdown +Getting the compartments failed. Policy: %s +``` + +### `DB-ABAC-30013` + +**メッセージ** + +```markdown +Creating a group failed. Policy: %s; Group short name: %s; Group long name: %s; Parent-group short name: %s +``` + +### `DB-ABAC-30014` + +**メッセージ** + +```markdown +Dropping the group failed. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-30015` + +**メッセージ** + +```markdown +Getting the group failed. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-30016` + +**メッセージ** + +```markdown +Getting groups failed. Policy: %s +``` + +### `DB-ABAC-30017` + +**メッセージ** + +```markdown +Getting child groups failed. Policy: %s; Parent-group short name: %s +``` + +### `DB-ABAC-30018` + +**メッセージ** + +```markdown +Setting the levels to the user failed. Policy: %s; User: %s; Level short name: %s; Default-level short name: %s; Row-level short name: %s +``` + +### `DB-ABAC-30019` + +**メッセージ** + +```markdown +Adding the compartment to the user failed. Policy: %s; User: %s; Compartment short name: %s +``` + +### `DB-ABAC-30020` + +**メッセージ** + +```markdown +Removing the compartment from the user failed. Policy: %s; User: %s; Compartment short name: %s +``` + +### `DB-ABAC-30021` + +**メッセージ** + +```markdown +Adding the group to the user failed. Policy: %s; User: %s; Group short name: %s +``` + +### `DB-ABAC-30022` + +**メッセージ** + +```markdown +Removing the group from the user failed. Policy: %s; User: %s; Group short name: %s +``` + +### `DB-ABAC-30023` + +**メッセージ** + +```markdown +Dropping the user tag information from the user failed. Policy: %s; User: %s +``` + +### `DB-ABAC-30024` + +**メッセージ** + +```markdown +Getting the user tag information failed. Policy: %s; User: %s +``` + +### `DB-ABAC-30025` + +**メッセージ** + +```markdown +Creating a namespace policy failed. NamespacePolicy: %s; Policy: %s; Namespace: %s +``` + +### `DB-ABAC-30026` + +**メッセージ** + +```markdown +Enabling the namespace policy failed. NamespacePolicy: %s +``` + +### `DB-ABAC-30027` + +**メッセージ** + +```markdown +Disabling the namespace policy failed. NamespacePolicy: %s +``` + +### `DB-ABAC-30028` + +**メッセージ** + +```markdown +Removing the namespace policies assigned to the namespace failed. Namespace: %s +``` + +### `DB-ABAC-30029` + +**メッセージ** + +```markdown +Getting the namespace policies failed +``` + +### `DB-ABAC-30030` + +**メッセージ** + +```markdown +Creating a table policy failed. TablePolicy: %s; Policy: %s; Table: %s +``` + +### `DB-ABAC-30031` + +**メッセージ** + +```markdown +Enabling the table policy failed. TablePolicy: %s +``` + +### `DB-ABAC-30032` + +**メッセージ** + +```markdown +Disabling the table policy failed. TablePolicy: %s +``` + +### `DB-ABAC-30033` + +**メッセージ** + +```markdown +Removing the table policies assigned to the table failed. Table: %s +``` + +### `DB-ABAC-30034` + +**メッセージ** + +```markdown +Getting the table policies failed +``` + +### `DB-ABAC-30035` + +**メッセージ** + +```markdown +Getting the policies assigned to the namespace failed. Namespace: %s +``` + +### `DB-ABAC-30036` + +**メッセージ** + +```markdown +Getting the policies assigned to the table failed. Table: %s +``` + +### `DB-ABAC-30037` + +**メッセージ** + +```markdown +Registering the data tag failed. Policy: %s; Data tag: %s +``` + +### `DB-ABAC-30038` + +**メッセージ** + +```markdown +Getting the data tags failed. Policy: %s +``` + +### `DB-ABAC-30039` + +**メッセージ** + +```markdown +Getting the namespace policy failed. NamespacePolicy: %s +``` + +### `DB-ABAC-30040` + +**メッセージ** + +```markdown +Getting the table policy failed. TablePolicy: %s +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-auth-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-auth-status-codes.mdx new file mode 100644 index 00000000..ec84a3ae --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-auth-status-codes.mdx @@ -0,0 +1,309 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 認証および認可エラーコード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、認証および認可に関連するエラーコードの一覧を示します。 + +## エラーコードのクラスと説明 + +| クラス | 説明 | +|:----------------|:--------------------------| +| `DB-AUTH-1xxxx` | ユーザーエラーカテゴリのエラー | +| `DB-AUTH-3xxxx` | 内部エラーカテゴリのエラー | + +## `DB-AUTH-1xxxx` ステータスコード + +以下は、ユーザーエラーカテゴリのステータスコードとメッセージです。 + +### `DB-AUTH-10000` + +**メッセージ** + +```markdown +The user already exists. Username: %s +``` + +### `DB-AUTH-10001` + +**メッセージ** + +```markdown +The user does not exist. Username: %s +``` + +### `DB-AUTH-10003` + +**メッセージ** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-AUTH-10004` + +**メッセージ** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-AUTH-10005` + +**メッセージ** + +```markdown +Invalid username or password +``` + +### `DB-AUTH-10006` + +**メッセージ** + +```markdown +Access denied: Invalid auth token +``` + +### `DB-AUTH-10007` + +**メッセージ** + +```markdown +Access denied: You need the %s privilege on the namespace %s to execute this operation +``` + +### `DB-AUTH-10008` + +**メッセージ** + +```markdown +Access denied: You need the %s privilege on the table %s to execute this operation +``` + +### `DB-AUTH-10009` + +**メッセージ** + +```markdown +Access denied: You must be a superuser to execute this operation +``` + +### `DB-AUTH-10010` + +**メッセージ** + +```markdown +Access denied: You can't access information about the user %s +``` + +### `DB-AUTH-10011` + +**メッセージ** + +```markdown +Access denied: You can't alter the user %s +``` + +### `DB-AUTH-10012` + +**メッセージ** + +```markdown +Access denied: You must be a superuser to change the SUPERUSER attribute +``` + +### `DB-AUTH-10013` + +**メッセージ** + +```markdown +You can't change the SUPERUSER attribute for the current user %s +``` + +### `DB-AUTH-10014` + +**メッセージ** + +```markdown +You can't drop the current user %s +``` + +### `DB-AUTH-10015` + +**メッセージ** + +```markdown +Access denied: You can't grant the %s privilege because you don't have the same privilege on the table %s +``` + +### `DB-AUTH-10016` + +**メッセージ** + +```markdown +Access denied: You can't grant the %s privilege because you don't have the same privilege on the namespace %s +``` + +### `DB-AUTH-10017` + +**メッセージ** + +```markdown +Access denied: You can't revoke the %s privilege because you don't have the same privilege on the table %s +``` + +### `DB-AUTH-10018` + +**メッセージ** + +```markdown +Access denied: You can't revoke the %s privilege because you don't have the same privilege on the namespace %s +``` + +### `DB-AUTH-10019` + +**メッセージ** + +```markdown +The operation does not have the target namespace or table name. Operation: %s +``` + +## `DB-AUTH-3xxxx` ステータスコード + +以下は、内部エラーカテゴリのステータスコードとメッセージです。 + +### `DB-AUTH-30000` + +**メッセージ** + +```markdown +Getting auth token information failed +``` + +### `DB-AUTH-30001` + +**メッセージ** + +```markdown +Getting the user failed. Username: %s +``` + +### `DB-AUTH-30002` + +**メッセージ** + +```markdown +Creating a user failed. Username: %s +``` + +### `DB-AUTH-30003` + +**メッセージ** + +```markdown +Altering the user failed. Username: %s +``` + +### `DB-AUTH-30004` + +**メッセージ** + +```markdown +Dropping the user failed. Username: %s +``` + +### `DB-AUTH-30005` + +**メッセージ** + +```markdown +Granting privileges failed. Username: %s; Namespace: %s; Privileges: %s +``` + +### `DB-AUTH-30006` + +**メッセージ** + +```markdown +Granting privileges failed. Username: %s; Table: %s; Privileges: %s +``` + +### `DB-AUTH-30007` + +**メッセージ** + +```markdown +Revoking privileges failed. Username: %s; Namespace: %s; Privileges: %s +``` + +### `DB-AUTH-30008` + +**メッセージ** + +```markdown +Revoking privileges failed. Username: %s; Table: %s; Privileges: %s +``` + +### `DB-AUTH-30009` + +**メッセージ** + +```markdown +Getting users failed +``` + +### `DB-AUTH-30010` + +**メッセージ** + +```markdown +Getting privileges failed. Username: %s; Namespace: %s +``` + +### `DB-AUTH-30011` + +**メッセージ** + +```markdown +Getting privileges failed. Username: %s; Table: %s +``` + +### `DB-AUTH-30012` + +**メッセージ** + +```markdown +Deleting privileges failed. Namespace: %s +``` + +### `DB-AUTH-30013` + +**メッセージ** + +```markdown +Deleting privileges failed. Table: %s +``` + +### `DB-AUTH-30014` + +**メッセージ** + +```markdown +Logging in failed. Username: %s +``` + +### `DB-AUTH-30015` + +**メッセージ** + +```markdown +Logging out failed +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-auth-with-sql.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-auth-with-sql.mdx new file mode 100644 index 00000000..d3aec54f --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-auth-with-sql.mdx @@ -0,0 +1,380 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ユーザーの認証と認可 + +import JavadocLink from '/src/theme/JavadocLink.js'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + + + +ScalarDB Cluster には、ユーザーを認証および認可するメカニズムがあります。 + +このガイドでは、ScalarDB SQL で認証と認可を使用する方法について説明します。 + +:::tip + +プリミティブインターフェースを使用して認証と認可を行うこともできます。詳細については、を参照してください。これは を実装しています。 + +::: + +## 概要 + +認証と認可を使用することで、ユーザーを作成し、その権限を付与または取り消すことができます。`CREATE USER` コマンドを使用してユーザーを作成し、`GRANT` コマンドまたは `REVOKE` コマンドを使用して、それぞれテーブルまたは名前空間に対する権限を付与または取り消すことができます。このようなデータ制御言語 (DCL) コマンドの詳細については、[DCL](../scalardb-sql/grammar.mdx#dcl) を参照してください。 + +ユーザーは、必要な権限を持っている場合、ユーザー名とパスワードを使用して ScalarDB Cluster にログインし、SQL ステートメントを実行できます。 + +認証と認可では、次の2種類のユーザーがサポートされます。 + +- **スーパーユーザー:** このタイプのユーザーにはすべての権限があります。スーパーユーザーのみが他のユーザーや名前空間を作成または削除できます。 +- **通常のユーザー:** このタイプのユーザーには最初は権限がないため、スーパーユーザーまたは `GRANT` 権限を持つ別のユーザーによって権限を付与する必要があります。 + +認証と認可を使用する場合、次の権限が利用できます。 + +- `SELECT` +- `INSERT` +- `UPDATE` +- `DELETE` +- `CREATE` +- `DROP` +- `TRUNCATE` +- `ALTER` +- `GRANT` + +権限の詳細については、[各タイプの操作に必要な権限](#各タイプの操作に必要な権限)を参照してください。 + +## 設定 + +このセクションでは、認証と認可に使用できる設定について説明します。 + +### ScalarDB Cluster ノードの設定 + +認証と認可を有効にするには、`scalar.db.cluster.auth.enabled` を `true` に設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|----------------------------------|-----------------------------|-----------| +| `scalar.db.cluster.auth.enabled` | 認証と認可が有効かどうか。 | `false` | + +以下を設定することもできます。 + +| 名前 | 説明 | デフォルト | +|----------------------------------------------------------------|---------------------------------------------------------------------------------------------------|-----------------| +| `scalar.db.cluster.auth.cache_expiration_time_millis` | 認証および認可情報のキャッシュ有効期限(ミリ秒単位)。 | `60000` (1分) | +| `scalar.db.cluster.auth.auth_token_expiration_time_minutes` | 認証および認可トークンの有効期限(分単位)。 | `1440` (1日) | +| `scalar.db.cluster.auth.auth_token_gc_thread_interval_minutes` | 認証および認可トークンのガベージコレクション (GC) スレッド間隔 (分単位)。 | 360(6時間) | +| `scalar.db.cluster.auth.pepper` | ハッシュ化の前にパスワードに追加されるシークレットの値。指定しない場合、パスワードはペッパーなしでハッシュ化されます。 | | + +:::note + +認証と認可を有効にする場合は、認証と認可によって内部的にパーティション間スキャンが実行されるため、システム名前空間 (デフォルトでは `scalardb`) の `scalar.db.cross_partition_scan.enabled` を `true` に設定する必要もあります。 + +::: + +### ScalarDB Cluster Java Client SDK 設定 + +クライアント側で認証と認可を有効にするには、`scalar.db.cluster.auth.enabled` を `true` に設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|----------------------------------|------------------------|----------| +| `scalar.db.cluster.auth.enabled` | 認証と認可が有効かどうか。 | `false` | + +[ScalarDB Cluster SQL クライアント設定](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定) セクションの設定に加えて、クライアントのユーザー名とパスワードを指定するために `scalar.db.sql.cluster_mode.username` と `scalar.db.sql.cluster_mode.password` も設定する必要があります。 + +| 名前 | 説明 | デフォルト | +|---------------------------------------|-----------------------------|---------| +| `scalar.db.sql.cluster_mode.username` | クライアントのユーザー名。 | | +| `scalar.db.sql.cluster_mode.password` | クライアントのパスワード。 | | + +## 初期ユーザー + +認証と認可を有効にすると、初期ユーザー `admin` が作成され、そのユーザーの初期パスワードは `admin` になります。このユーザーはスーパーユーザーであり、すべての権限を持ちます。このユーザーでログインし、必要に応じて他のユーザーを作成できます。 + +:::warning + +セキュリティ上の理由から、特に実稼働環境にデプロイする前に、初期ユーザーのパスワードを必ず変更してください。 + +::: + +## 各タイプの操作に必要な権限 + +次の表は、各タイプの操作に必要な権限を示しています。 + +### DDL + +| コマンド | スーパーユーザーが必要です | 必要な権限 | +|-------------------------------|-----------------------|---------------------| +| `CREATE NAMESPACE` | `true` | | +| `DROP NAMESPACE` | `true` | | +| `CREATE TABLE` | | `CREATE` | +| `DROP TABLE` | | `DROP` | +| `CREATE INDEX` | | `CREATE` | +| `DROP INDEX` | | `DROP` | +| `TRUNCATE TABLE` | | `TRUNCATE` | +| `ALTER TABLE` | | `ALTER` | +| `CREATE COORDINATOR TABLES` | `true` | | +| `DROP COORDINATOR TABLES` | `true` | | +| `TRUNCATE COORDINATOR TABLES` | `true` | | + +### DML + +| コマンド | スーパーユーザーが必要です | 必要な権限 | +|----------|------------------------|----------------------| +| `SELECT` | | `SELECT` | +| `INSERT` | | `INSERT` | +| `UPSERT` | | `INSERT` | +| `UPDATE` | | `SELECT` と `UPDATE` | +| `DELETE` | | `SELECT` と `DELETE` | + +### DCL + +| コマンド | スーパーユーザーが必要です | 必要な権限 | +|---------------|---------------------------------------------|-------------------------------------------------------------| +| `CREATE USER` | `true` | | +| `ALTER USER` | `true` (ユーザーは自分のパスワードを変更できます。) | | +| `DROP USER` | `true` | | +| `GRANT` | | `GRANT` (ユーザーは自分が持っている権限のみを付与できます。) | +| `REVOKE` | | `GRANT` (ユーザーは自分が持っている権限のみを取り消すことができます。) | + +## 制限事項 + +認証と認可で付与または取り消される権限には、いくつかの制限があります: + +- `INSERT` 権限と `UPDATE` 権限は、一緒に付与または取り消す必要があります。 +- ユーザーに `UPDATE` 権限または `DELETE` 権限を付与するには、対象ユーザーに `SELECT` 権限が必要です。 +- 対象ユーザーに `INSERT` 権限または `UPDATE` 権限がある場合、そのユーザーから `SELECT` 権限を取り消すことはできません。 + +## ワイヤ暗号化 + +認証と認可を有効にする場合は、ユーザー資格情報を保護するために、本番環境でワイヤ暗号化を有効にすることを強くお勧めします。ワイヤ暗号化の詳細については、[ScalarDB Cluster ワイヤ暗号化](encrypt-wire-communications.mdx)を参照してください。 + +## チュートリアル - ユーザーの認証と認可 + +このチュートリアルでは、認証と認可の使用方法を説明します。 + +## 前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10以降と [Docker Compose](https://docs.docker.com/compose/install/) V2以降 + +:::note + +このチュートリアルは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../requirements.mdx)を参照してください。 + +::: + + + +### 1. ScalarDB Cluster 設定ファイルを作成する + +次の設定ファイルを `scalardb-cluster-node.properties` として作成し、`` と `` を ScalarDB ライセンスキーとライセンスチェック証明書の値に置き換えます。ライセンスキーと証明書の詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + +```properties +scalar.db.storage=jdbc +scalar.db.contact_points=jdbc:postgresql://postgresql:5432/postgres +scalar.db.username=postgres +scalar.db.password=postgres +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.cross_partition_scan.enabled=true +scalar.db.sql.enabled=true + +# Enable authentication and authorization +scalar.db.cluster.auth.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +### 2. Docker Compose ファイルを作成する + +次の設定ファイルを `docker-compose.yaml` として作成します。 + +```yaml +services: + postgresql: + container_name: "postgresql" + image: "postgres:15" + ports: + - 5432:5432 + environment: + - POSTGRES_PASSWORD=postgres + healthcheck: + test: ["CMD-SHELL", "pg_isready || exit 1"] + interval: 1s + timeout: 10s + retries: 60 + start_period: 30s + + scalardb-cluster-standalone: + container_name: "scalardb-cluster-node" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + ports: + - 60053:60053 + - 9080:9080 + volumes: + - ./scalardb-cluster-node.properties:/scalardb-cluster/node/scalardb-cluster-node.properties + depends_on: + postgresql: + condition: service_healthy +``` + +### 3. PostgreSQL と ScalarDB Cluster を起動します + +次のコマンドを実行して、PostgreSQL と ScalarDB Cluster をスタンドアロンモードで起動します。 + +```console +docker compose up -d +``` + +### 4. ScalarDB Cluster に接続する + +ScalarDB Cluster に接続するために、このチュートリアルでは、ScalarDB Cluster に接続して SQL クエリを実行するツールである SQL CLI を使用します。SQL CLI は、[ScalarDB Releases ページ](https://github.com/scalar-labs/scalardb/releases)からダウンロードできます。 + +`scalardb-cluster-sql-cli.properties` という名前の設定ファイルを作成します。このファイルは、SQL CLI を使用して ScalarDB Cluster に接続するために使用されます。 + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost + +# Enable authentication and authorization +scalar.db.cluster.auth.enabled=true +``` + +次に、次のコマンドを実行して SQL CLI を起動します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +ユーザー名とパスワードをそれぞれ `admin` と `admin` と入力します。 + +これで、ScalarDB Cluster で認証と認可を有効にしてデータベースを使用する準備が整いました。 + +### 5. 名前空間とテーブルを作成する + +名前空間を作成します。 + +```sql +CREATE NAMESPACE ns1; + +CREATE NAMESPACE ns2; +``` + +次に、`ns1` 名前空間にテーブルを作成します。 + +```sql +CREATE TABLE ns1.tbl ( + id INT PRIMARY KEY, + col1 TEXT, + col2 INT); +``` + +### 6. ユーザーを作成する + +`user1` という名前のユーザーを作成します。 + +```sql +CREATE USER user1 WITH PASSWORD 'user1'; +``` + +ユーザーを確認するには、次のコマンドを実行します。 + +```sql +SHOW USERS; +``` + +```console ++----------+-------------+ +| username | isSuperuser | ++----------+-------------+ +| user1 | false | +| admin | true | ++----------+-------------+ +``` + +`user1` ユーザーが作成されたことがわかります。 + +### 7. 権限の付与 + +`ns1.tbl` テーブルで `user1` に `SELECT`、`INSERT`、および `UPDATE` 権限を付与します。 + +```sql +GRANT SELECT, INSERT, UPDATE ON ns1.tbl TO user1; +``` + +次に、`ns2` 名前空間の `user1` に `SELECT` 権限を付与します。 + +```sql +GRANT SELECT ON NAMESPACE ns2 TO user1; +``` + +権限を確認するには、次のコマンドを実行します。 + +```sql +SHOW GRANTS FOR user1; +``` + +```console ++---------+-----------+-----------+ +| name | type | privilege | ++---------+-----------+-----------+ +| ns2 | NAMESPACE | SELECT | +| ns1.tbl | TABLE | SELECT | +| ns1.tbl | TABLE | INSERT | +| ns1.tbl | TABLE | UPDATE | ++---------+-----------+-----------+ +``` + +`user1` に `ns.tbl` テーブルに対する `SELECT`、`INSERT`、`UPDATE` 権限と、`ns2` 名前空間に対する `SELECT` 権限が付与されていることがわかります。 + +### 8. `user1` としてログインする + +`user1` としてログインし、SQL ステートメントを実行します。 + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +ユーザー名とパスワードをそれぞれ `user1` と `user1` として入力します。 + +これで、`user1` として SQL ステートメントを実行できます。 + +### 9. DML ステートメントを実行する + +`user1` として次の `INSERT` ステートメントを実行します。 + +```sql +INSERT INTO ns1.tbl VALUES (1, 'a', 1); +``` + +次に、`user1` として次の `SELECT` ステートメントを実行します。 + +```sql +SELECT * FROM ns1.tbl; +``` + +```console ++----+------+------+ +| id | col1 | col2 | ++----+------+------+ +| 1 | a | 1 | ++----+------+------+ +``` + +`user1` が `INSERT` および `SELECT` ステートメントを実行できることがわかります。 + +次に、`user1` として次の `DELETE` ステートメントを実行してみてください。 + +```sql +DELETE FROM ns1.tbl WHERE id = 1; +``` + +```console +Error: Authorization error (PERMISSION_DENIED: SQL-10021: Access denied: You need the DELETE privilege on the table ns1.tbl to execute this operation) (state=SDB11,code=9911) +``` + +`user1` には `ns1.tbl` テーブルに対する `DELETE` 権限がないため、上記のエラーメッセージが表示されます。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-configurations.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-configurations.mdx new file mode 100644 index 00000000..1a1732e4 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-configurations.mdx @@ -0,0 +1,244 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster の設定 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + +このドキュメントでは、ScalarDB Cluster の設定について説明します。ScalarDB Cluster は複数のクラスターノードで構成されており、各クラスターノードを設定する必要があります。 + +## 基本設定 + +クラスターノードの基本設定は次のとおりです。 + +| 名前 | 説明 | デフォルト | +|-------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|----------------| +| `scalar.db.cluster.membership.type` | メンバーシップの種類。現在、`KUBERNETES` のみ指定できます。 | `KUBERNETES` | +| `scalar.db.cluster.membership.kubernetes.endpoint.namespace_name` | この設定は、`KUBERNETES` メンバーシップタイプ用です。[endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) の名前空間名。 | `default` | +| `scalar.db.cluster.membership.kubernetes.endpoint.name` | この設定は、`KUBERNETES` メンバーシップタイプ用です。メンバーシップ情報を取得するための [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) の名前。 | | +| `scalar.db.cluster.node.decommissioning_duration_secs` | 廃止期間(秒単位)。 | `30` | +| `scalar.db.cluster.node.grpc.max_inbound_message_size` | 受信可能な最大メッセージサイズ。 | gRPCのデフォルト値 | +| `scalar.db.cluster.node.grpc.max_inbound_metadata_size` | 受信できるメタデータの最大サイズ。 | gRPCのデフォルト値 | +| `scalar.db.cluster.node.port` | ScalarDB Cluster ノードのポート番号。 | `60053` | +| `scalar.db.cluster.node.prometheus_exporter_port` | Prometheus エクスポーターのポート番号。 | `9080` | +| `scalar.db.cluster.grpc.deadline_duration_millis` | gRPC の期限期間(ミリ秒単位)。 | `60000` (60秒) | +| `scalar.db.cluster.node.standalone_mode.enabled` | スタンドアロンモードが有効かどうか。スタンドアロンモードが有効になっている場合、メンバーシップ設定 (`scalar.db.cluster.membership.*`) は無視されることに注意してください。 | `false` | +| `scalar.db.metadata.cache_expiration_time_secs` | ScalarDB には、データベースへのリクエスト数を減らすためのメタデータキャッシュがあります。この設定では、キャッシュの有効期限を秒単位で指定します。`-1`を指定した場合は、キャッシュは期限切れになりません。 | `60` | +| `scalar.db.active_transaction_management.expiration_time_millis` | ScalarDB Cluster ノードは進行中のトランザクションを維持し、トランザクション ID を使用して再開できます。この設定では、このトランザクション管理機能の有効期限をミリ秒単位で指定します。 | `60000` (60秒) | +| `scalar.db.system_namespace_name` | 指定された名前空間名は ScalarDB によって内部的に使用されます。 | `scalardb` | +| `scalar.db.transaction.enabled` | トランザクション機能が有効かどうか。例えば、Embedding 機能のみを使用する場合、このプロパティをfalseに設定できます。 | `true` | + +## トランザクションマネージャーの設定 + +このセクションでは、トランザクションマネージャーの設定について説明します。ScalarDB は、コンセンサスコミットを使用してトランザクションを実行する方法と、非トランザクションストレージ操作を実行する方法を提供します。 + +### コンセンサスコミットを使用してトランザクションを実行する + +ScalarDB は、コンセンサスコミットと呼ばれる独自のトランザクションプロトコルを提供します。これは、ScalarDB のデフォルトのトランザクションマネージャータイプです。コンセンサスコミットトランザクションマネージャーを使用するには、ScalarDB プロパティファイルに次の内容を追加します。 + +```properties +scalar.db.transaction_manager=consensus-commit +``` + +:::note + +`scalar.db.transaction_manager` プロパティを指定しない場合は、`consensus-commit` がデフォルト値になります。 + +::: + +#### 基本設定 + +コンセンサスコミットトランザクションマネージャーでは、次の基本設定が利用可能です。 + +| 名前 | 説明 | デフォルト | +|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------| +| `scalar.db.transaction_manager` | `consensus-commit` を指定する必要があります。 | - | +| `scalar.db.consensus_commit.isolation_level` | コンセンサスコミットに使用される分離レベル。`SNAPSHOT` または `SERIALIZABLE` のいずれかを指定できます。 | `SNAPSHOT` | +| `scalar.db.consensus_commit.serializable_strategy` | コンセンサスコミットに使用されるシリアル化可能な戦略。`EXTRA_READ` または `EXTRA_WRITE` のいずれかを指定できます。`scalar.db.consensus_commit.isolation_level` プロパティで `SNAPSHOT` が指定されている場合、この設定は無視されます。 | `EXTRA_READ` | +| `scalar.db.consensus_commit.coordinator.namespace` | Coordinator テーブルの名前空間名。 | `coordinator` | +| `scalar.db.consensus_commit.include_metadata.enabled` | `true` に設定すると、`Get` および `Scan` 操作の結果にトランザクションメタデータが含まれます。特定のテーブルのトランザクションメタデータ列の詳細を表示するには、`DistributedTransactionAdmin.getTableMetadata()` メソッドを使用します。このメソッドは、トランザクションメタデータ列が追加されたテーブルメタデータを返します。この設定を使用すると、トランザクション関連の問題を調査するのに役立ちます。 | `false` | + +#### パフォーマンス関連の設定 + +コンセンサスコミットトランザクションマネージャーでは、次のパフォーマンス関連の設定が利用できます。 + +| 名前 | 説明 | デフォルト | +|----------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------| +| `scalar.db.consensus_commit.parallel_executor_count` | 並列実行のためのエグゼキュータ (スレッド) の数。この数値は、ScalarDB Cluster ノード内または ScalarDB プロセス内のトランザクション全体のスレッド数の合計を示します。 | `128` | +| `scalar.db.consensus_commit.parallel_preparation.enabled` | 準備フェーズが並行して実行されるかどうか。 | `true` | +| `scalar.db.consensus_commit.parallel_validation.enabled` | 検証フェーズ (`EXTRA_READ` 内) が並列で実行されるかどうか。 | `scalar.db.consensus_commit.parallel_commit.enabled` の値 | +| `scalar.db.consensus_commit.parallel_commit.enabled` | コミットフェーズが並列で実行されるかどうか。 | `true` | +| `scalar.db.consensus_commit.parallel_rollback.enabled` | ロールバックフェーズが並列で実行されるかどうか。 | `scalar.db.consensus_commit.parallel_commit.enabled` の値 | +| `scalar.db.consensus_commit.async_commit.enabled` | コミットフェーズが非同期で実行されるかどうか。 | `false` | +| `scalar.db.consensus_commit.async_rollback.enabled` | ロールバックフェーズが非同期に実行されるかどうか。 | `scalar.db.consensus_commit.async_commit.enabled` の値 | +| `scalar.db.consensus_commit.parallel_implicit_pre_read.enabled` | 暗黙的な事前読み取りが並列で実行されるかどうか。 | `true` | +| `scalar.db.consensus_commit.coordinator.group_commit.enabled` | トランザクション状態のコミットがバッチモードで実行されるかどうか。この機能は、2フェーズコミットインターフェイスでは使用できません。 | `false` | +| `scalar.db.consensus_commit.coordinator.group_commit.slot_capacity` | グループコミット機能のグループ内のスロットの最大数。値が大きいとグループコミットの効率は向上しますが、待ち時間が増加し、トランザクションの競合が発生する可能性も高くなります。[^1] | `20` | +| `scalar.db.consensus_commit.coordinator.group_commit.group_size_fix_timeout_millis` | グループ内のスロットのサイズを固定するためのタイムアウト。値が大きいとグループコミットの効率が向上しますが、待ち時間が増加し、トランザクションの競合が発生する可能性も高くなります。[^1] | `40` | +| `scalar.db.consensus_commit.coordinator.group_commit.delayed_slot_move_timeout_millis` | 遅延スロットをグループから別の分離グループに移動して、元のグループが遅延トランザクションの影響を受けないようにするためのタイムアウト。値が大きいとグループコミットの効率が向上しますが、待ち時間が増加し、トランザクションの競合が発生する可能性も高くなります。[^1] | `1200` | +| `scalar.db.consensus_commit.coordinator.group_commit.old_group_abort_timeout_millis` | 進行中の古いグループをアボートするためのタイムアウト。値が小さいと、積極的なアボートによってリソースの消費量が減りますが、長時間実行されるトランザクションで不要なアボートが発生する可能性も高くなります。 | `60000` | +| `scalar.db.consensus_commit.coordinator.group_commit.timeout_check_interval_millis` | グループコミット関連のタイムアウトをチェックする間隔。 | `20` | +| `scalar.db.consensus_commit.coordinator.group_commit.metrics_monitor_log_enabled` | グループコミットのメトリックが定期的にログに記録されるかどうか。 | `false` | + +#### 基盤となるストレージまたはデータベースの設定 + +Consensus Commit にはストレージ抽象化レイヤーがあり、複数の基盤となるストレージをサポートしています。`scalar.db.storage` プロパティを使用してストレージ実装を指定できます。 + +データベースを選択して、各ストレージで使用可能な設定を確認します。 + + + + JDBC データベースでは次の設定を使用できます。 + + | 名前 | 説明 | デフォルト | + |-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| + | `scalar.db.storage` | `jdbc` を指定する必要があります。 | - | + | `scalar.db.contact_points` | JDBC 接続 URL。 | | + | `scalar.db.username` | データベースにアクセスするためのユーザー名。 | | + | `scalar.db.password` | データベースにアクセスするためのパスワード。 | | + | `scalar.db.jdbc.connection_pool.min_idle` | 接続プール内のアイドル接続の最小数。 | `20` | + | `scalar.db.jdbc.connection_pool.max_idle` | 接続プール内でアイドル状態のままにできる接続の最大数。 | `50` | + | `scalar.db.jdbc.connection_pool.max_total` | 接続プールで同時にアクティブにできるアイドル接続と借用接続の最大合計数。制限がない場合は負の値を使用します。 | `100` | + | `scalar.db.jdbc.prepared_statements_pool.enabled` | このプロパティを `true` に設定すると、準備されたステートメントのプールが有効になります。 | `false` | + | `scalar.db.jdbc.prepared_statements_pool.max_open` | ステートメントプールから同時に割り当てることができるオープンステートメントの最大数。制限がない場合は負の値を使用します。 | `-1` | + | `scalar.db.jdbc.isolation_level` | JDBC の分離レベル。`READ_UNCOMMITTED`、`READ_COMMITTED`、`REPEATABLE_READ`、または `SERIALIZABLE` を指定できます。 | 基盤データベース固有 | + | `scalar.db.jdbc.table_metadata.connection_pool.min_idle` | テーブルメタデータの接続プール内のアイドル接続の最小数。 | `5` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_idle` | テーブルメタデータの接続プール内でアイドル状態のままにできる接続の最大数。 | `10` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_total` | テーブルメタデータの接続プールで同時にアクティブにできるアイドル接続と借用接続の最大合計数。制限がない場合は負の値を使用します。 | `25` | + | `scalar.db.jdbc.admin.connection_pool.min_idle` | 管理者の接続プール内のアイドル接続の最小数。 | `5` | + | `scalar.db.jdbc.admin.connection_pool.max_idle` | 管理者の接続プール内でアイドル状態のままにできる接続の最大数。 | `10` | + | `scalar.db.jdbc.admin.connection_pool.max_total` | 管理者の接続プールで同時にアクティブにできるアイドル接続と借用接続の最大合計数。制限がない場合は負の値を使用します。 | `25` | + +:::note + +SQLite3 を JDBC データベースとして使用している場合は、`scalar.db.contact_points` を次のように設定する必要があります。 + +```properties +scalar.db.contact_points=jdbc:sqlite:?busy_timeout=10000 +``` + +他の JDBC データベースとは異なり、[SQLite3 doesn't fully support concurrent access](https://www.sqlite.org/lang_transaction.html)。[`SQLITE_BUSY`](https://www.sqlite.org/rescode.html#busy) によって内部的に頻繁に発生するエラーを回避するには、[`busy_timeout`](https://www.sqlite.org/c3ref/busy_timeout.html) パラメータを設定することをお勧めします。 + +::: + + +DynamoDB では次の設定が利用可能です。 + + | 名前 | 説明 | デフォルト | + |---------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------| + | `scalar.db.storage` | `dynamo` を指定する必要があります。 | - | + | `scalar.db.contact_points` | ScalarDB が通信する AWS リージョン (例: `us-east-1`)。 | | + | `scalar.db.username` | AWS とやり取りするユーザーを識別するために使用される AWS アクセスキー。 | | + | `scalar.db.password` | AWS と対話するユーザーを認証するために使用される AWS シークレットアクセスキー。 | | + | `scalar.db.dynamo.endpoint_override` | ScalarDB が通信する Amazon DynamoDB エンドポイント。これは主に、AWS サービスではなくローカルインスタンスでのテストに使用されます。 | | + | `scalar.db.dynamo.namespace.prefix` | ユーザー名前空間とメタデータ名前空間名のプレフィックス。AWS では単一の AWS リージョン内で一意のテーブル名を持つ必要があるため、単一の AWS リージョン内で複数の ScalarDB 環境 (開発、本番など) を使用する場合に便利です。 | | + + + CosmosDB for NoSQL では次の設定が利用可能です。 + + | 名前 | 説明 | デフォルト | + |--------------------------------------|----------------------------------------------------------------------------------------------------------|----------| + | `scalar.db.storage` | `cosmos` を指定する必要があります。 | - | + | `scalar.db.contact_points` | ScalarDB が通信する NoSQL エンドポイント用の Azure Cosmos DB。 | | + | `scalar.db.password` | Azure Cosmos DB for NoSQL にアクセスするための認証を実行するために使用されるマスターキーまたは読み取り専用キーのいずれか。 | | + | `scalar.db.cosmos.consistency_level` | Cosmos DB 操作に使用される一貫性レベル。`STRONG` または `BOUNDED_STALENESS` を指定できます。 | `STRONG` | + + + Cassandra では次の設定が利用可能です。 + + | 名前 | 説明 | デフォルト | + |-----------------------------------------|-----------------------------------------------------------------------|------------| + | `scalar.db.storage` | `cassandra` を指定する必要があります。 | - | + | `scalar.db.contact_points` | カンマで区切られた連絡先。 | | + | `scalar.db.contact_port` | すべての連絡先ポイントのポート番号。 | | + | `scalar.db.username` | データベースにアクセスするためのユーザー名。 | | + | `scalar.db.password` | データベースにアクセスするためのパスワード。 | | + + + +##### マルチストレージのサポート + +ScalarDB は、複数のストレージ実装を同時に使用することをサポートしています。`scalar.db.storage` プロパティの値として `multi-storage` を指定すると、複数のストレージを使用できます。 + +複数のストレージの使用の詳細については、[マルチストレージトランザクション](../multi-storage-transactions.mdx)を参照してください。 + +##### パーティション間スキャン設定 + +以下で説明するようにパーティション間スキャンオプションを有効にすると、`Scan` 操作でパーティション全体のすべてのレコードを取得できます。さらに、`cross_partition_scan.filtering` と `cross_partition_scan.ordering` をそれぞれ有効にすることで、パーティション間 `Scan` 操作で任意の条件と順序を指定できます。現在、順序付けオプション付きのパーティション間スキャンは、JDBC データベースでのみ使用できます。フィルタリングと順序付けを有効にするには、`scalar.db.cross_partition_scan.enabled` を `true` に設定する必要があります。 + +パーティション間スキャンの使用方法の詳細については、[スキャン操作](../api-guide.mdx#スキャン操作)を参照してください。 + +:::warning + +非 JDBC データベースの場合、トランザクションはより低い分離レベル (つまり、`SNAPSHOT`) で実行される可能性があるため、`SERIALIAZABLE` 分離レベルでパーティション間スキャンを有効にすることはお勧めしません。非 JDBC データベースを使用する場合は、トランザクションの一貫性が重要でない場合にのみ、自己責任でパーティション間スキャンを使用してください。 + +::: + +| 名前 | 説明 | デフォルト | +|----------------------------------------------------|-----------------------------------------------|---------| +| `scalar.db.cross_partition_scan.enabled` | パーティション間スキャンを有効にします。 | `false` | +| `scalar.db.cross_partition_scan.filtering.enabled` | パーティション間スキャンでフィルタリングを有効にします。 | `false` | +| `scalar.db.cross_partition_scan.ordering.enabled` | パーティション間スキャンで順序付けを有効にします。 | `false` | + +### 非トランザクションストレージ操作を実行する + +非トランザクションストレージ操作を実行するには、`scalar.db.transaction_manager` プロパティを `single-crud-operation` に設定する必要があります。 + +```properties +scalar.db.transaction_manager=single-crud-operation +``` + +また、[基盤となるストレージまたはデータベースの設定](#基盤となるストレージまたはデータベースの設定)の説明に従って、基盤となるストレージまたはデータベースを設定する必要があります。 + +## ScalarDB Cluster GraphQL 設定 + +ScalarDB Cluster GraphQL の設定は次のとおりです。 + +| 名前 | 説明 | デフォルト | +|-----------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| +| `scalar.db.graphql.enabled` | ScalarDB Cluster GraphQL が有効かどうか。 | `false` | +| `scalar.db.graphql.port` | GraphQL サーバーのポート番号。 | `8080` | +| `scalar.db.graphql.path` | GraphQL エンドポイントの URL のパスコンポーネント。 | `/graphql` | +| `scalar.db.graphql.namespaces` | GraphQL サーバーがスキーマを生成するテーブルの名前空間のコンマ区切りリスト。指定しない場合、GraphQL サーバーは、すべての ScalarDB 管理名前空間内のすべてのテーブルのスキーマを生成します。 | | +| `scalar.db.graphql.graphiql` | GraphQL サーバーが [GraphiQL](https://github.com/graphql/graphiql) IDE を提供するかどうか。 | `true` | +| `scalar.db.graphql.schema_checking_interval_millis` | ScalarDB スキーマに変更が検出された場合に GraphQL サーバーが GraphQL スキーマを再構築する間隔 (ミリ秒単位)。 | `30000` (30秒) | + +### サーバーの実行中に ScalarDB スキーマを作成または変更する + +GraphQL スキーマはサーバーの起動時に静的に構築されるため、ScalarDB スキーマが変更された場合 (たとえば、テーブルが追加、変更、または削除された場合)、対応する GraphQL スキーマは再構築されない限り変更を反映しません。これに対処するために、GraphQL サーバーは、定期的なチェックとオンデマンドチェックの2つのメカニズムを提供します。 + +#### 定期的なチェックを実行する + +サーバーは、ScalarDB スキーマに変更が発生したかどうかを定期的にチェックし、必要に応じて対応する GraphQL スキーマを再構築します。デフォルトでは、チェックは30秒ごとに行われますが、間隔は `scalar.db.graphql.schema_checking_interval_millis` プロパティを使用して設定できます。 + +定期的なチェックを実行する必要がない場合は、プロパティ値を `-1` に設定して無効にすることができます。 + +#### オンデマンドチェックを実行する + +また、HTTP API の `/update-graphql-schema` エンドポイントに POST リクエストを実行して、サーバーに ScalarDB スキーマの変更をチェックし、必要に応じて対応する GraphQL スキーマを再構築するように要求することもできます。 + +たとえば、HTTP API が `localhost:8080` で実行されていて、`scalar.db.graphql.path` プロパティが `/graphql` に設定されている場合、次のコマンドを実行してこのエンドポイントを呼び出すことができます。 + +```console +curl -X POST http://localhost:8080/graphql/update-graphql-schema +``` + +## ScalarDB Cluster SQL 設定 + +ScalarDB Cluster SQL の設定は次のとおりです。 + +| 名前 | 説明 | デフォルト | +|------------------------------------------|----------------------------------------------------------------------------------------------------------|---------------| +| `scalar.db.sql.enabled` | ScalarDB Cluster SQL が有効かどうか。 | `false` | +| `scalar.db.sql.statement_cache.enabled` | ステートメントキャッシュを有効にします。 | `false` | +| `scalar.db.sql.statement_cache.size` | キャッシュされたステートメントの最大数。 | `100` | +| `scalar.db.sql.default_transaction_mode` | デフォルトのトランザクションモード。`TRANSACTION` または `TWO_PHASE_COMMIT_TRANSACTION` を設定できます。 | `TRANSACTION` | +| `scalar.db.sql.default_namespace_name` | デフォルトの名前空間名。SQL ステートメントで名前空間名を指定しない場合は、この値が使用されます。 | | diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-grpc-api-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-grpc-api-guide.mdx new file mode 100644 index 00000000..2c8c1e30 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-grpc-api-guide.mdx @@ -0,0 +1,212 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster gRPC API ガイド + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; + + + +このドキュメントでは、ScalarDB Cluster gRPC API について説明します。 + + + +ScalarDB Cluster は、内部で gRPC API を使用する Java API を提供します。 + +Java または JVM 言語を使用する場合は、ScalarDB Cluster gRPC API を直接使用する代わりに、Java API を使用できます。 + +Java API の詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx)を参照してください。 + +ScalarDB Cluster gRPC API のサービスとメッセージの詳細については、`scalardb-cluster.proto` ファイルの定義を参照してください。商用ライセンスを持つ ScalarDB Cluster ユーザーで、`scalardb-cluster.proto` ファイルが必要な場合は、[お問い合わせ](https://www.scalar-labs.com/support)ください。 + +ScalarDB Cluster gRPC API は、次のサービスで構成されています。 + +- `scalardb.cluster.rpc.v1.DistributedTransaction`: ScalarDB Cluster に分散トランザクション機能を提供します。 +- `scalardb.cluster.rpc.v1.TwoPhaseCommitTransaction`: ScalarDB Cluster に2フェーズコミットトランザクション機能を提供します。 +- `scalardb.cluster.rpc.v1.DistributedTransactionAdmin`: 包括的な管理操作を提供します。 + +次のセクションでは、各サービスの使用方法について説明します。 + +## ScalarDB Cluster gRPC API でのエラー処理の概要 + +各サービスの使用方法を説明する前に、このセクションでは ScalarDB Cluster gRPC API でのエラー処理の仕組みについて説明します。 + +ScalarDB Cluster gRPC API は、エラー処理に [Richer error model](https://grpc.io/docs/guides/error/#richer-error-model) を採用しています。このモデルにより、サーバーは1つ以上の protobuf メッセージとして表現される追加のエラー詳細を返すことができ、クライアントはそれを利用できるようになります。ScalarDB Cluster gRPC API は、[standard set of error message types](https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto) の1つである `google.rpc.ErrorInfo` を使用し、追加のエラー詳細を `ErrorInfo` フィールドに格納します。 + +`ErrorInfo` には次のフィールドがあります: + +- `reason`: エラーの簡単な説明を提供する文字列。次のセクションでは、各サービスにおける `reason` の可能な値について説明します。 +- `domain`: エラーの原因を示す文字列。ScalarDB Cluster gRPC API では、この文字列は常に `com.scalar.db.cluster` に設定されます。 +- `metadata`: 特定のエラーのメタデータのマップ。ScalarDB Cluster gRPC API では、エラーがトランザクションに関連している場合、マップに `transactionId` キーを持つトランザクション ID が配置されます。 + +エラーが発生した場合は、gRPC レスポンスの `google.rpc.Status` から `ErrorInfo` を取得できますが、取得方法はプログラミング言語によって異なります。 + +特定のプログラミング言語で `ErrorInfo` を取得する方法については、適切なドキュメントを参照してください。 + +## `DistributedTransaction` サービスの使用方法 + +`DistributedTransaction` サービスは次の RPC を提供します: + +- `Begin`: トランザクションを開始します。 +- `Get`: レコードを取得します。 +- `Scan`: レコードをスキャンします。 +- `Put`: レコードを配置します。 +- `Delete`: レコードを削除します。 +- `Mutate` 複数のレコードを変更 (配置および削除) します。 +- `Commit`: トランザクションをコミットします。 +- `Rollback`: トランザクションをロールバックします。 + +まず、`Begin` を呼び出してトランザクションを開始します。 + +次に、`Get` と `Scan` を呼び出してレコードを読み取り、`Put` と `Mutate` を呼び出してレコードを書き込み、`Delete` と `Mutate` を呼び出してレコードを削除します。 + +トランザクションを終了するには、`Commit` を呼び出します。あるいは、トランザクションがコミットされる前にいつでも `Rollback` を呼び出してキャンセルできます。`Begin` を呼び出すと、応答でトランザクション ID を受け取ります。これを使用して、`Get`、`Scan`、`Put`、`Delete`、`Mutate`、`Commit`、および `Rollback` を呼び出すことができます。 + +`Begin` を呼び出すときに、オプションでトランザクション ID を指定できます。トランザクション ID を指定する場合、ユーザーは ID の一意性を保証する責任があります。トランザクション ID を指定しない場合は、ScalarDB Cluster がトランザクションのトランザクション ID を生成します。 + +RPC リクエストごとに `RequestHeader` を設定する必要があります。`RequestHeader` には、リクエストのホップ数を制限している `hop_limit` フィールドが含まれています。`hop_limit` の目的は、クラスター内での無限ループを防ぐことです。リクエストが別のクラスターノードに転送されるたびに、`hop_limit` は1つ減少します。`hop_limit` が0に達すると、リクエストは拒否されます。 + +### エラー処理 + +以下の表は、`DistributedTransaction` サービスの各 RPC におけるステータスコードと `ErrorInfo` の `reason` の可能な値を示しています。 + +| RPC | ステータスコード | `ErrorInfo` の `reason` | 説明 | +|--------------------------------|---------------------|----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Begin | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Begin | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Begin | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Begin | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Get, Scan, Put, Delete, Mutate | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Get, Scan, Put, Delete, Mutate | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Get, Scan, Put, Delete, Mutate | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合は、トランザクションを最初から再試行してください。 | +| Get, Scan, Put, Delete, Mutate | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Get, Scan, Put, Delete, Mutate | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Get, Scan, Put, Delete, Mutate | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Put, Delete, Mutate | FAILED_PRECONDITION | UNSATISFIED_CONDITION | 突然変異条件が満たされていません。 | +| Commit | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Commit | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Commit | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合は、トランザクションを最初から再試行してください。 | +| Commit | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Commit | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Commit | INTERNAL | UNKNOWN_TRANSACTION_STATUS | トランザクションのステータスは不明です (トランザクションが正常にコミットされたかどうかは不明です)。この状況では、トランザクションが正常にコミットされたかどうかを確認し、そうでない場合は再試行する必要があります。トランザクションステータスを判別する責任はユーザーにあります。トランザクションステータステーブルを作成し、他のアプリケーションデータと連動して更新すると、テーブル自体からトランザクションのステータスを判別できるため、便利です。 | +| Commit | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Rollback | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Rollback | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Rollback | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。ロールバックの場合、トランザクションは自動的に期限切れになるため、トランザクションを再試行する必要はありません。 | +| Rollback | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。ロールバックの場合、トランザクションは自動的に期限切れになるため、トランザクションを再試行する必要はありません。 | +| Rollback | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | + +エラーが発生した場合は、`Begin` の場合を除き、トランザクションをロールバックする必要があります。その後、再試行によって解決できるエラーについては、トランザクションを最初から再試行できます。 + +上記のエラーの他に、gRPC ライブラリによって返されるエラーが発生する場合があります。これらの場合、応答には `ErrorInfo` は含まれません。詳細については、[gRPC ドキュメント](https://grpc.io/docs/guides/error/#error-status-codes)を参照してください。 + +gRPC では、RPC ごとに期限を設定できます。期限を超えると、`DEADLINE_EXCEEDED` エラーが表示されます。一般に、RPC が `Begin` または `Commit` でない限り、この状況ではトランザクションをロールバックする必要があります。`Commit` の場合は `UNKNOWN_TRANSACTION_STATUS` (トランザクションが正常にコミットされたかどうか不明) と同等の状況となり、同様にエラーを処理する必要があります。 + +## `TwoPhaseCommitTransaction` サービスの使用方法 + +`TwoPhaseCommitTransaction` サービスは次の RPC を提供します: + +- `Begin`: トランザクションを開始します。 +- `Join`: トランザクションに参加します。 +- `Get`: レコードを取得します。 +- `Scan`: レコードをスキャンします。 +- `Put`: レコードを配置します。 +- `Delete`: レコードを削除します。 +- `Mutate`: 複数のレコードを変更 (配置および削除) します。 +- `Prepare`: トランザクションを準備します。 +- `Validate`: トランザクションを検証します。 +- `Commit`: トランザクションをコミットします。 +- `Rollback`: トランザクションをロールバックします。 + +まず、コーディネータープロセスの場合は、`Begin` を呼び出してトランザクションを開始します。あるいは、参加プロセスの場合は、`Join` を呼び出して、コーディネーターがすでに開始しているトランザクションに参加できます。次に、`Get` と `Scan` を呼び出してレコードを読み取り、`Put` と `Mutate` を呼び出してレコードを書き込み、`Delete` と `Mutate` を呼び出してレコードを削除できます。トランザクションを確定するには、`Prepare`、`Validate`、`Commit` の順に呼び出します。または、トランザクションがコミットされる前であればいつでも `Rollback` を呼び出してトランザクションをキャンセルできます。`Begin` または `Join` を呼び出すと、応答でトランザクション ID が返されます。これを使用して、`Get`、`Scan`、`Put`、`Delete`、`Mutate`、`Prepare`、`Validate`、`Commit`、`Rollback` を呼び出すことができます。 + +`Begin` を呼び出すときに、オプションでトランザクション ID を指定できます。トランザクション ID を指定する場合、ID の一意性を保証するのはユーザーの責任です。トランザクション ID を指定しない場合、ScalarDB Cluster はトランザクションのトランザクション ID を生成します。 + +RPC リクエストごとに `RequestHeader` を設定する必要があります。`RequestHeader` には、リクエストのホップ数を制限している `hop_limit` フィールドが含まれています。`hop_limit` の目的は、クラスター内での無限ループを防ぐことです。リクエストが別のクラスターノードに転送されるたびに、`hop_limit` は1つ減ります。`hop_limit` が0に達すると、リクエストは拒否されます。 + +### エラー処理 + +次の表は、`TwoPhaseCommitTransaction` サービスの各 RPC のステータスコードと `ErrorInfo` の `reason` の可能な値を示しています。 + +| RPC | ステータスコード | `ErrorInfo` の `reason` | 説明 | +|--------------------------------|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Begin, Join | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Begin, Join | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Begin, Join | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Begin, Join | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Get, Scan, Put, Delete, Mutate | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Get, Scan, Put, Delete, Mutate | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Get, Scan, Put, Delete, Mutate | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。これは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合は、トランザクションを最初から再試行してください。 | +| Get, Scan, Put, Delete, Mutate | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Get, Scan, Put, Delete, Mutate | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Get, Scan, Put, Delete, Mutate | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Put, Delete, Mutate | FAILED_PRECONDITION | UNSATISFIED_CONDITION | 突然変異条件が満たされていません。 | +| Prepare, Validate | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Prepare, Validate | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Prepare, Validate | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合は、トランザクションを最初から再試行してください。 | +| Prepare, Validate | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Prepare, Validate | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Prepare, Validate | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Commit | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Commit | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Commit | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合は、トランザクションを最初から再試行してください。 | +| Commit | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Commit | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Commit | INTERNAL | UNKNOWN_TRANSACTION_STATUS | トランザクションのステータスは不明です (トランザクションが正常にコミットされたかどうかは不明です)。この状況では、トランザクションが正常にコミットされたかどうかを確認し、そうでない場合は再試行する必要があります。トランザクションステータスを判別する責任はユーザーにあります。トランザクションステータステーブルを作成し、他のアプリケーションデータと連動して更新すると、テーブル自体からトランザクションのステータスを判別できるため、便利です。 | +| Commit | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Rollback | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Rollback | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Rollback | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。ロールバックの場合、トランザクションは自動的に期限切れになるため、トランザクションを再試行する必要はありません。 | +| Rollback | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。ロールバックの場合、トランザクションは自動的に期限切れになるため、トランザクションを再試行する必要はありません。 | +| Rollback | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | + +エラーが発生した場合は、`Begin` または `Join` の場合を除き、トランザクションをロールバックする必要があります。その後、再試行によって解決できるエラーについては、トランザクションを最初から再試行できます。 + +上記のエラーの他に、gRPC ライブラリによって返されるエラーが発生する場合があります。これらの場合、応答には `ErrorInfo` は含まれません。詳細については、[gRPC ドキュメント](https://grpc.io/docs/guides/error/#error-status-codes)を参照してください。 + +gRPC では、各 RPC に期限を設定できます。期限を超えると、`DEADLINE_EXCEEDED` エラーが表示されます。一般に、RPC が `Begin`、`Join`、または `Commit` でない限り、この状況ではトランザクションをロールバックする必要があります。`Commit` の場合、状況は `UNKNOWN_TRANSACTION_STATUS` (トランザクションが正常にコミットされたかどうか不明) と同等であり、同じ方法でエラーを処理する必要があります。 + +## `DistributedTransactionAdmin` サービスの使用方法 + +`DistributedTransactionAdmin` サービスは、次の RPC を提供します。 + +- `CreateNamespace`: 名前空間を作成します。 +- `DropNamespace`: 名前空間を削除します。 +- `NamespaceExists`: 指定された名前空間が存在するかどうかを返します。 +- `CreateTable`: テーブルを作成します。 +- `DropTable`: テーブルを削除します。 +- `TruncateTable`: テーブルを切り捨てます。 +- `TableExists`: 指定されたテーブルが存在するかどうかを返します。 +- `CreateIndex`: インデックスを作成します。 +- `DropIndex`: インデックスを削除します。 +- `IndexExists`: 指定されたインデックスが存在するかどうかを返します。 +- `RepairNamespace`: 不明な状態にある可能性がある名前空間を修復します。 +- `RepairTable`: 不明な状態にある可能性がある名前空間を修復します。 +- `AddNewColumnToTable`: テーブルに新しい列を追加します。 +- `CreateCoordinatorTables`: Coordinator テーブルを作成します。 +- `DropCoordinatorTables`: Coordinator テーブルを削除します。 +- `TruncateCoordinatorTables`: Coordinator テーブルを切り捨てます。 +- `CoordinatorTablesExist`: Coordinator テーブルが存在するかどうかを返します。 +- `RepairCoordinatorTables`: Coordinator テーブルを修復します。 +- `GetTableMetadata`: 指定されたテーブルのテーブルメタデータを返します。 +- `GetNamespaceTableNames`: 指定された名前空間内のテーブルを返します。 +- `GetNamespaceNames`: ScalarDB によって作成された既存の名前空間名を返します。 +- `ImportTable`: ScalarDB によって管理されていない既存のテーブルをインポートします。 +- `Upgrade`: ScalarDB 環境をアップグレードして、最新バージョンの ScalarDB API をサポートします。 + +### エラー処理 + +以下の表は、`DistributedTransactionAdmin` サービスのすべての RPC のステータスコードと `ErrorInfo` の `reason` の可能な値を示しています。 + +| ステータスコード | `ErrorInfo` の `reason` | 説明 | +|---------------------|----------------------------|------------------------------| +| INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| FAILED_PRECONDITION | ILLEGAL_STATE | が無効な状態で呼び出されました。 | +| INTERNAL | INTERNAL_ERROR | 操作が失敗しました。 | + +上記のエラー以外にも、gRPC ライブラリによって返されるエラーが発生する場合があります。このような場合、応答には `ErrorInfo` は含まれません。詳細については、[gRPC ドキュメント](https://grpc.io/docs/guides/error/#error-status-codes)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide.mdx new file mode 100644 index 00000000..33e0e8a6 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide.mdx @@ -0,0 +1,185 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster SQL gRPC API ガイド + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; + + + +このドキュメントでは、ScalarDB Cluster SQL gRPC API について説明します。 + + + +ScalarDB Cluster SQL は、内部で gRPC API を使用する Java API を提供します。Java または JVM 言語を使用する場合は、ScalarDB Cluster SQL gRPC API を直接使用する代わりに、Java API を使用できます。Java API の詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx)を参照してください。 + +ScalarDB Cluster SQL gRPC API のサービスとメッセージの詳細については、`scalardb-cluster-sql.proto` ファイルの定義を参照してください。商用ライセンスを持つ ScalarDB Cluster ユーザーで、`scalardb-cluster-sql.proto` ファイルが必要な場合は、[お問い合わせ](https://www.scalar-labs.com/support)ください。 + +ScalarDB Cluster SQL gRPC API は、次のサービスで構成されています: + +- `scalardb.cluster.rpc.v1.sql.SqlTransaction`: ScalarDB Cluster SQL のトランザクション機能を提供します。 +- `scalardb.cluster.rpc.v1.sql.SqlTwoPhaseCommitTransaction`: ScalarDB Cluster SQL の2フェーズコミットトランザクション機能を提供します。 +- `scalardb.cluster.rpc.v1.sql.Metadata`: ScalarDB Cluster SQL のメタデータビューを提供します。 + +次のセクションでは、各サービスの使用方法について説明します。 + +## ScalarDB Cluster SQL gRPC API でのエラー処理の概要 + +各サービスの使用方法を説明する前に、このセクションでは、ScalarDB Cluster SQL gRPC API でのエラー処理の仕組みについて説明します。 + +ScalarDB Cluster SQL gRPC API は、エラー処理に [Richer error model](https://grpc.io/docs/guides/error/#richer-error-model) を採用しています。 + +このモデルにより、サーバーは1つ以上の protobuf メッセージとして表現される追加のエラー詳細を返すことができ、クライアントはそれを利用できるようになります。 + +ScalarDB Cluster SQL gRPC API は、[standard set of error message types](https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto) の1つである `google.rpc.ErrorInfo` を使用し、追加のエラー詳細を `ErrorInfo` フィールドに格納します。 + +`ErrorInfo` には次のフィールドがあります: + +- `reason`: エラーの簡単な説明を提供する文字列。次のセクションでは、各サービスにおける `reason` の可能な値について説明します。 +- `domain`: エラーの原因を示す文字列。ScalarDB Cluster SQL gRPC API では、この文字列は常に `com.scalar.db.cluster.sql` に設定されます。 +- `metadata`: 特定のエラーのメタデータのマップ。ScalarDB Cluster SQL gRPC API では、エラーがトランザクションに関連している場合、マップに `transactionId` キーを持つトランザクション ID が配置されます。 + +エラーが発生した場合は、gRPC レスポンスの `google.rpc.Status` から `ErrorInfo` を取得できますが、その方法はプログラミング言語によって異なります。 + +特定のプログラミング言語で `ErrorInfo` を取得する方法については、適切なドキュメントを参照してください。 + +## `SqlTransaction` サービスの使用方法 + +`SqlTransaction` サービスは次の RPC を提供します: + +- `Begin`: トランザクションを開始します。 +- `Execute`: SQL ステートメントを実行します。 +- `Commit`: トランザクションをコミットします。 +- `Rollback`: トランザクションをロールバックします。 + +まず、`Begin` を呼び出してトランザクションを開始します。その後、`Execute` を呼び出してレコードの読み取り、書き込み、削除を行うことができます。トランザクションを終了するには、`Commit` を呼び出します。 + +または、トランザクションがコミットされる前であればいつでも `Rollback` を呼び出してキャンセルできます。`Begin` を呼び出すと、レスポンスでトランザクション ID を受け取ります。この ID を使用して、`Execute`、`Commit`、および `Rollback` を呼び出すことができます。 + +また、トランザクション ID なしで `Execute` を呼び出して、ワンショットトランザクションを実行することもできます。この場合、トランザクションは実行後に自動的にコミットされます。このメソッドを使用して、DDL ステートメントを実行することもできます。サポートされている SQL ステートメントの詳細については、[ScalarDB SQL 文法](../scalardb-sql/grammar.mdx)を参照してください。ただし、`Execute` は DML ステートメントと DDL ステートメントのみをサポートすることに注意してください。 + +`Begin` を呼び出すときに、オプションでトランザクション ID を指定できます。トランザクション ID を指定する場合、ユーザーは ID の一意性を保証する責任があります。トランザクション ID を指定しない場合、ScalarDB Cluster はトランザクションのトランザクション ID を生成します。 + +各 RPC リクエストに対して `RequestHeader` を設定する必要があります。`RequestHeader` には、リクエストのホップ数を制限する `hop_limit` フィールドが含まれています。`hop_limit` の目的は、クラスター内での無限ループを防ぐことです。リクエストが別のクラスターノードに転送されるたびに、`hop_limit` は1つ減ります。`hop_limit` が0に達すると、リクエストは拒否されます。 + +### エラー処理 + +以下の表は、`SqlTransaction` サービスの各 RPC におけるステータスコードと `ErrorInfo` の `reason` の可能な値を示しています。 + +| RPC | ステータスコード | `ErrorInfo` の `reason` | 説明 | +|----------|---------------------|----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Begin | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Begin | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Begin | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Begin | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Execute | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Execute | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Execute | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合、トランザクションを最初から再試行してください。 | +| Execute | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Execute | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Execute | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Commit | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Commit | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Commit | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合、トランザクションを最初から再試行してください。 | +| Commit | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Commit | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Commit | INTERNAL | UNKNOWN_TRANSACTION_STATUS | トランザクションのステータスは不明です (トランザクションが正常にコミットされたかどうかは不明です)。この状況では、トランザクションが正常にコミットされたかどうかを確認し、そうでない場合は再試行する必要があります。トランザクションステータスを判別する責任はユーザーにあります。トランザクションステータステーブルを作成し、他のアプリケーションデータと連動して更新すると、テーブル自体からトランザクションのステータスを判別できるため、便利です。 | +| Commit | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Rollback | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Rollback | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Rollback | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。ロールバックの場合、トランザクションは自動的に期限切れになるため、トランザクションを再試行する必要はありません。 | +| Rollback | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。ロールバックの場合、トランザクションは自動的に期限切れになるため、トランザクションを再試行する必要はありません。 | +| Rollback | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | + +エラーが発生した場合は、`Begin` の場合を除き、トランザクションをロールバックする必要があります。その後、再試行によって解決できるエラーについては、トランザクションを最初から再試行できます。 + +上記のエラーの他に、gRPC ライブラリによって返されるエラーが発生する場合があります。これらの場合、応答には `ErrorInfo` は含まれません。詳細については、[gRPC ドキュメント](https://grpc.io/docs/guides/error/#error-status-codes)を参照してください。 + +gRPC では、RPC ごとに期限を設定できます。期限を超えると、`DEADLINE_EXCEEDED` エラーが表示されます。一般に、RPC が `Begin` または `Commit` でない限り、この状況ではトランザクションをロールバックする必要があります。`Commit` の場合は `UNKNOWN_TRANSACTION_STATUS` (トランザクションが正常にコミットされたかどうか不明) と同等の状況となり、同様にエラーを処理する必要があります。 + +## `SqlTwoPhaseCommitTransaction` サービスの使用方法 + +`SqlTwoPhaseCommitTransaction` サービスは次の RPC を提供します: + +- `Begin`: トランザクションを開始します。 +- `Join`: トランザクションに参加します。 +- `Execute`: SQL ステートメントを実行します。 +- `Prepare`: トランザクションを準備します。 +- `Validate`: トランザクションを検証します。 +- `Commit`: トランザクションをコミットします。 +- `Rollback`: トランザクションをロールバックします。 + +まず、コーディネータープロセスの場合は、`Begin` を呼び出してトランザクションを開始します。または、参加者プロセスの場合は、`Join` を呼び出して、コーディネーターが既に開始しているトランザクションに参加できます。その後、`Execute` を呼び出してレコードの読み取り、書き込み、および削除を行うことができます。 +トランザクションを確定するには、`Prepare`、`Validate`、`Commit` の順に呼び出します。または、トランザクションがコミットされる前であればいつでも `Rollback` を呼び出してキャンセルできます。`Begin` または `Join` を呼び出すと、応答でトランザクション ID が返されます。これを使用して、`Execute`、`Prepare`、`Validate`、`Commit`、および `Rollback` を呼び出すことができます。 + +また、トランザクション ID なしで `Execute` を呼び出して、ワンショットトランザクションを実行することもできます。この場合、トランザクションは実行後に自動的にコミットされます。この方法を使用して、DDL ステートメントを実行することもできます。 サポートされている SQL ステートメントの詳細については、[ScalarDB SQL 文法](../scalardb-sql/grammar.mdx)を参照してください。ただし、`Execute` は DML ステートメントと DDL ステートメントのみをサポートすることに注意してください。 + +`Begin` を呼び出すときに、オプションでトランザクション ID を指定できます。トランザクション ID を指定する場合、ID の一意性を保証するのはユーザーの責任です。トランザクション ID を指定しない場合、ScalarDB Cluster はトランザクションのトランザクション ID を生成します。 + +RPC リクエストごとに `RequestHeader` を設定する必要があります。`RequestHeader` には、リクエストのホップ数を制限している `hop_limit` フィールドが含まれています。`hop_limit` の目的は、クラスター内での無限ループを防ぐことです。リクエストが別のクラスターノードに転送されるたびに、`hop_limit` は1つ減ります。`hop_limit` が0に達すると、リクエストは拒否されます。 + +### エラー処理 + +次の表は、`SqlTwoPhaseCommitTransaction` サービスの各 RPC のステータスコードと `ErrorInfo` の `reason` の可能な値を示しています。 + +| RPC | ステータスコード | `ErrorInfo` の `reason` | 説明 | +|-------------------|---------------------|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Begin, Join | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Begin, Join | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Begin, Join | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Begin, Join | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Execute | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Execute | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Execute | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合、トランザクションを最初から再試行してください。 | +| Execute | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Execute | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Execute | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Prepare, Validate | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Prepare, Validate | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Prepare, Validate | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合、トランザクションを最初から再試行してください。 | +| Prepare, Validate | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Prepare, Validate | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Prepare, Validate | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Commit | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Commit | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Commit | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。このエラーは、トランザクションの有効期限が切れたか、クラスタートポロジの変更によりルーティング情報が更新されたことを示します。この場合、トランザクションを最初から再試行してください。 | +| Commit | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。これは、クラスターノード間のルーティング情報が矛盾している場合に発生します。通常、このエラーは短時間で解決されるため、このエラーが発生してからしばらく経ってから、トランザクションを最初から再試行できます。 | +| Commit | FAILED_PRECONDITION | TRANSACTION_CONFLICT | トランザクションの競合が発生しました。このエラーが発生した場合は、トランザクションを最初から再試行してください。 | +| Commit | INTERNAL | UNKNOWN_TRANSACTION_STATUS | トランザクションのステータスは不明です (トランザクションが正常にコミットされたかどうかは不明です)。この状況では、トランザクションが正常にコミットされたかどうかを確認し、そうでない場合は再試行する必要があります。トランザクションステータスを判別する責任はユーザーにあります。トランザクションステータステーブルを作成し、他のアプリケーションデータと連動して更新すると、テーブル自体からトランザクションのステータスを判別できるため、便利です。 | +| Commit | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | +| Rollback | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です。 | +| Rollback | FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| Rollback | NOT_FOUND | TRANSACTION_NOT_FOUND | 指定されたトランザクション ID に関連付けられたトランザクションが見つかりませんでした。ロールバックの場合、トランザクションは自動的に期限切れになるため、トランザクションを再試行する必要はありません。 | +| Rollback | INTERNAL | HOP_LIMIT_EXCEEDED | ホップ制限を超えました。ロールバックの場合、トランザクションは自動的に期限切れになるため、トランザクションを再試行する必要はありません。 | +| Rollback | INTERNAL | INTERNAL_ERROR | 一時的または非一時的障害のため、操作が失敗しました。トランザクションを最初から再試行することはできますが、原因が非一時的である場合、トランザクションは失敗する可能性があります。 | + +エラーが発生した場合は、`Begin` または `Join` の場合を除き、トランザクションをロールバックする必要があります。その後、再試行によって解決できるエラーについては、トランザクションを最初から再試行できます。 + +上記のエラーの他に、gRPC ライブラリによって返されるエラーが発生する場合があります。これらの場合、応答には `ErrorInfo` は含まれません。詳細については、[gRPC ドキュメント](https://grpc.io/docs/guides/error/#error-status-codes)を参照してください。 + +gRPC では、各 RPC に期限を設定できます。期限を超えると、`DEADLINE_EXCEEDED` エラーが表示されます。一般に、RPC が `Begin`、`Join`、または `Commit` でない限り、この状況ではトランザクションをロールバックする必要があります。`Commit` の場合は `UNKNOWN_TRANSACTION_STATUS` (トランザクションが正常にコミットされたかどうか不明) と同等の状況となり、同様にエラーを処理する必要があります。 + +## `Metadata` サービスの使用方法 + +`Metadata` サービスは次の RPC を提供します: + +- `GetNamespaceMetadata`: 指定された名前空間の名前空間メタデータを取得します。 +- `ListTableMetadataInNamespace`: 指定された名前空間内のテーブルのテーブルメタデータを取得します。 +- `GetTableMetadata`: 指定されたテーブルのテーブルメタデータを取得します。 +- `ListNamespaceMetadata`: 名前空間メタデータのリストを取得します。 + +### エラー処理 + +以下の表は、`Metadata` サービスのすべての RPC のステータスコードと `ErrorInfo` の `reason` の可能な値を示しています: + +| ステータスコード | `ErrorInfo` の `reason` | 説明 | +|---------------------|----------------------------|---------------------------------| +| INVALID_ARGUMENT | ILLEGAL_ARGUMENT | 要求メッセージ内の引数が無効です | +| FAILED_PRECONDITION | ILLEGAL_STATE | RPC が無効な状態で呼び出されました。 | +| INTERNAL | INTERNAL_ERROR | 操作が失敗しました。 | + +上記のエラー以外にも、gRPC ライブラリによって返されるエラーが発生する場合があります。このような場合、応答には `ErrorInfo` は含まれません。詳細については、[gRPC ドキュメント](https://grpc.io/docs/guides/error/#error-status-codes)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-status-codes.mdx new file mode 100644 index 00000000..7b68f95e --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/scalardb-cluster-status-codes.mdx @@ -0,0 +1,562 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster エラーコード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB Cluster のエラーコードの一覧を示します。 + +## エラーコードのクラスと説明 + +| クラス | 説明 | +|:-------------------|:--------------------------| +| `DB-CLUSTER-1xxxx` | ユーザーエラーカテゴリのエラー | +| `DB-CLUSTER-2xxxx` | 同時実行エラーカテゴリのエラー | +| `DB-CLUSTER-3xxxx` | 内部エラーカテゴリのエラー | + +## `DB-CLUSTER-1xxxx` ステータスコード + +以下は、ユーザーエラーカテゴリのステータスコードとメッセージです。 + +### `DB-CLUSTER-10000` + +**メッセージ** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-CLUSTER-10001` + +**メッセージ** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-CLUSTER-10002` + +**メッセージ** + +```markdown +The user does not exist. User: %s +``` + +### `DB-CLUSTER-10003` + +**メッセージ** + +```markdown +ClusterConfig is not specified +``` + +### `DB-CLUSTER-10004` + +**メッセージ** + +```markdown +The get type is unspecified +``` + +### `DB-CLUSTER-10005` + +**メッセージ** + +```markdown +The get type is unrecognized +``` + +### `DB-CLUSTER-10006` + +**メッセージ** + +```markdown +The value of the column is not set. Column: %s +``` + +### `DB-CLUSTER-10007` + +**メッセージ** + +```markdown +The scan type is unspecified +``` + +### `DB-CLUSTER-10008` + +**メッセージ** + +```markdown +The scan type is unrecognized +``` + +### `DB-CLUSTER-10009` + +**メッセージ** + +```markdown +The order is unspecified +``` + +### `DB-CLUSTER-10010` + +**メッセージ** + +```markdown +The order is unrecognized +``` + +### `DB-CLUSTER-10011` + +**メッセージ** + +```markdown +The clustering order is unspecified +``` + +### `DB-CLUSTER-10012` + +**メッセージ** + +```markdown +The clustering order is unrecognized +``` + +### `DB-CLUSTER-10013` + +**メッセージ** + +```markdown +The put condition type is unspecified +``` + +### `DB-CLUSTER-10014` + +**メッセージ** + +```markdown +The put condition type is unrecognized +``` + +### `DB-CLUSTER-10015` + +**メッセージ** + +```markdown +The delete condition type is unspecified +``` + +### `DB-CLUSTER-10016` + +**メッセージ** + +```markdown +The delete condition type is unrecognized +``` + +### `DB-CLUSTER-10017` + +**メッセージ** + +```markdown +The operator is unspecified +``` + +### `DB-CLUSTER-10018` + +**メッセージ** + +```markdown +The operator is unrecognized +``` + +### `DB-CLUSTER-10019` + +**メッセージ** + +```markdown +The mutation is not set +``` + +### `DB-CLUSTER-10020` + +**メッセージ** + +```markdown +The data type is unspecified +``` + +### `DB-CLUSTER-10021` + +**メッセージ** + +```markdown +The data type is unrecognized +``` + +### `DB-CLUSTER-10022` + +**メッセージ** + +```markdown +The user option is unspecified +``` + +### `DB-CLUSTER-10023` + +**メッセージ** + +```markdown +The user option is unrecognized +``` + +### `DB-CLUSTER-10024` + +**メッセージ** + +```markdown +The privilege is unspecified +``` + +### `DB-CLUSTER-10025` + +**メッセージ** + +```markdown +The privilege is unrecognized +``` + +### `DB-CLUSTER-10026` + +**メッセージ** + +```markdown +The username is not set +``` + +### `DB-CLUSTER-10027` + +**メッセージ** + +```markdown +This feature is not supported in ScalarDB Cluster +``` + +### `DB-CLUSTER-10028` + +**メッセージ** + +```markdown +The property 'scalar.db.contact_points' must not be empty +``` + +### `DB-CLUSTER-10029` + +**メッセージ** + +```markdown +The property 'scalar.db.contact_points' must be prefixed with 'indirect:' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10030` + +**メッセージ** + +```markdown +The format of the property 'scalar.db.contact_points' for direct-kubernetes client mode is 'direct-kubernetes:/' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10031` + +**メッセージ** + +```markdown +The property 'scalar.db.sql.cluster_mode.contact_points' must not be empty +``` + +### `DB-CLUSTER-10032` + +**メッセージ** + +```markdown +The property 'scalar.db.sql.cluster_mode.contact_points' must be prefixed with 'indirect:' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10033` + +**メッセージ** + +```markdown +The format of the property 'scalar.db.sql.cluster_mode.contact_points' for direct-kubernetes client mode is 'direct-kubernetes:/' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10034` + +**メッセージ** + +```markdown +ClusterNodeManagerFactory is not specified +``` + +### `DB-CLUSTER-10035` + +**メッセージ** + +```markdown +The update condition type is unspecified +``` + +### `DB-CLUSTER-10036` + +**メッセージ** + +```markdown +The update condition type is unrecognized +``` + +### `DB-CLUSTER-10037` + +**メッセージ** + +```markdown +The two-phase commit interface is not supported +``` + +### `DB-CLUSTER-10038` + +**メッセージ** + +```markdown +Membership is not specified +``` + +### `DB-CLUSTER-10039` + +**メッセージ** + +```markdown +The policy state is unspecified +``` + +### `DB-CLUSTER-10040` + +**メッセージ** + +```markdown +The policy state is unrecognized +``` + +### `DB-CLUSTER-10041` + +**メッセージ** + +```markdown +The access mode is unspecified +``` + +### `DB-CLUSTER-10042` + +**メッセージ** + +```markdown +The access mode is unrecognized +``` + +### `DB-CLUSTER-10043` + +**メッセージ** + +```markdown +The service does not exist. Service Class: %s +``` + +### `DB-CLUSTER-10044` + +**メッセージ** + +```markdown +The policy does not exist. Policy: %s +``` + +### `DB-CLUSTER-10045` + +**メッセージ** + +```markdown +The property 'scalar.db.embedding.client.contact_points' must not be empty +``` + +### `DB-CLUSTER-10046` + +**メッセージ** + +```markdown +The property 'scalar.db.embedding.client.contact_points' must be prefixed with 'indirect:' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10047` + +**メッセージ** + +```markdown +The format of the property 'scalar.db.embedding.client.contact_points' for direct-kubernetes client mode is 'direct-kubernetes:/' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10048` + +**メッセージ** + +```markdown +The embeddings must be provided +``` + +### `DB-CLUSTER-10049` + +**メッセージ** + +```markdown +Only one embedding can be added with an embedding ID +``` + +### `DB-CLUSTER-10050` + +**メッセージ** + +```markdown +Text segments cannot be provided when adding an embedding with an embedding ID +``` + +### `DB-CLUSTER-10051` + +**メッセージ** + +```markdown +Both embedding IDs and a filter cannot be provided +``` + +### `DB-CLUSTER-10052` + +**メッセージ** + +```markdown +Unsupported embedding store type. Type: %s +``` + +### `DB-CLUSTER-10053` + +**メッセージ** + +```markdown +Unsupported embedding model type. Type: %s +``` + +### `DB-CLUSTER-10054` + +**メッセージ** + +```markdown +The filter is not set +``` + +### `DB-CLUSTER-10055` + +**メッセージ** + +```markdown +Unsupported metadata value type. Type: %s +``` + +### `DB-CLUSTER-10056` + +**メッセージ** + +```markdown +The metadata value is not set +``` + +## `DB-CLUSTER-2xxxx` ステータスコード + +以下は、同時実行エラーカテゴリのステータスコードとメッセージです。 + +### `DB-CLUSTER-20000` + +**メッセージ** + +```markdown +The hop limit is exceeded +``` + +### `DB-CLUSTER-20001` + +**メッセージ** + +```markdown +A transaction associated with the specified transaction ID is not found. The transaction might have expired, or the cluster node that handled the transaction might have been restarted. Transaction ID: %s +``` + +## `DB-CLUSTER-3xxxx` ステータスコード + +以下は、内部エラーカテゴリのステータスコードとメッセージです。 + +### `DB-CLUSTER-30000` + +**メッセージ** + +```markdown +Getting local IP addresses failed +``` + +### `DB-CLUSTER-30001` + +**メッセージ** + +```markdown +Getting a cluster node object from the cache failed. Cluster Node IP Address: %s +``` + +### `DB-CLUSTER-30002` + +**メッセージ** + +```markdown +The ring is empty +``` + +### `DB-CLUSTER-30003` + +**メッセージ** + +```markdown +Getting the Kubernetes API client failed +``` + +### `DB-CLUSTER-30004` + +**メッセージ** + +```markdown +Reading the Kubernetes endpoint failed. Namespace: %s; Name: %s; Code: %d; Response Headers: %s; Response Body: %s +``` + +### `DB-CLUSTER-30005` + +**メッセージ** + +```markdown +Configuring TLS failed +``` + +### `DB-CLUSTER-30006` + +**メッセージ** + +```markdown +No nearest cluster nodes are found +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx new file mode 100644 index 00000000..1f276e3c --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx @@ -0,0 +1,258 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster をローカルにデプロイする方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; + + + +このガイドでは、テスト環境向けに特別に設計されたローカル Kubernetes クラスターで Helm Chart を使用して ScalarDB Cluster をデプロイする方法について説明します。 + +## 前提条件 + +- [Docker](https://www.docker.com/get-started/) 20.10以降と [Docker Compose](https://docs.docker.com/compose/install/) V2以降 +- Kubernetes クラスター ([minikube](https://minikube.sigs.k8s.io/docs/start/) または [kind](https://kind.sigs.k8s.io/docs/user/quick-start/#installation) のいずれか) +- [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) +- [Helm](https://helm.sh/docs/intro/install/) + + + +## 作成するもの + +以下に示すように、ローカル Kubernetes クラスターに次のコンポーネントをデプロイします。 + +``` ++----------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes クラスター] | +| | +| [ポッド] [ポッド] [ポッド] | +| | +| +-------+ | +| +---> | Envoy | ---+ | +| | +-------+ | | +| | | | +| +---------+ | +-------+ | +--------------------+ | +| | サービス | ---+---> | Envoy | ---+---------> | サービス | ---+ | +| | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | | +| +---------+ | | +--------------------+ | +------------------------+ | +| | +-------+ | | +---> | ScalarDB Cluster ノード | ---+ | +| +---> | Envoy | ---+ | | +------------------------+ | | +| +-------+ | | | | +| | | +------------------------+ | +------------+ | +| +---+---> | ScalarDB Cluster ノード | ---+---> | PostgreSQL | | +| | | +------------------------+ | +------------+ | +| | | | | +| | | +------------------------+ | | +| | +---> | ScalarDB Cluster ノード | ---+ | +| | +------------------------+ | +| +-----------------------------+ | | +| | サービス | ---+ | +| | (ScalarDB Cluster GraphQL) | | +| +-----------------------------+ | +| | ++----------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## ステップ 1. PostgreSQL コンテナを起動する + +ScalarDB Cluster は、バックエンドデータベースとして何らかのデータベースシステムを使用する必要があります。このガイドで使用するデータベースは PostgreSQL です。 + +次のようにして、Kubernetes クラスターに PostgreSQL をデプロイできます。 + +1. 次のコマンドを実行して、Bitnami Helm リポジトリを追加します。 + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +2. 次のコマンドを実行して PostgreSQL をデプロイします。 + + ```console + helm install postgresql-scalardb-cluster bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +3. 次のコマンドを実行して、PostgreSQL コンテナが実行されているかどうかを確認します。 + + ```console + kubectl get pod + ``` + + 次の出力が表示されます。 + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 17s + ``` + +## ステップ 2. Helm Chart を使用して Kubernetes クラスターに ScalarDB Cluster をデプロイする + +1. 次のコマンドを実行して Scalar Helm Charts リポジトリを追加します。 + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +2. ライセンスキーと証明書を環境変数として設定します。ライセンスキーがない場合は、[お問い合わせ](https://www.scalar-labs.com/contact)ください。`` の値の詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx)を参照してください。 + + ```console + SCALAR_DB_CLUSTER_LICENSE_KEY='' + SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM='' + ``` + +3. 次のコマンドを実行して、ScalarDB Cluster のカスタム値ファイル (`scalardb-cluster-custom-values.yaml`) を作成します。 + + ```console + cat << 'EOF' > scalardb-cluster-custom-values.yaml + envoy: + enabled: true + service: + type: "LoadBalancer" + + scalardbCluster: + + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium" + + scalardbClusterNodeProperties: | + # ScalarDB Cluster configurations + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} + + # Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb-cluster.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DB_CLUSTER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DB_CLUSTER_POSTGRES_PASSWORD} + + # For ScalarDB Cluster GraphQL tutorial. + scalar.db.graphql.enabled=true + + # For ScalarDB Cluster SQL tutorial. + scalar.db.sql.enabled=true + + ### License key configurations + scalar.db.cluster.node.licensing.license_key=${env:SCALAR_DB_CLUSTER_LICENSE_KEY} + scalar.db.cluster.node.licensing.license_check_cert_pem=${env:SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} + graphql: + enabled: true + service: + type: "LoadBalancer" + + secretName: "scalardb-credentials-secret" + EOF + ``` + +:::note + + このガイドでは、ScalarDB Cluster GraphQL および Envoy のサービスタイプは `LoadBalancer` に設定されています。 + +::: + +4. 資格情報とライセンスキーを含む `scalardb-credentials-secret` という名前のシークレットリソースを作成します。 + + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DB_CLUSTER_LICENSE_KEY="${SCALAR_DB_CLUSTER_LICENSE_KEY}" \ + --from-file=SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +5. ScalarDB Cluster のチャートバージョンを設定します。 + + ```console + SCALAR_DB_CLUSTER_VERSION=3.15.4 + SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +6. ScalarDB Cluster をデプロイします。 + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f scalardb-cluster-custom-values.yaml --version ${SCALAR_DB_CLUSTER_CHART_VERSION} -n default + ``` + +7. ScalarDB Cluster ポッドがデプロイされているかどうかを確認します。 + + ```console + kubectl get pod + ``` + + 次の出力が表示されます。 + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 84s + scalardb-cluster-envoy-59899dc588-477tg 1/1 Running 0 35s + scalardb-cluster-envoy-59899dc588-dpvhx 1/1 Running 0 35s + scalardb-cluster-envoy-59899dc588-lv9hx 1/1 Running 0 35s + scalardb-cluster-node-866c756c79-5v2tk 1/1 Running 0 35s + scalardb-cluster-node-866c756c79-9zhq5 1/1 Running 0 35s + scalardb-cluster-node-866c756c79-t6v86 1/1 Running 0 35s + ``` + + ScalarDB Cluster Node Pod と Envoy Pod が適切にデプロイされている場合、各 Pod の `STATUS` は `Running` になります。 + +6. 次のコマンドを実行して、ScalarDB Cluster のサービスリソースがデプロイされているかどうかを確認します。 + + ```console + kubectl get svc + ``` + + 次の出力が表示されます。 + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 260d + postgresql-scalardb-cluster ClusterIP 10.110.97.40 5432/TCP 86s + postgresql-scalardb-cluster-hl ClusterIP None 5432/TCP 86s + scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 49s + scalardb-cluster-envoy-metrics ClusterIP 10.111.131.189 9001/TCP 49s + scalardb-cluster-graphql LoadBalancer 10.105.74.214 localhost 8080:30514/TCP 49s + scalardb-cluster-headless ClusterIP None 60053/TCP 49s + scalardb-cluster-metrics ClusterIP 10.110.132.22 9080/TCP 49s + ``` + + ScalarDB Cluster と Envoy のサービスリソースが適切にデプロイされている場合、`CLUSTER-IP` 列にプライベート IP アドレスが表示されます。 + + :::note + + `scalardb-cluster-headless` には `CLUSTER-IP` アドレスがありません。 + + ::: + + また、`TYPE` が `LoadBalancer` に設定されている ScalarDB Cluster GraphQL (`scalardb-cluster-graphql`) のサービスリソースと Envoy (`scalardb-cluster-envoy`) のサービスリソースに割り当てられた `EXTERNAL-IP` アドレスも確認できます。 + + また、環境から `LoadBalancer` サービスにアクセスする方法は、Kubernetes ディストリビューションごとに異なります。例: + + - minikube を使用している場合は、[`minikube tunnel` コマンド](https://minikube.sigs.k8s.io/docs/commands/tunnel/)を使用できます。 + - kind を使用している場合は、[Cloud Provider KIND](https://kind.sigs.k8s.io/docs/user/loadbalancer/) を使用できます。 + + `LoadBalancer` サービスにアクセスする方法の詳細については、使用している Kubernetes ディストリビューションの公式ドキュメントを参照してください。 + +## すべてのリソースを削除する + +以下のコマンドを実行すると、このガイドで作成したすべてのリソースを削除できます。 + +```console +helm uninstall scalardb-cluster postgresql-scalardb-cluster +``` + +## 詳細 + +ScalarDB Cluster の他のユースケースについて詳しく知るには、次のチュートリアルをお試しください。 + +- [ScalarDB Cluster をはじめよう](getting-started-with-scalardb-cluster.mdx) +- [ScalarDB Cluster GraphQL をはじめよう](getting-started-with-scalardb-cluster-graphql.mdx) +- [JDBC 経由の ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/standalone-mode.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/standalone-mode.mdx new file mode 100644 index 00000000..2ad601ed --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-cluster/standalone-mode.mdx @@ -0,0 +1,239 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Cluster スタンドアロンモード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; + + + +Kubernetes クラスターをセットアップし、Helm Chart を使用してその上に ScalarDB Cluster をデプロイする代わりに、ScalarDB Cluster をスタンドアロンモードで実行できます。これにより、開発プロセスとテストプロセスが簡素化されます。この主な使用例は、ローカルマシン上の Docker を介して ScalarDB Cluster をスタンドアロンモードで起動し、開発とテストに使用する場合です。 + +ScalarDB Cluster をスタンドアロンモードで実行するには、`scalar.db.cluster.node.standalone_mode.enabled` プロパティを `true` に設定する必要があります。 + +```properties +scalar.db.cluster.node.standalone_mode.enabled=true +``` + +## Docker Compose で ScalarDB Cluster をスタンドアロンモードで実行 + +このセクションでは、Docker Compose で ScalarDB Cluster をスタンドアロンモードで起動する方法について説明します。 + + + +### ScalarDB サンプルリポジトリのクローンを作成する + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、必要なファイルが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode/ +``` + +### ScalarDB Cluster 用にデータベースをセットアップする + +データベースを選択し、指示に従って ScalarDB Cluster 用に設定します。 + +ScalarDB がサポートするデータベースの一覧については、[データベース](../requirements.mdx#databases)を参照してください。 + + + +

MySQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で MySQL を実行できます。 + + MySQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d mysql + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の MySQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

PostgreSQL をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で PostgreSQL を実行できます。 + + PostgreSQL を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d postgres + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の PostgreSQL のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Oracle Database をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Oracle Database を実行できます。 + + Oracle Database を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d oracle + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Oracle データベースのプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

SQL Server をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で SQL Server を実行できます。 + + SQL Server を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d sqlserver + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の SQL Server のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Amazon DynamoDB Local を実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Amazon DynamoDB Local を実行できます。 + + Amazon DynamoDB Local を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d dynamodb + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Amazon DynamoDB Local のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + Azure Cosmos DB for NoSQL を使用するには、Azure アカウントが必要です。Azure アカウントがない場合は、[Azure Cosmos DB アカウントを作成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/quickstart-portal#create-account)にアクセスしてください。 + +

Cosmos DB for NoSQL を設定する

+ + [既定の整合性レベルを構成する](https://learn.microsoft.com/ja-jp/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level)の公式ドキュメントに従って、**既定の整合性レベル** を **強力** に設定します。 + +

ScalarDB Cluster を設定する

+ + 次の手順では、ローカル環境に JDK が適切にインストールおよび設定されており、Azure で Cosmos DB for NoSQL アカウントが適切に設定されていることを前提としています。 + + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。説明に従って、`scalar.db.contact_points` と `scalar.db.password` の値を必ず変更してください。 + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +Azure Cosmos DB アカウントの主キーまたはセカンダリキーを `scalar.db.password` の値として使用できます。 + +::: +
+ +

Cassandra をローカルで実行する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの `docker-compose.yaml` ファイルを使用して、Docker Compose で Apache Cassandra を実行できます。 + + Apache Cassandra を起動するには、次のコマンドを実行します。 + + ```console + docker compose up -d cassandra + ``` + +

ScalarDB Cluster を設定する

+ + `scalardb-samples/scalardb-cluster-standalone-mode` ディレクトリの **scalardb-cluster-node.properties** ファイルには、ScalarDB Cluster のデータベース設定が含まれています。**scalardb-cluster-node.properties** ファイル内の Cassandra のプロパティのコメントを解除して、設定が次のようになるようにしてください。 + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +### ライセンスキーを設定する + +設定ファイル `scalardb-cluster-node.properties` で、ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) を設定します。詳細については、[製品ライセンスキーの設定方法](../scalar-licensing/index.mdx) を参照してください。 + +### スタンドアロンモードで ScalarDB Cluster を起動する + +スタンドアロンモードで ScalarDB Cluster を起動するには、次のコマンドを実行します。 + +:::note + +ScalarDB Cluster のその他の設定を変更する場合は、以下のコマンドを実行する前に `scalardb-cluster-node.properties` ファイルを更新してください。 + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## ScalarDB Cluster Java API のクライアント設定 + +`indirect` クライアントモードを使用して、スタンドアロンモードで ScalarDB Cluster に接続できます。ScalarDB Cluster Java API のクライアント設定の詳細については、[Java API を使用した ScalarDB Cluster の開発者ガイド](developer-guide-for-scalardb-cluster-with-java-api.mdx) を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-core-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-core-status-codes.mdx new file mode 100644 index 00000000..adf41c2b --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-core-status-codes.mdx @@ -0,0 +1,2064 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Core エラーコード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB Core のエラーコードの一覧を示します。 + +## エラーコードのクラスと説明 + +| クラス | 説明 | +|:----------------|:---------------------------------------------------------| +| `DB-CORE-1xxxx` | ユーザーエラーカテゴリのエラー | +| `DB-CORE-2xxxx` | 同時実行エラーカテゴリのエラー | +| `DB-CORE-3xxxx` | 内部エラーカテゴリのエラー | +| `DB-CORE-4xxxx` | 不明なトランザクションステータスエラーカテゴリのエラー | + +## `DB-CORE-1xxxx` ステータスコード + +以下は、ユーザーエラーカテゴリのステータスコードとメッセージです。 + +### `DB-CORE-10000` + +**メッセージ** + +```markdown +Only a single-column index is supported. Operation: %s +``` + +### `DB-CORE-10001` + +**メッセージ** + +```markdown +The column of the specified index key is not indexed. Operation: %s +``` + +### `DB-CORE-10002` + +**メッセージ** + +```markdown +The index key is not properly specified. Operation: %s +``` + +### `DB-CORE-10003` + +**メッセージ** + +```markdown +Clustering keys cannot be specified when using an index. Operation: %s +``` + +### `DB-CORE-10004` + +**メッセージ** + +```markdown +Orderings cannot be specified when using an index. Operation: %s +``` + +### `DB-CORE-10005` + +**メッセージ** + +```markdown +The limit cannot be negative. Operation: %s +``` + +### `DB-CORE-10006` + +**メッセージ** + +```markdown +Cross-partition scan is not enabled. Operation: %s +``` + +### `DB-CORE-10007` + +**メッセージ** + +```markdown +Cross-partition scan ordering is not enabled. Operation: %s +``` + +### `DB-CORE-10008` + +**メッセージ** + +```markdown +Cross-partition scan filtering is not enabled. Operation: %s +``` + +### `DB-CORE-10009` + +**メッセージ** + +```markdown +The specified projection is not found. Projection: %s, Operation: %s +``` + +### `DB-CORE-10010` + +**メッセージ** + +```markdown +The clustering key boundary is not properly specified. Operation: %s +``` + +### `DB-CORE-10011` + +**メッセージ** + +```markdown +The start clustering key is not properly specified. Operation: %s +``` + +### `DB-CORE-10012` + +**メッセージ** + +```markdown +The end clustering key is not properly specified. Operation: %s +``` + +### `DB-CORE-10013` + +**メッセージ** + +```markdown +Orderings are not properly specified. Operation: %s +``` + +### `DB-CORE-10014` + +**メッセージ** + +```markdown +The specified ordering column is not found. Ordering: %s, Operation: %s +``` + +### `DB-CORE-10015` + +**メッセージ** + +```markdown +The condition is not properly specified. Operation: %s +``` + +### `DB-CORE-10016` + +**メッセージ** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-CORE-10017` + +**メッセージ** + +```markdown +The column value is not properly specified. Column: %s, Operation: %s +``` + +### `DB-CORE-10018` + +**メッセージ** + +```markdown +The mutations are empty +``` + +### `DB-CORE-10019` + +**メッセージ** + +```markdown +Mutations that span multiple partitions are not supported. Mutations: %s +``` + +### `DB-CORE-10020` + +**メッセージ** + +```markdown +The partition key is not properly specified. Operation: %s +``` + +### `DB-CORE-10021` + +**メッセージ** + +```markdown +The clustering key is not properly specified. Operation: %s +``` + +### `DB-CORE-10022` + +**メッセージ** + +```markdown +The authentication and authorization feature is not enabled. To use this feature, you must enable it. Note that this feature is supported only in the ScalarDB Enterprise edition +``` + +### `DB-CORE-10023` + +**メッセージ** + +```markdown +This condition is not allowed for the PutIf operation. Condition: %s +``` + +### `DB-CORE-10024` + +**メッセージ** + +```markdown +This condition is not allowed for the DeleteIf operation. Condition: %s +``` + +### `DB-CORE-10025` + +**メッセージ** + +```markdown +Operator must be LIKE or NOT_LIKE. Operator: %s +``` + +### `DB-CORE-10026` + +**メッセージ** + +```markdown +An escape character must be a string of a single character or an empty string +``` + +### `DB-CORE-10027` + +**メッセージ** + +```markdown +The LIKE pattern must not be null +``` + +### `DB-CORE-10028` + +**メッセージ** + +```markdown +The LIKE pattern must not include only an escape character +``` + +### `DB-CORE-10029` + +**メッセージ** + +```markdown +The LIKE pattern must not end with an escape character +``` + +### `DB-CORE-10030` + +**メッセージ** + +```markdown +The column %s does not exist +``` + +### `DB-CORE-10031` + +**メッセージ** + +```markdown +This operation is not supported when getting records of a database without using an index +``` + +### `DB-CORE-10032` + +**メッセージ** + +```markdown +This operation is not supported when getting records of a database by using an index +``` + +### `DB-CORE-10033` + +**メッセージ** + +```markdown +This operation is not supported when scanning all the records of a database or scanning records of a database by using an index +``` + +### `DB-CORE-10034` + +**メッセージ** + +```markdown +This operation is supported only when scanning records of a database by using an index +``` + +### `DB-CORE-10035` + +**メッセージ** + +```markdown +This operation is not supported when scanning records of a database by using an index +``` + +### `DB-CORE-10037` + +**メッセージ** + +```markdown +This operation is supported only when no conditions are specified. If you want to modify a condition, please use clearConditions() to remove all existing conditions first +``` + +### `DB-CORE-10038` + +**メッセージ** + +```markdown +One or more columns must be specified. +``` + +### `DB-CORE-10039` + +**メッセージ** + +```markdown +One or more partition keys must be specified. +``` + +### `DB-CORE-10040` + +**メッセージ** + +```markdown +The column definition must be specified since %s is specified as a partition key +``` + +### `DB-CORE-10041` + +**メッセージ** + +```markdown +The column definition must be specified since %s is specified as a clustering key +``` + +### `DB-CORE-10042` + +**メッセージ** + +```markdown +Invalid ID specified. ID: %d +``` + +### `DB-CORE-10043` + +**メッセージ** + +```markdown +The transaction is not active. Status: %s +``` + +### `DB-CORE-10044` + +**メッセージ** + +```markdown +The transaction has already been committed or rolled back. Status: %s +``` + +### `DB-CORE-10045` + +**メッセージ** + +```markdown +The transaction has not been prepared. Status: %s +``` + +### `DB-CORE-10046` + +**メッセージ** + +```markdown +The transaction has not been prepared or validated. Status: %s +``` + +### `DB-CORE-10047` + +**メッセージ** + +```markdown +The transaction already exists +``` + +### `DB-CORE-10048` + +**メッセージ** + +```markdown +A transaction associated with the specified transaction ID is not found. The transaction might have expired +``` + +### `DB-CORE-10049` + +**メッセージ** + +```markdown +%s is the system namespace name +``` + +### `DB-CORE-10050` + +**メッセージ** + +```markdown +The namespace already exists. Namespace: %s +``` + +### `DB-CORE-10051` + +**メッセージ** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-CORE-10052` + +**メッセージ** + +```markdown +The table already exists. Table: %s +``` + +### `DB-CORE-10053` + +**メッセージ** + +```markdown +The namespace is not empty. Namespace: %s; Tables in the namespace: %s +``` + +### `DB-CORE-10054` + +**メッセージ** + +```markdown +The column does not exist. Table: %s; Column: %s +``` + +### `DB-CORE-10055` + +**メッセージ** + +```markdown +The index already exists. Table: %s; Column: %s +``` + +### `DB-CORE-10056` + +**メッセージ** + +```markdown +The index does not exist. Table: %s; Column: %s +``` + +### `DB-CORE-10057` + +**メッセージ** + +```markdown +The column already exists. Table: %s; Column: %s +``` + +### `DB-CORE-10058` + +**メッセージ** + +```markdown +The operation does not have the target namespace or table name. Operation: %s +``` + +### `DB-CORE-10059` + +**メッセージ** + +```markdown +The specified value of the property '%s' is not a number. Value: %s +``` + +### `DB-CORE-10060` + +**メッセージ** + +```markdown +The specified value of the property '%s' is not a boolean. Value: %s +``` + +### `DB-CORE-10061` + +**メッセージ** + +```markdown +Reading the file failed. File: %s +``` + +### `DB-CORE-10062` + +**メッセージ** + +```markdown +The property 'scalar.db.cross_partition_scan.enabled' must be set to true to use cross-partition scan with filtering or ordering +``` + +### `DB-CORE-10063` + +**メッセージ** + +```markdown +This column value is out of range for BigInt. Value: %s +``` + +### `DB-CORE-10064` + +**メッセージ** + +```markdown +This type is not supported. Name: %s, Type: %s +``` + +### `DB-CORE-10065` + +**メッセージ** + +```markdown +Storage '%s' is not found +``` + +### `DB-CORE-10066` + +**メッセージ** + +```markdown +Transaction manager '%s' is not found +``` + +### `DB-CORE-10068` + +**メッセージ** + +```markdown +Please use scan() for non-exact match selection. Operation: %s +``` + +### `DB-CORE-10069` + +**メッセージ** + +```markdown +Import-related functionality is not supported in Cassandra +``` + +### `DB-CORE-10070` + +**メッセージ** + +```markdown +The %s network strategy does not exist +``` + +### `DB-CORE-10071` + +**メッセージ** + +```markdown +The property 'scalar.db.contact_port' must be greater than or equal to zero +``` + +### `DB-CORE-10073` + +**メッセージ** + +```markdown +The BLOB type is not supported for clustering keys in Cosmos DB. Column: %s +``` + +### `DB-CORE-10074` + +**メッセージ** + +```markdown +Import-related functionality is not supported in Cosmos DB +``` + +### `DB-CORE-10075` + +**メッセージ** + +```markdown +The property 'scalar.db.contact_points' must not be empty +``` + +### `DB-CORE-10076` + +**メッセージ** + +```markdown +Cosmos DB supports only EQ, NE, IS_NULL, and IS_NOT_NULL operations for the BLOB type in conditions. Mutation: %s +``` + +### `DB-CORE-10077` + +**メッセージ** + +```markdown +The specified consistency level is not supported. Consistency level: %s +``` + +### `DB-CORE-10078` + +**メッセージ** + +```markdown +0x00 bytes are not accepted in BLOB values in DESC order +``` + +### `DB-CORE-10079` + +**メッセージ** + +```markdown +Cannot encode a Text value that contains '\u0000' +``` + +### `DB-CORE-10081` + +**メッセージ** + +```markdown +An index column cannot be set to null or an empty value for Text or Blob in DynamoDB. Operation: %s +``` + +### `DB-CORE-10082` + +**メッセージ** + +```markdown +DynamoDB supports only EQ, NE, IS_NULL, and IS_NOT_NULL operations for the BOOLEAN type in conditions. Mutation: %s +``` + +### `DB-CORE-10083` + +**メッセージ** + +```markdown +Nested multi-storage definitions are not supported. Storage: %s +``` + +### `DB-CORE-10084` + +**メッセージ** + +```markdown +Storage not found. Storage: %s +``` + +### `DB-CORE-10085` + +**メッセージ** + +```markdown +The namespace name is not acceptable. Namespace: %s +``` + +### `DB-CORE-10086` + +**メッセージ** + +```markdown +The table name is not acceptable. Table: %s +``` + +### `DB-CORE-10087` + +**メッセージ** + +```markdown +Importing tables is not allowed in the RDB engine. RDB engine: %s +``` + +### `DB-CORE-10088` + +**メッセージ** + +```markdown +The %s table must have a primary key +``` + +### `DB-CORE-10089` + +**メッセージ** + +```markdown +The RDB engine is not supported. JDBC connection URL: %s +``` + +### `DB-CORE-10090` + +**メッセージ** + +```markdown +Data type %s(%d) is not supported: %s +``` + +### `DB-CORE-10091` + +**メッセージ** + +```markdown +Data type %s is not supported: %s +``` + +### `DB-CORE-10092` + +**メッセージ** + +```markdown +Getting a transaction state is not supported in JDBC transactions +``` + +### `DB-CORE-10093` + +**メッセージ** + +```markdown +Rolling back a transaction is not supported in JDBC transactions +``` + +### `DB-CORE-10094` + +**メッセージ** + +```markdown +Coordinator tables already exist +``` + +### `DB-CORE-10095` + +**メッセージ** + +```markdown +Coordinator tables do not exist +``` + +### `DB-CORE-10096` + +**メッセージ** + +```markdown +The namespace %s is reserved. Any operations on this namespace are not allowed +``` + +### `DB-CORE-10097` + +**メッセージ** + +```markdown +Mutating transaction metadata columns is not allowed. Table: %s; Column: %s +``` + +### `DB-CORE-10098` + +**メッセージ** + +```markdown +A %s condition is not allowed on Put operations +``` + +### `DB-CORE-10099` + +**メッセージ** + +```markdown +A %s condition is not allowed on Delete operations +``` + +### `DB-CORE-10100` + +**メッセージ** + +```markdown +The condition is not allowed to target transaction metadata columns. Column: %s +``` + +### `DB-CORE-10101` + +**メッセージ** + +```markdown +The column '%s' is reserved as transaction metadata +``` + +### `DB-CORE-10102` + +**メッセージ** + +```markdown +Non-primary key columns with the 'before_' prefix, '%s', are reserved as transaction metadata +``` + +### `DB-CORE-10103` + +**メッセージ** + +```markdown +Put cannot have a condition when the target record is unread and implicit pre-read is disabled. Please read the target record beforehand or enable implicit pre-read: %s +``` + +### `DB-CORE-10104` + +**メッセージ** + +```markdown +Writing already-deleted data is not allowed +``` + +### `DB-CORE-10105` + +**メッセージ** + +```markdown +Getting data neither in the read set nor the delete set is not allowed +``` + +### `DB-CORE-10106` + +**メッセージ** + +```markdown +Reading already-written data is not allowed +``` + +### `DB-CORE-10107` + +**メッセージ** + +```markdown +The transaction is not validated. When using the EXTRA_READ serializable strategy, you need to call validate() before calling commit() +``` + +### `DB-CORE-10108` + +**メッセージ** + +```markdown +DynamoDB cannot batch more than 100 mutations at once +``` + +### `DB-CORE-10109` + +**メッセージ** + +```markdown +The partition keys of the table %s.%s were modified, but altering partition keys is not supported +``` + +### `DB-CORE-10110` + +**メッセージ** + +```markdown +The clustering keys of the table %s.%s were modified, but altering clustering keys is not supported +``` + +### `DB-CORE-10111` + +**メッセージ** + +```markdown +The clustering ordering of the table %s.%s were modified, but altering clustering ordering is not supported +``` + +### `DB-CORE-10112` + +**メッセージ** + +```markdown +The column %s of the table %s.%s has been deleted. Column deletion is not supported when altering a table +``` + +### `DB-CORE-10113` + +**メッセージ** + +```markdown +The data type of the column %s of the table %s.%s was modified, but altering data types is not supported +``` + +### `DB-CORE-10114` + +**メッセージ** + +```markdown +Specifying the '--schema-file' option is required when using the '--repair-all' option +``` + +### `DB-CORE-10115` + +**メッセージ** + +```markdown +Specifying the '--schema-file' option is required when using the '--alter' option +``` + +### `DB-CORE-10116` + +**メッセージ** + +```markdown +Specifying the '--schema-file' option is required when using the '--import' option +``` + +### `DB-CORE-10117` + +**メッセージ** + +```markdown +Specifying the '--coordinator' option with the '--import' option is not allowed. Create Coordinator tables separately +``` + +### `DB-CORE-10118` + +**メッセージ** + +```markdown +Reading the configuration file failed. File: %s +``` + +### `DB-CORE-10119` + +**メッセージ** + +```markdown +Reading the schema file failed. File: %s +``` + +### `DB-CORE-10120` + +**メッセージ** + +```markdown +Parsing the schema JSON failed. Details: %s +``` + +### `DB-CORE-10121` + +**メッセージ** + +```markdown +The table name must contain the namespace and the table. Table: %s +``` + +### `DB-CORE-10122` + +**メッセージ** + +```markdown +The partition key must be specified. Table: %s +``` + +### `DB-CORE-10123` + +**メッセージ** + +```markdown +Invalid clustering-key format. The clustering key must be in the format of 'column_name' or 'column_name ASC/DESC'. Table: %s; Clustering key: %s +``` + +### `DB-CORE-10124` + +**メッセージ** + +```markdown +Columns must be specified. Table: %s +``` + +### `DB-CORE-10125` + +**メッセージ** + +```markdown +Invalid column type. Table: %s; Column: %s; Type: %s +``` + +### `DB-CORE-10126` + +**メッセージ** + +```markdown +The mutation type is not supported. Only the Put or Delete type is supported. Mutation: %s +``` + +### `DB-CORE-10127` + +**メッセージ** + +```markdown +This condition is not allowed for the UpdateIf operation. Condition: %s +``` + +### `DB-CORE-10128` + +**メッセージ** + +```markdown +Cross-partition scan with ordering is not supported in Cassandra +``` + +### `DB-CORE-10129` + +**メッセージ** + +```markdown +Cross-partition scan with ordering is not supported in Cosmos DB +``` + +### `DB-CORE-10130` + +**メッセージ** + +```markdown +Cross-partition scan with ordering is not supported in DynamoDB +``` + +### `DB-CORE-10131` + +**メッセージ** + +```markdown +The directory '%s' does not have write permissions. Please ensure that the current user has write access to the directory. +``` + +### `DB-CORE-10132` + +**メッセージ** + +```markdown +Failed to create the directory '%s'. Please check if you have sufficient permissions and if there are any file system restrictions. Details: %s +``` + +### `DB-CORE-10133` + +**メッセージ** + +```markdown +Directory path cannot be null or empty. +``` + +### `DB-CORE-10134` + +**メッセージ** + +```markdown +No file extension was found on the provided file name %s. +``` + +### `DB-CORE-10135` + +**メッセージ** + +```markdown +Invalid file extension: %s. Allowed extensions are: %s +``` + +### `DB-CORE-10136` + +**メッセージ** + +```markdown +Getting a transaction state is not supported in single CRUD operation transactions +``` + +### `DB-CORE-10137` + +**メッセージ** + +```markdown +Rolling back a transaction is not supported in single CRUD operation transactions +``` + +### `DB-CORE-10138` + +**メッセージ** + +```markdown +Multiple mutations are not supported in single CRUD operation transactions +``` + +### `DB-CORE-10139` + +**メッセージ** + +```markdown +Beginning a transaction is not allowed in single CRUD operation transactions +``` + +### `DB-CORE-10140` + +**メッセージ** + +```markdown +Resuming a transaction is not allowed in single CRUD operation transactions +``` + +### `DB-CORE-10141` + +**メッセージ** + +```markdown +Using the group commit feature on the Coordinator table with a two-phase commit interface is not allowed +``` + +### `DB-CORE-10142` + +**メッセージ** + +```markdown +This operation is supported only when no conditions are specified. If you want to modify a condition, please use clearConditions() to remove all existing conditions first +``` + +### `DB-CORE-10143` + +**メッセージ** + +```markdown +The encryption feature is not enabled. To encrypt data at rest, you must enable this feature. Note that this feature is supported only in the ScalarDB Enterprise edition +``` + +### `DB-CORE-10144` + +**メッセージ** + +```markdown +The variable key column size must be greater than or equal to 64 +``` + +### `DB-CORE-10145` + +**メッセージ** + +```markdown +The value of the column %s in the primary key contains an illegal character. Primary-key columns must not contain any of the following characters in Cosmos DB: ':', '/', '\', '#', '?'. Value: %s +``` + +### `DB-CORE-10146` + +**メッセージ** + +```markdown +Inserting already-written data is not allowed +``` + +### `DB-CORE-10147` + +**メッセージ** + +```markdown +Deleting already-inserted data is not allowed +``` + +### `DB-CORE-10148` + +**メッセージ** + +```markdown +Invalid key: Column %s does not exist in the table %s in namespace %s. +``` + +### `DB-CORE-10149` + +**メッセージ** + +```markdown +Invalid base64 encoding for blob value for column %s in table %s in namespace %s +``` + +### `DB-CORE-10150` + +**メッセージ** + +```markdown +Invalid number specified for column %s in table %s in namespace %s +``` + +### `DB-CORE-10151` + +**メッセージ** + +```markdown +Method null argument not allowed +``` + +### `DB-CORE-10152` + +**メッセージ** + +```markdown +The attribute-based access control feature is not enabled. To use this feature, you must enable it. Note that this feature is supported only in the ScalarDB Enterprise edition +``` + +### `DB-CORE-10153` + +**メッセージ** + +```markdown +The provided clustering key %s was not found +``` + +### `DB-CORE-10154` + +**メッセージ** + +```markdown +The column '%s' was not found +``` + +### `DB-CORE-10155` + +**メッセージ** + +```markdown +The provided partition key is incomplete. Required key: %s +``` + +### `DB-CORE-10156` + +**メッセージ** + +```markdown +The provided clustering key order does not match the table schema. Required order: %s +``` + +### `DB-CORE-10157` + +**メッセージ** + +```markdown +The provided partition key order does not match the table schema. Required order: %s +``` + +### `DB-CORE-10158` + +**メッセージ** + +```markdown +This DATE column value is out of the valid range. It must be between 1000-01-01 and 9999-12-12. Value: %s +``` + +### `DB-CORE-10159` + +**メッセージ** + +```markdown +This TIME column value precision cannot be shorter than one microsecond. Value: %s +``` + +### `DB-CORE-10160` + +**メッセージ** + +```markdown +This TIMESTAMP column value is out of the valid range. It must be between 1000-01-01T00:00:00.000 and 9999-12-31T23:59:59.999. Value: %s +``` + +### `DB-CORE-10161` + +**メッセージ** + +```markdown +This TIMESTAMP column value precision cannot be shorter than one millisecond. Value: %s +``` + +### `DB-CORE-10162` + +**メッセージ** + +```markdown +This TIMESTAMPTZ column value is out of the valid range. It must be between 1000-01-01T00:00:00.000Z to 9999-12-31T23:59:59.999Z. Value: %s +``` + +### `DB-CORE-10163` + +**メッセージ** + +```markdown +This TIMESTAMPTZ column value precision cannot be shorter than one millisecond. Value: %s +``` + +### `DB-CORE-10164` + +**メッセージ** + +```markdown +The underlying-storage data type %s is not supported as the ScalarDB %s data type: %s +``` + +### `DB-CORE-10165` + +**メッセージ** + +```markdown +Missing namespace or table: %s, %s +``` + +### `DB-CORE-10166` + +**メッセージ** + +```markdown +Failed to retrieve table metadata. Details: %s +``` + +### `DB-CORE-10167` + +**メッセージ** + +```markdown +Duplicate data mappings found for table '%s' in the control file +``` + +### `DB-CORE-10168` + +**メッセージ** + +```markdown +No mapping found for column '%s' in table '%s' in the control file. Control file validation set at 'FULL'. All columns need to be mapped. +``` + +### `DB-CORE-10169` + +**メッセージ** + +```markdown +The control file is missing data mappings +``` + +### `DB-CORE-10170` + +**メッセージ** + +```markdown +The target column '%s' for source field '%s' could not be found in table '%s' +``` + +### `DB-CORE-10171` + +**メッセージ** + +```markdown +The required partition key '%s' is missing in the control file mapping for table '%s' +``` + +### `DB-CORE-10172` + +**メッセージ** + +```markdown +The required clustering key '%s' is missing in the control file mapping for table '%s' +``` + +### `DB-CORE-10173` + +**メッセージ** + +```markdown +Duplicated data mappings found for column '%s' in table '%s' +``` + +### `DB-CORE-10174` + +**メッセージ** + +```markdown +Missing required field or column mapping for clustering key %s +``` + +### `DB-CORE-10175` + +**メッセージ** + +```markdown +Missing required field or column mapping for partition key %s +``` + +### `DB-CORE-10176` + +**メッセージ** + +```markdown +Missing field or column mapping for %s +``` + +## `DB-CORE-2xxxx` ステータスコード + +以下は、同時実行エラーカテゴリのステータスコードとメッセージです。 + +### `DB-CORE-20000` + +**メッセージ** + +```markdown +No mutation was applied +``` + +### `DB-CORE-20001` + +**メッセージ** + +```markdown +Logging failed in the batch +``` + +### `DB-CORE-20002` + +**メッセージ** + +```markdown +The operation failed in the batch with type %s +``` + +### `DB-CORE-20003` + +**メッセージ** + +```markdown +An error occurred in the batch. Details: %s +``` + +### `DB-CORE-20004` + +**メッセージ** + +```markdown +A Paxos phase in the CAS operation failed +``` + +### `DB-CORE-20005` + +**メッセージ** + +```markdown +The learn phase in the CAS operation failed +``` + +### `DB-CORE-20006` + +**メッセージ** + +```markdown +A simple write operation failed +``` + +### `DB-CORE-20007` + +**メッセージ** + +```markdown +An error occurred in the mutation. Details: %s +``` + +### `DB-CORE-20008` + +**メッセージ** + +```markdown +A RetryWith error occurred in the mutation. Details: %s +``` + +### `DB-CORE-20009` + +**メッセージ** + +```markdown +A transaction conflict occurred in the mutation. Details: %s +``` + +### `DB-CORE-20010` + +**メッセージ** + +```markdown +A transaction conflict occurred in the mutation. Details: %s +``` + +### `DB-CORE-20011` + +**メッセージ** + +```markdown +A conflict occurred. Please try restarting the transaction. Details: %s +``` + +### `DB-CORE-20012` + +**メッセージ** + +```markdown +The %s condition of the %s operation is not satisfied. Targeting column(s): %s +``` + +### `DB-CORE-20013` + +**メッセージ** + +```markdown +The record being prepared already exists +``` + +### `DB-CORE-20014` + +**メッセージ** + +```markdown +A conflict occurred when preparing records +``` + +### `DB-CORE-20015` + +**メッセージ** + +```markdown +The committing state in the coordinator failed. The transaction has been aborted +``` + +### `DB-CORE-20016` + +**メッセージ** + +```markdown +A conflict occurred during implicit pre-read +``` + +### `DB-CORE-20017` + +**メッセージ** + +```markdown +This record needs to be recovered +``` + +### `DB-CORE-20018` + +**メッセージ** + +```markdown +The record does not exist, so the %s condition is not satisfied +``` + +### `DB-CORE-20019` + +**メッセージ** + +```markdown +The record exists, so the %s condition is not satisfied +``` + +### `DB-CORE-20020` + +**メッセージ** + +```markdown +The condition on the column '%s' is not satisfied +``` + +### `DB-CORE-20021` + +**メッセージ** + +```markdown +Reading empty records might cause a write skew anomaly, so the transaction has been aborted for safety purposes +``` + +### `DB-CORE-20022` + +**メッセージ** + +```markdown +An anti-dependency was found. The transaction has been aborted +``` + +### `DB-CORE-20023` + +**メッセージ** + +```markdown +A transaction conflict occurred in the Insert operation +``` + +### `DB-CORE-20024` + +**メッセージ** + +```markdown +The %s condition of the %s operation is not satisfied. Targeting column(s): %s +``` + +### `DB-CORE-20025` + +**メッセージ** + +```markdown +A transaction conflict occurred in the Insert operation +``` + +## `DB-CORE-3xxxx` ステータスコード + +以下は、内部エラーカテゴリのステータスコードとメッセージです。 + +### `DB-CORE-30000` + +**メッセージ** + +```markdown +Creating the namespace failed. Namespace: %s +``` + +### `DB-CORE-30001` + +**メッセージ** + +```markdown +Dropping the namespace failed. Namespace: %s +``` + +### `DB-CORE-30002` + +**メッセージ** + +```markdown +Creating the table failed. Table: %s +``` + +### `DB-CORE-30003` + +**メッセージ** + +```markdown +Dropping the table failed. Table: %s +``` + +### `DB-CORE-30004` + +**メッセージ** + +```markdown +Truncating the table failed. Table: %s +``` + +### `DB-CORE-30005` + +**メッセージ** + +```markdown +Creating the index failed. Table: %s, Column: %s +``` + +### `DB-CORE-30006` + +**メッセージ** + +```markdown +Dropping the index failed. Table: %s, Column: %s +``` + +### `DB-CORE-30007` + +**メッセージ** + +```markdown +Getting the table metadata failed. Table: %s +``` + +### `DB-CORE-30008` + +**メッセージ** + +```markdown +Getting the table names in the namespace failed. Namespace: %s +``` + +### `DB-CORE-30009` + +**メッセージ** + +```markdown +Checking the namespace existence failed. Namespace: %s +``` + +### `DB-CORE-30010` + +**メッセージ** + +```markdown +Checking the table existence failed. Table: %s +``` + +### `DB-CORE-30011` + +**メッセージ** + +```markdown +Checking the index existence failed. Table: %s; Column: %s +``` + +### `DB-CORE-30012` + +**メッセージ** + +```markdown +Repairing the namespace failed. Namespace: %s +``` + +### `DB-CORE-30013` + +**メッセージ** + +```markdown +Repairing the table failed. Table: %s +``` + +### `DB-CORE-30014` + +**メッセージ** + +```markdown +Adding a new column to the table failed. Table: %s; Column: %s; ColumnType: %s +``` + +### `DB-CORE-30015` + +**メッセージ** + +```markdown +Getting the namespace names failed +``` + +### `DB-CORE-30016` + +**メッセージ** + +```markdown +Getting the table metadata of the table being imported failed. Table: %s +``` + +### `DB-CORE-30017` + +**メッセージ** + +```markdown +Importing the table failed. Table: %s +``` + +### `DB-CORE-30018` + +**メッセージ** + +```markdown +Adding the raw column to the table failed. Table: %s; Column: %s; ColumnType: %s +``` + +### `DB-CORE-30019` + +**メッセージ** + +```markdown +Upgrading the ScalarDB environment failed +``` + +### `DB-CORE-30020` + +**メッセージ** + +```markdown +Something wrong because WriteType is neither CAS nor SIMPLE +``` + +### `DB-CORE-30021` + +**メッセージ** + +```markdown +An error occurred in the selection. Details: %s +``` + +### `DB-CORE-30022` + +**メッセージ** + +```markdown +An error occurred in the mutation. Details: %s +``` + +### `DB-CORE-30023` + +**メッセージ** + +```markdown +An error occurred in the selection. Details: %s +``` + +### `DB-CORE-30024` + +**メッセージ** + +```markdown +An error occurred in the mutation. Details: %s +``` + +### `DB-CORE-30025` + +**メッセージ** + +```markdown +An error occurred in the selection. Details: %s +``` + +### `DB-CORE-30026` + +**メッセージ** + +```markdown +An error occurred in the mutation. Details: %s +``` + +### `DB-CORE-30027` + +**メッセージ** + +```markdown +An error occurred in the selection. Details: %s +``` + +### `DB-CORE-30028` + +**メッセージ** + +```markdown +Fetching the next result failed +``` + +### `DB-CORE-30029` + +**メッセージ** + +```markdown +Rolling back the transaction failed. Details: %s +``` + +### `DB-CORE-30030` + +**メッセージ** + +```markdown +Committing the transaction failed. Details: %s +``` + +### `DB-CORE-30031` + +**メッセージ** + +```markdown +The Get operation failed. Details: %s +``` + +### `DB-CORE-30032` + +**メッセージ** + +```markdown +The Scan operation failed. Details: %s +``` + +### `DB-CORE-30033` + +**メッセージ** + +```markdown +The Put operation failed. Details: %s +``` + +### `DB-CORE-30034` + +**メッセージ** + +```markdown +The Delete operation failed. Details: %s +``` + +### `DB-CORE-30035` + +**メッセージ** + +```markdown +Beginning a transaction failed. Details: %s +``` + +### `DB-CORE-30036` + +**メッセージ** + +```markdown +Preparing records failed +``` + +### `DB-CORE-30037` + +**メッセージ** + +```markdown +Validation failed +``` + +### `DB-CORE-30038` + +**メッセージ** + +```markdown +Executing implicit pre-read failed +``` + +### `DB-CORE-30039` + +**メッセージ** + +```markdown +Reading a record from the underlying storage failed +``` + +### `DB-CORE-30040` + +**メッセージ** + +```markdown +Scanning records from the underlying storage failed +``` + +### `DB-CORE-30041` + +**メッセージ** + +```markdown +Rollback failed because the transaction has already been committed +``` + +### `DB-CORE-30042` + +**メッセージ** + +```markdown +Rollback failed +``` + +### `DB-CORE-30043` + +**メッセージ** + +```markdown +The Insert operation failed. Details: %s +``` + +### `DB-CORE-30044` + +**メッセージ** + +```markdown +The Upsert operation failed. Details: %s +``` + +### `DB-CORE-30045` + +**メッセージ** + +```markdown +The Update operation failed. Details: %s +``` + +### `DB-CORE-30046` + +**メッセージ** + +```markdown +Handling the before-preparation snapshot hook failed. Details: %s +``` + +### `DB-CORE-30047` + +**メッセージ** + +```markdown +Something went wrong while trying to save the data. Details: %s +``` + +### `DB-CORE-30048` + +**メッセージ** + +```markdown +Something went wrong while scanning. Are you sure you are running in the correct transaction mode? Details: %s +``` + +## `DB-CORE-4xxxx` ステータスコード + +以下は、不明なトランザクションステータスエラーカテゴリのステータスコードとメッセージです。 + +### `DB-CORE-40000` + +**メッセージ** + +```markdown +Rolling back the transaction failed. Details: %s +``` + +### `DB-CORE-40001` + +**メッセージ** + +```markdown +Committing state failed with NoMutationException, but the coordinator status does not exist +``` + +### `DB-CORE-40002` + +**メッセージ** + +```markdown +The state cannot be retrieved +``` + +### `DB-CORE-40003` + +**メッセージ** + +```markdown +The coordinator status is unknown +``` + +### `DB-CORE-40004` + +**メッセージ** + +```markdown +Aborting state failed with NoMutationException, but the coordinator status does not exist +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-data-loader/getting-started-export.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-data-loader/getting-started-export.mdx new file mode 100644 index 00000000..ce6ac8cc --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-data-loader/getting-started-export.mdx @@ -0,0 +1,63 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# データのエクスポート + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDB Data Loader のエクスポート機能について説明します。 + +## 機能 + +ScalarDB Data Loader を使用すると、次の形式でデータをエクスポートできます。 + +- JSON +- JSONLines +- CSV + +各エクスポートでは、Data Loader の実行時に指定された CLI 引数に基づいて ScalarDB スキャン操作が実行されます。 + +## 使用方法 + +Data Loader のエクスポート機能は、次の最小限の設定で開始できます。 + +```console +./scalardb-data-loader export --config scalardb.properties --namespace namespace --table tableName +``` + +- --config: 接続プロパティファイルへのパス +- --namespace: データを含むテーブルの名前空間 +- --table: データを含むテーブルの名前 + +デフォルトでは、`--output-file` 引数も省略されている場合、Data Loader は作業ディレクトリに出力ファイルを作成します。 + +### コマンドラインオプション + +ScalarDB Data Loader で使用できるオプションの一覧を次に示します。 + +| オプション | 説明 | 使用方法 | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | +| --config | 設定ファイルへのパス。省略すると、ツールは現在のフォルダーで `scalardb.properties` という名前のファイルを検索します。 | `scalardb-data-loader --config scalardb.properties` | +| --namespace | テーブルデータをエクスポートする名前空間。必須。 | `scalardb-data-loader --namespace namespace` | +| --table | データをエクスポートするテーブルの名前。必須。 | `scalardb-data-loader --table tableName` | +| --key | 特定のパーティションキーのデータをエクスポートします。デフォルトでは、指定されたテーブルのすべてのデータがエクスポートされます。 | `scalardb-data-loader --key columnName=value` | +| --sort | 並べ替える列を指定します。列はクラスタリングキーである必要があります。引数を繰り返して複数の並べ替えを行うことができます。このオプションは `--key` にのみ適用されます。 | `scalardb-data-loader --sort columnName=desc` | +| --projection | 投影を指定してエクスポートする列を制限します。引数を繰り返して複数の投影を指定できます。 | `scalardb-data-loader --projection columnName` | +| --start | スキャン開始をマークするクラスタリングキー。このオプションは `--key` にのみ適用されます。 | `scalardb-data-loader --start columnName=value` | +| --start-exclusive | スキャン開始が排他的かどうか。省略した場合、デフォルト値は `false` です。このオプションは `--key` にのみ適用されます。 | `scalardb-data-loader --start-exclusive` | +| --end | スキャン終了をマークするクラスタリングキー。このオプションは `--key` にのみ適用されます。 | `scalardb-data-loader --end columnName=value` | +| --end-exclusive | スキャン開始が排他的かどうか。省略した場合、デフォルト値は `false` です。このオプションは `--key` にのみ適用されます。 | `scalardb-data-loader --end-exclusive` | +| --limit | スキャンの結果を制限します。省略した場合、デフォルト値は `0` で、制限がないことを意味します。 | `scalardb-data-loader --limit 1000` | +| --output-file | 出力ファイルの名前とパス。省略した場合、ツールは現在のフォルダーに次の名前形式でファイルを保存します:
`export_namespace.tableName_timestamp.json` または `export_namespace.tableName_timestamp.csv`

出力フォルダーが存在する必要があります。dataloader は出力フォルダーを作成しません。 | `scalardb-data-loader --output-file ./out/output.json` | +| --format | 出力形式。デフォルトでは `json` が選択されます。 | `scalardb-data-loader --format json` | +| --metadata | `true` に設定すると、トランザクションメタデータがエクスポートに含まれます。デフォルトでは `false` に設定されています。 | `scalardb-data-loader --metadata` | +| --delimiter | CSV ファイルで使用される区切り文字。デフォルト値は `;` です。 | `scalardb-data-loader --delimiter ;` | +| --no-headers | CSV ファイルからヘッダー行を除外します。デフォルトは `false` です。 | `scalardb-data-loader --no-headers` | +| --threads | 同時処理のスレッド数。 | `scalardb-data-loader --threads 500` | diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-data-loader/getting-started-import.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-data-loader/getting-started-import.mdx new file mode 100644 index 00000000..122f6f57 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-data-loader/getting-started-import.mdx @@ -0,0 +1,277 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# データのインポート + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このドキュメントでは、ScalarDB Data Loader のインポート機能について説明します。 + +## 機能 + +- JSON または JSONLines ファイルからデータをインポート +- ソースフィールド名マッピングに基づく自動データマッピング +- JSON 制御ファイルによるカスタムデータマッピング +- 1つのレコードまたは行から複数​​のテーブルにデータをインポート +- INSERT、UPDATE、UPSERT のサポート + +## 使用方法 + +Data Loader のインポート機能は、次の最小限の設定で開始できます: + +```console +./scalardb-data-loader import --config scalardb.properties --namespace namespace --table tableName +``` + +上記の設定により、制御ファイルが使用されず、データマッピングが自動的に適用されるインポートプロセスが開始されます。 + +新規または既存のデータを正常にインポートするには、次の手順を実行してください + +- インポートする必要があるデータを含むソースファイルを準備します。 + +- 適切なインポートモードを選択します。デフォルトでは、インポートは `upsert` モードで実行されます。つまり、新しい場合はデータが挿入され、パーティションキーやクラスタリングキーが見つかった場合は更新されます。その他のオプションは、`insert` モードまたは `update` モードです。 + +- データをインポートする正しい `namespace` および `table` 名を見つけます。 + +- 各データ行に対して `all required columns` チェックを実行するかどうかを決定します。有効にすると、列が欠落しているデータ行は失敗として扱われ、インポートされません。 + +- `success` および `failed` 出力ファイルのパス名を指定します。デフォルトでは、Data Loader は作業ディレクトリにファイルを作成します。 + +- JSON データを処理する場合、成功または失敗のログファイルの JSON 出力を `pretty print` にするかどうかを決定します。デフォルトでは、このオプションはパフォーマンスのために無効になっています + +- 必要に応じて `threads` 引数を指定してパフォーマンスを調整します + +- コマンドラインからインポートを実行して、データのインポートを開始します。実行中の ScalarDB インスタンスに応じて、ScalarDB Data Loader を正しい `storage` または `transaction` モードで実行してください。 + +### コマンドラインオプション + +ScalarDB Data Loader で使用できるオプションの一覧を次に示します。 + +| オプション | 説明 | 使用方法 | +|---------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------| +| --mode | ScalarDB の実行モード。省略した場合、デフォルト値は `storage` です。 | `scalardb-data-loader --mode transaction` | +| --config | 設定ファイルへのパス。省略した場合、ツールは現在のフォルダーで `scalardb.properties` という名前のファイルを検索します。 | `scalardb-data-loader --config scalardb.properties` | +| --namespace | テーブルデータをエクスポートする名前空間。制御ファイルが指定されていない場合は必須です。 | `scalardb-data-loader --namespace namespace` | +| --table | データをエクスポートするテーブルの名前。制御ファイルが指定されていない場合は必須です。 | `scalardb-data-loader --table tableName` | +| --import-mode | ScalarDB テーブルにデータをインポートするモード。サポートされているモードは `insert`、`update`、および `upsert` です。オプション。デフォルトでは、値は `upsert` に設定されています。 | `scalardb-data-loader --import-mode=upsert` | +| --all-columns-required | 設定されている場合、列が欠落しているデータ行はインポートできません。オプションです。デフォルトでは、チェックは実行されません。 | `scalardb-data-loader --all-columns-required` | +| --file | インポートするファイルへのパスを指定します。必須。 | `scalardb-data-loader --file ` | +| --success | 成功したインポート結果を書き込むために作成されるファイルへのパス。成功したインポート結果と失敗したインポート結果は、両方とも別のファイルに書き込まれます。
オプションです。デフォルトでは、現在の作業ディレクトリに新しいファイルが作成されます。

注: ファイルが既に存在する場合は、上書きされます。 | `scalardb-data-loader --success ` | +| --failed | 失敗したインポート結果を書き込むために作成されるファイルへのパス。
オプション。デフォルトでは、現在の作業ディレクトリに新しいファイルが作成されます。

注: ファイルがすでに存在する場合は、上書きされます。 | `scalardb-data-loader --failed ` | +| --threads | 同時処理のスレッド数。 | `scalardb-data-loader --threads 500` | +| --format | インポートファイルの形式。`json` および `jsonl` ファイルがサポートされています。オプション。デフォルトでは値 `json` が選択されます。 | `scalardb-data-loader --format json` | +| --ignore-null | ソースファイル内の null 値は無視されます。つまり、既存のデータは上書きされません。オプション。デフォルトでは値は `false` です。 | `scalardb-data-loader --ignore-null` | +| --pretty | 設定すると、成功ファイルと失敗ファイルへの出力は `pretty print` モードで行われます。デフォルトでは、このオプションは有効になっていません。 | `scalardb-data-loader --pretty` | +| --control-file | カスタムデータマッピングやマルチテーブルインポートのルールを指定する JSON 制御ファイルへのパス。 | `scalardb-data-loader --control-file control.json` | +| --control-file-validation-level | 制御ファイルの検証レベル。`MAPPED`、`KEYS`、または` FULL`。

オプションで、デフォルトではレベルは `MAPPED` に設定されています。 | `scalardb-data-loader --control-file-validation-level FULL` | +| --log-put-value | ScalarDB `PUT` 操作で使用された値がログファイルに含まれるかどうか。
オプションで、デフォルトでは無効になっています。 | `scalardb-data-loader --log-put-value` | +| --error-file-required | インポートファイルに CSV データが含まれている場合に、オプションの JSON タイプのエラーファイルをエクスポートします。デフォルトでは、このオプションは無効になっています。 | `scalardb-data-loader --error-file-required` | +| --error | インポートファイルに CSV データが含まれている場合に、オプションのエラーファイルを指定します。 | `scalardb-data-loader --error ` | +| --delimiter | インポートファイルに CSV データが含まれている場合に、カスタム区切り文字を指定します。 | `scalardb-data-loader --delimiter ` | +| --header | インポートファイルに CSV データが含まれていて、ヘッダー行がない場合に、ヘッダー行データを指定します。 | `scalardb-data-loader --header ` | + +## インポートモード + +Data Loader は、次のインポートモードをサポートしています: + +| モード | 説明 | +| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| INSERT | 各ソースレコードは新しいデータとして扱われます。パーティションとクラスタリングキーに基づいて、ScalarDB テーブルにデータがすでに存在する場合、このソースデータのインポートは失敗します。 | +| UPDATE | 各ソースレコードは、ScalarDB テーブル内の既存のデータの更新として扱われます。パーティションキーとクラスタリングキーに基づいて、テーブルにデータが存在しない場合、このソースデータのインポートは失敗します。 | +| UPSERT | ターゲット ScalarDB テーブルにすでにデータが含まれている場合、インポートは UPDATE によって行われます。ターゲットデータがない場合は、INSERT として扱われます。 | + +*注*: + + `INSERT` の場合、自動マッピングまたは制御ファイルによるカスタムマッピングによって、各ターゲット列のソースファイル内に一致するフィールドが必要です。これは、`INSERT` に変わる `UPSERT` にも適用されます。 + +## データマッピング + +### 自動マッピング + +制御ファイルが指定されていない場合、Data Loader はソース JSON データ内のフィールドを ScalarDB テーブル内の使用可能な列に自動的にマッピングします。名前が一致せず、すべての列が必須である場合は、検証エラーとして扱われます。この場合、このレコードのインポートは失敗し、結果は失敗した出力ログに追加されます。 + +### カスタムマッピング + +ソースフィールドがターゲット列名と一致しない場合は、制御ファイルを使用する必要があります。この制御ファイルでは、フィールド名のカスタムマッピングルールを指定できます。 + +たとえば、次の制御ファイルは、ソースファイルのフィールド `custom_id` をターゲットテーブルの `id` にマッピングします。 + +```json +{ + "tables": [{ + "namespace": "sample", + "table_name": "table1", + "mappings": [{ + "source_field": "custom_id", + "target_column": "id" + }] + } + ] +} +``` + +## 制御ファイル + +カスタムデータマッピングまたは複数テーブルのインポートを可能にするために、Data Loader は JSON 制御ファイルによる設定をサポートしています。このファイルは、Data Loader を起動するときに `--control-file` 引数で渡す必要があります。 + +### 制御ファイルの検証レベル + +制御ファイルの検証を強制するために、Data Loader では検証レベルを指定できます。設定されたレベルに基づいて、Data Loader は事前チェックを実行し、レベルルールに基づいて制御ファイルを検証します。 + +次のレベルがサポートされています。 + +| レベル | 説明 | +| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| FULL | この検証では、制御ファイルにターゲット ScalarDB テーブルの各列のマッピングがあることを確認します。 | +| KEYS | この検証では、各 ScalarDB テーブルパーティションのマッピングと、使用可能な場合は制御ファイルマッピングのクラスタリングキー列のマッピングが使用可能であることを確認します。 | +| MAPPED | この検証では、指定されたソースフィールドとターゲット列が、制御ファイルで指定されたマッピングに対してのみ存在することを確認します。
その他のフィールドはチェックされません。 | + +検証レベルはオプションであり、Data Loader の起動時に `--control-file-validation-level` 引数で設定できます。 + +*注*: + +この検証は事前チェックとして実行されるものであり、インポートプロセスが自動的に成功することを意味するものではありません。 + +例:レベルがマップ済みに設定されていて、制御ファイルに INSERT の各列のマッピングが含まれていない場合、INSERT にはすべての列をマップする必要があるため、インポートプロセスは失敗します。 + +## 複数テーブルのインポート + +Data Loader は、複数テーブルのターゲットインポートをサポートしています。 + +JSON または JSONLine ファイル内の1つの行を、制御ファイルでテーブルマッピングルールを指定することにより、複数のテーブルにインポートできます。現在、制御ファイルなしでは複数テーブルのインポートはサポートされていません。 + +ScalarDB トランザクションモードで複数テーブルのインポートを使用する場合、各テーブルのインポートごとにトランザクションが作成されます。例: ソースレコードが制御ファイルで3つのテーブルにマップされている場合、3つの個別のトランザクションが作成されます。 + +例: 次のソースレコードを `table1` と `table2` にインポートするには、次の手順を実行します: + +| Table1 | Table2 | +| ------ | ------ | +| Id | Id | +| price | amount | + +**ソースレコード** + +```json +[{ + "custom_id": 1, + "custom_price": 1000, + "custom_amount": 100 + +}] +``` + +**制御ファイル** + +```json +{ + "tables": [{ + "namespace": "sample", + "table_name": "table1", + "mappings": [{ + "source_field": "custom_id", + "target_column": "id" + }, { + "source_field": "custom_price", + "target_column": "price" + }] + }, + { + "namespace": "sample", + "table_name": "table2", + "mappings": [{ + "source_field": "custom_id", + "target_column": "id" + }, { + "source_field": "custom_amount", + "target_column": "amount" + }] + } + ] +} +``` + +## 出力ログ + +インポートタスクを開始すると、Data Loader はインポート結果を2つのファイルに記録します。1つのファイルには正常にインポートされたインポートデータが含まれ、もう1つのファイルにはインポートできなかったデータが含まれます。失敗したデータには、データをインポートできなかった理由を説明する追加フィールドが含まれます。このフィールドは `data_loader_import_status` と呼ばれます。 + +失敗したインポートを含むファイルは、問題を修正するために編集し、そのまま新しいインポートタスクのソースファイルとして使用できます。エラーを含む `data_loader_import_status` フィールドを最初に削除する必要はありません。このフィールドはインポートプロセス中に無視され、元の値は成功または失敗した出力ファイルの新しいバージョンには含まれません。 + +正常にインポートされたデータを含むファイルには `data_loader_import_status` フィールドも含まれます。このファイルは、インポートされた各データ行に関するステータスメッセージ(新しい行が作成されたか、既存のデータが更新されたか)を含みます。 + +### ログ形式 + +| フィールド | 説明 | +| -------------- | -------------------------------------------------------------------------------------- | +| action | データレコードのインポートプロセスの結果。UPDATE、INSERT、または FAILED_DURING_VALIDATION。 | +| namespace | データがインポートされるテーブルの名前空間。 | +| tablename | データがインポートされるテーブルの名前。 | +| is_data_mapped | 使用可能な制御ファイルに基づいて、カスタムデータマッピングが適用されたかどうか。 | +| tx_id | トランザクションの ID。Data Loader が `transaction` モードで実行されている場合にのみ使用できます。 | +| value | オプションのデータマッピング後の最終値。Data Loader が `PUT` 操作で使用する値。 | +| row_number | ソースデータの行番号またはレコード番号。 | +| Errors | インポートプロセス中に問題が発生した検証エラーまたはその他のエラーのリスト。 | + +JSON 形式の成功ログファイルの例: + +```json +[{ + "column_1": 1, + "column_2": 2, + "column_n": 3, + "data_loader_import_status": { + "results": [{ + "action": "UPDATE", + "namespace": "namespace1", + "tableName": "table1", + "is_data_mapped": true, + "tx_id": "value", + "value": "value", + "row_number": "value" + }] + } +}] +``` + +JSON 形式の失敗したログファイルの例: + +```json +[{ + "column_1": 1, + "column_2": 2, + "column_n": 3, + "data_loader_import_status": { + "results": [{ + "action": "FAILED_DURING_VALIDATION", + "namespace": "namespace1", + "tableName": "table1", + "is_data_mapped": false, + "value": "value", + "row_number": "value", + "errors": [ + "missing columns found during validation" + ] + }] + } +}] +``` + +## データの重複 + +Data Loader は重複を単独では処理しません。ScalarDB トランザクションモードでは、同じターゲットデータを連続して更新しようとすると `No Mutation` エラーが発生しますが、これは Data Loader では処理されません。これらの失敗したデータ行は、失敗したインポート結果の出力ファイルに追加され、後でインポートを再試行できます。 + +ただし、Data Loader では正しい状態を保証できないため、インポートファイルに同じパーティションキーやクラスタリングキーの更新や挿入が含まれていないことを確認することをお勧めします。 + +## ストレージモードとトランザクションモード + +ScalarDB はストレージモードとトランザクションモードの両方をサポートしており、このサポートは Data Loader のインポートプロセスに含まれています。 + +ローダーがストレージモードで起動されると、各インポートは非​​トランザクション方式で実行されます。 + +ローダーをトランザクションモードで起動すると、トランザクションを使用してデータがインポートされます。現在、各行は個別のトランザクションを介してインポートされます。1つのレコードを複数のテーブルにインポートする場合、各テーブルのインポートごとに個別のトランザクションが作成されます。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/how-to-run-two-phase-commit-transaction.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/how-to-run-two-phase-commit-transaction.mdx new file mode 100644 index 00000000..47a1aa5d --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/how-to-run-two-phase-commit-transaction.mdx @@ -0,0 +1,143 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 2フェーズコミットトランザクションを実行する方法 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB GraphQL は、[2フェーズコミットトランザクション](../two-phase-commit-transactions.mdx)と呼ばれるトランザクションをサポートしています。 +2フェーズコミットトランザクションを使用すると、複数のプロセス/アプリケーション (マイクロサービスなど) にまたがるトランザクションを実行できます。 +トランザクションを開始するアプリケーションを「コーディネーター」と名付け、トランザクションに参加するアプリケーションを「参加者」と名付けます。 +すべての2フェーズコミット操作では、ミューテーションまたはクエリ操作に `@twoPhaseCommit` ディレクティブをアノテーションする必要があります。以下は、このような操作の説明です。 + +## トランザクションを開始する + +トランザクションを開始するには、パラメータを設定せずに `@twoPhaseCommit` ディレクティブを追加します。 + +```graphql +query some_query @twoPhaseCommit { + # some query +} +``` + +開始されたトランザクションのトランザクション ID は、結果の一部である拡張オブジェクトで返されます。 + +```json +{ + "data": { + ... + }, + "extensions": { + "transaction": { + "id": "the_transaction_id" + } + } +} +``` + +## トランザクションに参加する (参加者用) + +参加者アプリケーションで、コーディネーターアプリケーションによって開始されたトランザクションに参加するには、トランザクション ID を `id` パラメータで設定し、`join` パラメータを true に設定します。 + +```graphql +query some_query_from_participant @twoPhaseCommit(id:"the_transaction_id", join:true) { + # some query +} +``` + +## トランザクションを再開する + +開始または結合されたトランザクションで操作の実行を継続するには、`@twoPhaseCommit` ディレクティブの `id` パラメータにトランザクション ID 値を設定します。 + +```graphql +mutation some_mutation @twoPhaseCommit(id:"the_transaction_id") { + # some mutation +} +``` + +## トランザクションの準備、検証、コミット + +クエリと変更操作が完了したら、トランザクションをコミットする必要があります。 + +よく知られている2フェーズコミットプロトコルと同様に、準備とコミットの2つのフェーズがあります。 + +まず、すべてのコーディネータ/参加者アプリケーションでトランザクションを準備し、次にすべてのコーディネータ/参加者アプリケーションでトランザクションをコミットする必要があります。 + +Consensus Commit トランザクションマネージャーが `SERIALIZABLE` 分離レベルで `EXTRA_READ` シリアル化可能戦略を使用して設定されている場合、準備フェーズとコミットフェーズの間に追加の「検証」フェーズが必要です。 + +準備とコミットと同様に、検証はすべてのコーディネータ/参加者アプリケーションで実行する必要があります。 + +準備、検証、コミットは、すべてのコーディネータ/参加者アプリケーションで並行して実行できます。 + +### トランザクションを準備する + +2フェーズコミットトランザクションを準備するには、2つのオプションがあります。 + +#### ディレクティブパラメータ経由 + +ディレクティブの `prepare` パラメータを使用すると、操作フィールドの実行後に、エラーが発生しない場合にのみトランザクションが準備されます。 + +```graphql +mutation some_mutation_then_prepare_tx @twoPhaseCommit(id:"the_transaction_id", prepare:true) { + mutation1 : ... + mutation2 : ... + # the transaction will be prepared after the execution of the mutation1 and mutation2 fields +} +``` + +#### ミューテーションフィールド経由 + +ミューテーション操作に `prepare` フィールドを追加します。このフィールドはトランザクションの準備を開始します。 + +```graphql +mutation prepare_tx @twoPhaseCommit(id:"the_transaction_id") { + prepare +} +``` + +### トランザクションを検証する + +ミューテーション操作に `validate` フィールドを追加します。このフィールドはトランザクションの検証をトリガーします。 + +```graphql +mutation validate_tx @twoPhaseCommit(id:"the_transaction_id") { + validate +} +``` + +### トランザクションをコミットする + +ミューテーション操作に `commit` フィールドを追加します。このフィールドはトランザクションのコミットをトリガーします。 + +```graphql +mutation commit_tx @twoPhaseCommit(id:"the_transaction_id") { + commit +} +``` + +### トランザクションのアボート/ロールバック + +トランザクションを明示的にアボート/ロールバックする必要がある場合は、`abort` または `rollback` ミューテーションフィールドを互換的に使用できます (どちらも効果と使用法は同じです)。他の操作と混在させることはできないため、単独で指定する必要があります。 + +```graphql +mutation AbortTx @twoPhaseCommit(id: "the_transaction_id") { + abort +} +``` + +または + +```graphql +mutation RollbackTx @twoPhaseCommit(id: "the_transaction_id") { + rollback +} +``` + +## エラー処理 + +`@twoPhaseCommit` 操作によって例外がスローされた場合、ScalarDB GraphQL はトランザクションを回復するロールバックプロシージャをトリガーします。2フェーズコミットトランザクションでの例外処理の詳細については、[ScalarDB 2フェーズコミットトランザクションの例外処理ガイド](../two-phase-commit-transactions.mdx#handle-exceptions)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/index.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/index.mdx new file mode 100644 index 00000000..571e896f --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/index.mdx @@ -0,0 +1,27 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB GraphQL の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB GraphQL は、クライアントアプリケーションが GraphQL を使用して ScalarDB Cluster と通信できるようにするインターフェースレイヤーです。柔軟なデータ取得や型安全性などの GraphQL のメリットを活用しながら、ScalarDB のトランザクション管理とデータアクセス機能の恩恵を受けることができます。 + +ScalarDB GraphQL を使用することで、ScalarDB スキーマに基づいて GraphQL スキーマを自動的に作成し、CRUD 操作を実行し、複数のデータベースにまたがる複雑なトランザクションを実行することができます。このインターフェースは統一されたクエリ機構を提供することでバックエンド開発を簡素化し、高度かつ応答性の高いデータインタラクションを期待する現代のアプリケーションに特に有用です。 + +## ScalarDB Cluster での GraphQL の始めかた + +ScalarDB GraphQL は直感的でユーザーフレンドリーに設計されており、開発者が ScalarDB スキーマに基づいて GraphQL スキーマを簡単に自動作成し、基盤となるデータベースとやり取りできるようにします。 + +GraphQL サポートを備えた ScalarDB Cluster のセットアップ方法の詳細については、[ScalarDB Cluster GraphQL をはじめよう](../scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx)を参照してください。 + +## 2フェーズコミットによるトランザクション + +ScalarDB GraphQL は、2フェーズコミットインターフェースを使用してトランザクションを実行することをサポートしています。2フェーズコミットインターフェースを使用することで、複数のプロセス/アプリケーション(例えば、マイクロサービスアプリケーション)にまたがるトランザクションを実行できます。 + +ScalarDB GraphQL で2フェーズコミットインターフェースを使用してトランザクションを実行する方法の詳細については、[2フェーズコミットトランザクションを実行する方法](./how-to-run-two-phase-commit-transaction.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/scalardb-graphql-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/scalardb-graphql-status-codes.mdx new file mode 100644 index 00000000..88b2aacb --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-graphql/scalardb-graphql-status-codes.mdx @@ -0,0 +1,247 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB GraphQL エラーコード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB GraphQL のエラーコードの一覧を示します。 + +## エラーコードのクラスと説明 + +| クラス | 説明 | +|:-------------------|:--------------------------| +| `DB-GRAPHQL-1xxxx` | ユーザーエラーカテゴリのエラー | + +## `DB-GRAPHQL-1xxxx` ステータスコード + +以下は、ユーザーエラーカテゴリのステータスコードとメッセージです。 + +### `DB-GRAPHQL-10000` + +**メッセージ** + +```markdown +A long value was expected +``` + +### `DB-GRAPHQL-10001` + +**メッセージ** + +```markdown +The value is out of range for BigIntValue +``` + +### `DB-GRAPHQL-10002` + +**メッセージ** + +```markdown +A long, integer, or string value was expected +``` + +### `DB-GRAPHQL-10003` + +**メッセージ** + +```markdown +The AST type `IntValue` was expected +``` + +### `DB-GRAPHQL-10004` + +**メッセージ** + +```markdown +A float value was expected +``` + +### `DB-GRAPHQL-10005` + +**メッセージ** + +```markdown +An integer or float value was expected +``` + +### `DB-GRAPHQL-10006` + +**メッセージ** + +```markdown +The AST type `IntValue` or `FloatValue` was expected +``` + +### `DB-GRAPHQL-10007` + +**メッセージ** + +```markdown +The type is not supported. Type: %s +``` + +### `DB-GRAPHQL-10008` + +**メッセージ** + +```markdown +The field `%s` requires a `@transaction` or `@twoPhaseCommit` directive with proper arguments +``` + +### `DB-GRAPHQL-10009` + +**メッセージ** + +```markdown +The field `%s` cannot be used together with other fields +``` + +### `DB-GRAPHQL-10010` + +**メッセージ** + +```markdown +The `@twoPhaseCommit` directive with the `id` argument is required to `%s` the transaction +``` + +### `DB-GRAPHQL-10011` + +**メッセージ** + +```markdown +`%s` and `prepare` cannot be run simultaneously +``` + +### `DB-GRAPHQL-10012` + +**メッセージ** + +```markdown +`%s` and `join` cannot be run simultaneously +``` + +### `DB-GRAPHQL-10013` + +**メッセージ** + +```markdown +The `@transaction` directive with the `id` argument is required to `%s` the transaction +``` + +### `DB-GRAPHQL-10014` + +**メッセージ** + +```markdown +`%s` and `commit` cannot be run simultaneously +``` + +### `DB-GRAPHQL-10015` + +**メッセージ** + +```markdown +An object cannot be annotated with both `@transaction` and `@twoPhaseCommit` directives +``` + +### `DB-GRAPHQL-10016` + +**メッセージ** + +```markdown +The `join` argument of the `@twoPhaseCommit` directive requires a transaction `id` argument +``` + +### `DB-GRAPHQL-10017` + +**メッセージ** + +```markdown +`%s` requires the mutation object to be annotated with a `@twoPhaseCommit` directive +``` + +### `DB-GRAPHQL-10018` + +**メッセージ** + +```markdown +The `%s` clustering key must have only one of the following: %s +``` + +### `DB-GRAPHQL-10019` + +**メッセージ** + +```markdown +A string variable is expected but got %s +``` + +### `DB-GRAPHQL-10020` + +**メッセージ** + +```markdown +Unexpected value of id: %s +``` + +### `DB-GRAPHQL-10021` + +**メッセージ** + +```markdown +A Boolean variable is expected but got %s +``` + +### `DB-GRAPHQL-10022` + +**メッセージ** + +```markdown +Unexpected value of %s: %s +``` + +### `DB-GRAPHQL-10023` + +**メッセージ** + +```markdown +Invalid column. Column: %s; Type: %s +``` + +### `DB-GRAPHQL-10024` + +**メッセージ** + +```markdown +Unexpected value of type: %s +``` + +### `DB-GRAPHQL-10025` + +**メッセージ** + +```markdown +Only one of the following can be specified: %s +``` + +### `DB-GRAPHQL-10026` + +**メッセージ** + +```markdown +Unexpected mutation field: %s +``` + +### `DB-GRAPHQL-10027` + +**メッセージ** + +```markdown +Invalid type: %s +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/README.mdx new file mode 100644 index 00000000..39d11742 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/README.mdx @@ -0,0 +1,23 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# サンプルアプリケーションの実行の概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このサブカテゴリでは、ScalarDB を活用するさまざまなサンプルアプリケーションを実行する方法を学習できます。 + +サンプルアプリケーションをセットアップして実行するには、次のガイドを参照してください。 + +- [マルチストレージトランザクションサンプル](multi-storage-transaction-sample/README.mdx) +- [マイクロサービストランザクションサンプル](microservice-transaction-sample/README.mdx) +- [マルチストレージトランザクションサンプルを使用した Spring Data JDBC for ScalarDB](spring-data-multi-storage-transaction-sample/README.mdx) +- [マイクロサービストランザクションサンプルを使用した Spring Data JDBC for ScalarDB](spring-data-microservice-transaction-sample/README.mdx) +- [ScalarDB Analytics with PostgreSQL を使用した分析クエリ](scalardb-analytics-postgresql-sample/README.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/README.mdx new file mode 100644 index 00000000..f5cddf30 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/README.mdx @@ -0,0 +1,538 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# マイクロサービストランザクションをサポートするサンプルアプリケーションを作成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、ScalarDB でマイクロサービストランザクションをサポートするサンプルアプリケーションを作成する方法について説明します。 + +## 概要 + +このチュートリアルでは、ScalarDB の[2フェーズコミットインターフェースを使用したトランザクション](../../two-phase-commit-transactions.mdx)を通じてアイテムを注文し、信用枠で支払いを行うことができるサンプル電子商取引アプリケーションを作成するプロセスを示します。 + +サンプルアプリケーションには、[database-per-service pattern](https://microservices.io/patterns/data/database-per-service.html) に基づく *Customer Service* と *Order Service* という2つのマイクロサービスがあります。 + +- **Customer Service** は、信用枠情報、信用限度額、信用合計などの顧客情報を管理します。 +- **Order Service** は、注文の確定や注文履歴の取得などの注文操作を担当します。 + +各サービスには gRPC エンドポイントがあります。クライアントはエンドポイントを呼び出し、サービスも各エンドポイントを呼び出します。 + +サンプルアプリケーションで使用するデータベースは Cassandra と MySQL です。 Customer Service と Order Service は、それぞれ ScalarDB を介して Cassandra と MySQL を使用します。 + +![概要](images/overview.png) + +図に示されているように、両方のサービスは、Consensus Commit プロトコルに使用される小さな Coordinator データベースにアクセスします。データベースはサービスに依存せず、Consensus Commit のトランザクションメタデータを高可用性の方法で管理するために存在します。 + +サンプルアプリケーションでは、セットアップと説明を簡単にするために、Coordinator データベースを Order Service の同じ Cassandra インスタンスに共存させています。または、Coordinator データベースを別のデータベースとして管理することもできます。 + +:::note + +サンプルアプリケーションは ScalarDB の使用方法を示すことに重点を置いているため、アプリケーション固有のエラー処理、認証処理、および同様の機能はサンプルアプリケーションに含まれていません。ScalarDB での例外処理の詳細については、[例外の処理方法](../../api-guide.mdx#例外の処理方法)を参照してください。 + +さらに、サンプルアプリケーションの目的上、各サービスには1つのコンテナがあるため、サービス間のリクエストルーティングは不要です。ただし、実稼働環境では、スケーラビリティと可用性のために各サービスに複数のサーバーまたはホストがあるため、2フェーズコミットインターフェイスを使用したトランザクションでは、サービス間のリクエストルーティングを検討する必要があります。要求ルーティングの詳細については、[2フェーズコミットインターフェイスを使用したトランザクションでのリクエストルーティング](../../two-phase-commit-transactions.mdx#2フェーズコミットインターフェイスを使用したトランザクションでのリクエストルーティング) を参照してください。 + +::: + +### サービスエンドポイント + +サービスで定義されているエンドポイントは次のとおりです。 + +- Customer Service + - `getCustomerInfo` + - `payment` + - `prepare` + - `validate` + - `commit` + - `rollback` + - `repayment` + +- Order Service + - `placeOrder` + - `getOrder` + - `getOrders` + +### このサンプルアプリケーションで実行できること + +サンプルアプリケーションは、次の種類のトランザクションをサポートしています。 + +- Customer Service の `getCustomerInfo` エンドポイントを介して顧客情報を取得します。 +- Order Service の `placeOrder` エンドポイントと、Customer Service の `payment`、`prepare`、`validate`、`commit`、`rollback` エンドポイントを介して、信用枠を使用して注文を行います。 + - 注文のコストが顧客の信用限度額を下回っているかどうかを確認します。 + - チェックに合格した場合、注文履歴を記録し、顧客が支払った金額を更新します。 +- Order Service の `getOrder` エンドポイントと、Customer Service の `getCustomerInfo`、`prepare`、`validate`、`commit`、`rollback` エンドポイントを介して、注文 ID で注文情報を取得します。 +- Order Service の `getOrders` エンドポイントと、Customer Service の `getCustomerInfo`、`prepare`、`validate`、`commit`、`rollback` エンドポイントを介して、顧客 ID で注文情報を取得します。 +- Customer Service の `repayment` エンドポイントを介して支払いを行います。 + - 顧客が支払った金額を減らします。 + +:::note + +`getCustomerInfo` エンドポイントは、コーディネーターからトランザクション ID を受信するときに、参加者サービスエンドポイントとして機能します。 + +::: + +## このサンプルアプリケーションの前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10以降 ([Docker Compose](https://docs.docker.com/compose/install/) V2以降) + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../../requirements.mdx)を参照してください。 + +::: + +## ScalarDB のセットアップ + +次のセクションでは、ScalarDB でマイクロサービストランザクションをサポートするサンプルアプリケーションをセットアップする方法について説明します。 + +### ScalarDB サンプルリポジトリをクローンする + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリをクローンします。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、サンプルアプリケーションが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/microservice-transaction-sample +``` + +### CassandraとMySQLを起動する + +Cassandra と MySQL は、それぞれ [`database-cassandra.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/database-cassandra.properties) と [`database-mysql.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/database-mysql.properties) に示されているように、サンプルアプリケーション用にすでに設定されています。ScalarDB でのマルチストレージトランザクション機能の設定の詳細については、[マルチストレージトランザクションをサポートするように ScalarDB を設定する方法](../../multi-storage-transactions.mdx#マルチストレージトランザクションをサポートするように-scalardb-を設定する方法)を参照してください。 + +サンプルアプリケーションの Docker コンテナに含まれている Cassandra と MySQL を起動するには、次のコマンドを実行します。 + +```console +docker-compose up -d mysql cassandra +``` + +:::note + +開発環境によっては、Docker コンテナの起動に1分以上かかる場合があります。 + +::: + +### スキーマをロードします + +サンプルアプリケーションのデータベーススキーマ (データを整理する方法) は、Customer Service の場合は [`customer-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service-schema.json)、Order Service の場合は [`order-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service-schema.json) で既に定義されています。 + +スキーマを適用するには、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases)ページに移動し、使用する ScalarDB のバージョンに一致する ScalarDB Schema Loader を `scalardb-samples/microservice-transaction-sample` フォルダーにダウンロードします。 + +#### MySQL + +[`customer-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service-schema.json) のスキーマを MySQL にロードするには、次のコマンドを実行します。`` は、ダウンロードした ScalarDB Schema Loader のバージョンに置き換えます。 + +```console +java -jar scalardb-schema-loader-.jar --config database-mysql.properties --schema-file customer-service-schema.json +``` + +#### Cassandra + +[`order-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service-schema.json) のスキーマを Cassandra にロードするには、次のコマンドを実行します。`` は、ダウンロードした ScalarDB Schema Loader のバージョンに置き換えます。 + +```console +java -jar scalardb-schema-loader-.jar --config database-cassandra.properties --schema-file order-service-schema.json --coordinator +``` + +#### Schema details + +[`customer-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service-schema.json) に示されているように、Customer Service のすべてのテーブルは `customer_service` 名前空間に作成されます。 + +- `customer_service.customers`: 顧客の情報を管理するテーブル + - `credit_limit`: 貸し手が各顧客に信用枠の使用を許可する最大金額 + - `credit_total`: 各顧客が信用枠を使用してすでに使用した金額 + +[`order-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service-schema.json) に示されているように、Order Service のすべてのテーブルは `order_service` 名前空間に作成されます。 + +- `order_service.orders`: 注文情報を管理するテーブル +- `order_service.statements`: 注文明細情報を管理するテーブル +- `order_service.items`: 注文する商品の情報を管理するテーブル + +スキーマのエンティティリレーションシップダイアグラムは次のとおりです。 + +![ERD](images/ERD.png) + +### マイクロサービスを起動して初期データをロードします + +マイクロサービスを起動する前に、次のコマンドを実行してサンプルアプリケーションの Docker イメージをビルドします。 + +```console +./gradlew docker +``` + +次に、次のコマンドを実行してマイクロサービスを起動します。 + +```console +docker-compose up -d customer-service order-service +``` + +マイクロサービスを起動し、初期データが読み込まれた後、次のレコードが `customer_service.customers` テーブルに保存されるはずです。 + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +そして、次のレコードが `order_service.items` テーブルに保存される必要があります。 + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションでトランザクションを実行し、データを取得する + +次のセクションでは、サンプル電子商取引アプリケーションでトランザクションを実行し、データを取得する方法について説明します。 + +### 顧客情報を取得する + +次のコマンドを実行して、ID が `1` である顧客に関する情報を取得することから始めます。 + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。 + +```console +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000} +... +``` + +この時点では、`credit_total` は表示されません。つまり、`credit_total` の現在の値は `0` です。 + +### 注文する + +次に、次のコマンドを実行して、顧客 ID `1` にリンゴ3個とオレンジ2個を注文してもらいます。 + +:::note + +このコマンドの注文形式は `./gradlew run --args="PlaceOrder :,:,..."` です。 + +::: + +```console +./gradlew :client:run --args="PlaceOrder 1 1:3,2:2" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す出力が表示されます。 + +```console +... +{"order_id": "4ccdb21c-ac03-4b48-bcb7-cad57eac1e79"} +... +``` + +### 注文の詳細を確認する + +次のコマンドを実行して注文の詳細を確認します。`` は、前のコマンドを実行した後に表示される `order_id` の UUID に置き換えます。 + +```console +./gradlew :client:run --args="GetOrder " +``` + +`order_id` と `timestamp` の UUID が異なる、以下のような出力が表示されます。 + +```console +... +{"order": {"order_id": "4ccdb21c-ac03-4b48-bcb7-cad57eac1e79","timestamp": 1631605253126,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +### 別の注文をする + +次のコマンドを実行して、顧客 ID `1` の `credit_total` の残額を使用してメロン1個を注文します。 + +```console +./gradlew :client:run --args="PlaceOrder 1 5:1" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す出力が表示されます。 + +```console +... +{"order_id": "0b10db66-faa6-4323-8a7a-474e8534a7ee"} +... +``` + +### 注文履歴を確認する + +次のコマンドを実行して、顧客 ID `1` のすべての注文履歴を取得します。 + +```console +./gradlew :client:run --args="GetOrders 1" +``` + +`order_id` と `timestamp` の UUID が異なる以下のような出力が表示されます。これは、顧客 ID `1` のすべての注文履歴をタイムスタンプの降順で表示します。 + +```console +... +{"order": [{"order_id": "0b10db66-faa6-4323-8a7a-474e8534a7ee","timestamp": 1631605501485,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000},{"order_id": "4ccdb21c-ac03-4b48-bcb7-cad57eac1e79","timestamp": 1631605253126,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}]} +... +``` + +### クレジット合計の確認 + +次のコマンドを実行して、顧客 ID `1` のクレジット合計を取得します。 + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。これは、顧客 ID `1` が `credit_total` の `credit_limit` に達しており、これ以上注文できないことを示しています。 + +```console +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000,"credit_total": 10000} +... +``` + +次のコマンドを実行して、ブドウ1個とマンゴー1個を注文してみます。 + +```console +./gradlew :client:run --args="PlaceOrder 1 3:1,4:1" +``` + +次の出力が表示されます。これは、`credit_total` 金額が `credit_limit` 金額を超えたために注文が失敗したことを示しています。 + +```console +... +io.grpc.StatusRuntimeException: FAILED_PRECONDITION: Credit limit exceeded + at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:271) + at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:252) + at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:165) + at sample.rpc.OrderServiceGrpc$OrderServiceBlockingStub.placeOrder(OrderServiceGrpc.java:296) + at sample.client.command.PlaceOrderCommand.call(PlaceOrderCommand.java:38) + at sample.client.command.PlaceOrderCommand.call(PlaceOrderCommand.java:12) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.client.Client.main(Client.java:39) +... +``` + +### 支払いを行う + +注文を続行するには、顧客 ID `1` が支払いを行って `credit_total` の金額を減らす必要があります。 + +次のコマンドを実行して支払いを行います。 + +```console +./gradlew :client:run --args="Repayment 1 8000" +``` + +次に、次のコマンドを実行して、顧客 ID `1` の `credit_total` 金額を確認します。 + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。これは、顧客 ID `1` に支払いが適用され、`credit_total` の金額が減ったことを示しています。 + +```console +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000,"credit_total": 2000} +... +``` + +顧客 ID `1` が支払いを済ませたので、次のコマンドを実行してブドウ1個とメロン1個を注文します。 + +```console +./gradlew :client:run --args="PlaceOrder 1 3:1,4:1" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す出力が表示されます。 + +```console +... +{"order_id": "dd53dd9d-aaf4-41db-84b2-56951fed6425"} +... +``` + +## サンプルアプリケーションを停止する + +サンプルアプリケーションを停止するには、Cassandra、MySQL、およびマイクロサービスを実行している Docker コンテナを停止する必要があります。Docker コンテナを停止するには、次のコマンドを実行します。 + +```console +docker-compose down +``` + +## リファレンス - マイクロサービストランザクションの実現方法 + +注文、単一注文の取得、注文履歴の取得のトランザクションは、マイクロサービストランザクションを実現します。このセクションでは、注文を例に、Customer Service と Order Service にまたがるトランザクションの実装方法に焦点を当てます。 + +次のシーケンス図は、注文を行うトランザクションを示しています。 + +![マイクロサービストランザクションシーケンス図](images/sequence_diagram.png) + +### 1. 2フェーズコミットインターフェースを使用したトランザクションが開始されます + +クライアントが Order Service に注文リクエストを送信すると、`OrderService.placeOrder()` が呼び出され、マイクロサービストランザクションが開始されます。 + +最初に、Order Service は次のように `start()` を使用して2フェーズコミットインターフェースを使用したトランザクションを開始します。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +transaction = twoPhaseCommitTransactionManager.start(); +``` + +### 2. CRUD 操作が実行されます + +2フェーズコミットインターフェースを使用したトランザクションが開始されると、CRUD 操作が実行されます。Order Service は、次のように、注文情報を `order_service.orders` テーブルに、詳細情報を `order_service.statements` テーブルに格納します。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +// Put the order info into the `orders` table. +Order.put(transaction, orderId, request.getCustomerId(), System.currentTimeMillis()); + +int amount = 0; +for (ItemOrder itemOrder : request.getItemOrderList()) { + // Put the order statement into the `statements` table. + Statement.put(transaction, orderId, itemOrder.getItemId(), itemOrder.getCount()); + + // Retrieve the item info from the `items` table. + Optional item = Item.get(transaction, itemOrder.getItemId()); + if (!item.isPresent()) { + responseObserver.onError( + Status.NOT_FOUND.withDescription("Item not found").asRuntimeException()); + return; + } + + // Calculate the total amount. + amount += item.get().price * itemOrder.getCount(); +} +``` + +次に、Order Service は、トランザクション ID とともに Customer Service の `payment` gRPC エンドポイントを呼び出します。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +customerServiceStub.payment( + PaymentRequest.newBuilder() + .setTransactionId(transactionId) + .setCustomerId(customerId) + .setAmount(amount) + .build()); +``` + +Customer Service の `payment` エンドポイントは、まず次のように `join()` を使用してトランザクションを結合します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +private void execOperationsAsParticipant(String funcName, String transactionId, + TransactionFunction operations, + StreamObserver responseObserver) { + try { + // Join the transaction + TwoPhaseCommitTransaction transaction = twoPhaseCommitTransactionManager.join(transactionId); + + // Execute operations + T response = operations.apply(transaction); +``` + +次に、エンドポイントは顧客情報を取得し、支払い後に顧客のクレジット合計がクレジット限度額を超えているかどうかを確認します。クレジット合計がクレジット限度額を超えていない場合、エンドポイントは顧客のクレジット合計を更新します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +execOperationsAsParticipant("Payment", request.getTransactionId(), + transaction -> { + // Retrieve the customer info for the customer ID + Optional result = Customer.get(transaction, request.getCustomerId()); + if (!result.isPresent()) { + throw Status.NOT_FOUND.withDescription("Customer not found").asRuntimeException(); + } + + int updatedCreditTotal = result.get().creditTotal + request.getAmount(); + + // Check if the credit total exceeds the credit limit after payment + if (updatedCreditTotal > result.get().creditLimit) { + throw Status.FAILED_PRECONDITION + .withDescription("Credit limit exceeded") + .asRuntimeException(); + } + + // Update `credit_total` for the customer + Customer.updateCreditTotal(transaction, request.getCustomerId(), updatedCreditTotal); + + return Empty.getDefaultInstance(); + }, responseObserver +); +``` + +### 3. 2フェーズコミットプロトコルを使用してトランザクションがコミットされます + +Order Service は、支払いが成功したという更新を受信すると、トランザクションをコミットしようとします。 + +トランザクションをコミットするために、Order Service はトランザクションの準備から始めます。Order Service は、トランザクションオブジェクトから `prepare()` を呼び出し、Customer Service の `prepare` gRPC エンドポイントを呼び出します。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +transaction.prepare(); +callPrepareEndpoint(transaction.getId()); +``` + +このエンドポイントでは、Customer Service がトランザクションを再開し、トランザクションオブジェクトから `prepare()` も呼び出します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +// Resume the transaction. +transaction = twoPhaseCommitTransactionManager.resume(request.getTransactionId()); + +// Prepare the transaction. +transaction.prepare(); +``` + +同様に、Order Service と Customer Service は、トランザクションオブジェクトから `validate()` を呼び出します。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) と [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。`validate()` の詳細については、[トランザクションの検証](../../two-phase-commit-transactions.mdx#トランザクションの検証)を参照してください。 + +Order Service と Customer Service の両方でトランザクションの準備と検証が成功したら、トランザクションをコミットできます。この場合、Order Service はトランザクションオブジェクトから `commit()` を呼び出し、次に Customer Service の `commit` gRPC エンドポイントを呼び出します。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +transaction.commit(); +callCommitEndpoint(transaction.getId()); +``` + +このエンドポイントでは、Customer Service がトランザクションを再開し、トランザクションオブジェクトから `commit()` も呼び出します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +// Resume the transaction. +transaction = twoPhaseCommitTransactionManager.resume(request.getTransactionId()); + +// Commit the transaction. +transaction.commit(); +``` + +### エラー処理 + +トランザクションの実行中にエラーが発生した場合は、トランザクションをロールバックする必要があります。この場合、Order Service はトランザクションオブジェクトから `rollback()` を呼び出し、次に Customer Service の `rollback` gRPC エンドポイントを呼び出します。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +transaction.rollback(); +callRollbackEndpoint(transaction.getId()); +``` + +このエンドポイントでは、Customer Service がトランザクションを再開し、トランザクションオブジェクトから `rollback()` も呼び出します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +// Resume the transaction. +TwoPhaseCommitTransaction transaction = + twoPhaseCommitTransactionManager.resume(request.getTransactionId()); + +// Roll back the transaction. +transaction.rollback(); +``` + +ScalarDB で例外を処理する方法の詳細については、[例外の処理方法](../../api-guide.mdx#例外の処理方法)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/ERD.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/ERD.png new file mode 100644 index 00000000..c0468efa Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/ERD.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/overview.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/overview.png new file mode 100644 index 00000000..4340b4f5 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/overview.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/sequence_diagram.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/sequence_diagram.png new file mode 100644 index 00000000..0317b5f3 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/sequence_diagram.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/README.mdx new file mode 100644 index 00000000..e033cfd6 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/README.mdx @@ -0,0 +1,318 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# マルチストレージトランザクションをサポートするサンプルアプリケーションを作成する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、ScalarDB のマルチストレージトランザクション機能をサポートするサンプルアプリケーションを作成する方法について説明します。 + +## 概要 + +このチュートリアルでは、ScalarDB の[マルチストレージトランザクション](../../multi-storage-transactions.mdx)機能を使用して、アイテムを注文し、信用枠で支払うことができるサンプル電子商取引アプリケーションを作成するプロセスを示します。 + +このチュートリアルでは、Cassandra と MySQL の両方を使用するアプリケーションを構築します。ScalarDB のマルチストレージトランザクション機能を使用すると、Cassandra と MySQL の両方にまたがるトランザクションを実行できます。 + +![概要](images/overview.png) + +:::note + +サンプルアプリケーションは ScalarDB の使用方法を示すことに重点を置いているため、アプリケーション固有のエラー処理、認証処理、および同様の機能はサンプルアプリケーションに含まれていません。ScalarDB での例外処理の詳細については、[例外の処理方法](../../api-guide.mdx#例外の処理方法)を参照してください。 + +::: + +### このサンプルアプリケーションで実行できること + +サンプルアプリケーションは、次の種類のトランザクションをサポートしています: + +- 顧客情報を取得します。 +- 信用枠を使用して注文を行います。 + - 注文のコストが顧客の信用限度額を下回っているかどうかを確認します。 + - チェックが成功した場合は、注文履歴を記録し、顧客が支払った金額を更新します。 +- 注文 ID で注文情報を取得します。 +- 顧客 ID で注文情報を取得します。 +- 支払いを行います。 + - 顧客が支払った金額を減らします。 + +## このサンプルアプリケーションの前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10以降 ([Docker Compose](https://docs.docker.com/compose/install/) V2以降) + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../../requirements.mdx)を参照してください。 + +::: + +## ScalarDB のセットアップ + +次のセクションでは、ScalarDB のマルチストレージトランザクション機能をサポートするサンプルアプリケーションをセットアップする方法について説明します。 + +### ScalarDB サンプルリポジトリをクローンする + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリをクローンします。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、サンプルアプリケーションが含まれているディレクトリに移動します。 + +```console +cd scalardb-samples/multi-storage-transaction-sample +``` + +### Cassandra と MySQL を起動します + +[`database.properties`](https://github.com/scalar-labs/scalardb-samples/tree/master/multi-storage-transaction-sample/database.properties) に示されているように、Cassandra と MySQL はサンプルアプリケーション用にすでに設定されています。ScalarDB のマルチストレージトランザクション機能の設定の詳細については、[マルチストレージトランザクションをサポートするように ScalarDB を設定する方法](../../multi-storage-transactions.mdx#マルチストレージトランザクションをサポートするように-scalardb-を設定する方法)を参照してください。 + +サンプルアプリケーションの Docker コンテナに含まれている Cassandra と MySQL を起動するには、Docker が実行されていることを確認してから、次のコマンドを実行します。 + +```console +docker-compose up -d +``` + +:::note + +開発環境によっては、Docker コンテナの起動に1分以上かかる場合があります。 + +::: + +### スキーマをロードする + +サンプルアプリケーションのデータベーススキーマ (データを整理する方法) は、すでに [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/master/multi-storage-transaction-sample/schema.json) で定義されています。 + +スキーマを適用するには、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases)ページに移動し、使用する ScalarDB のバージョンに一致する ScalarDB Schema Loader を `scalardb-samples/multi-storage-transaction-sample` フォルダーにダウンロードします。 + +次に、次のコマンドを実行します。`` は、ダウンロードした ScalarDB Schema Loader のバージョンに置き換えます。 + +```console +java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator +``` + +#### スキーマの詳細 + +サンプルアプリケーションの [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/master/multi-storage-transaction-sample/schema.json) に示されているように、すべてのテーブルは `customer` および `order` 名前空間に作成されます。 + +- `customer.customers`: 顧客の情報を管理するテーブル + - `credit_limit`: 貸し手が各顧客に信用枠の使用を許可する最大金額 + - `credit_total`: 各顧客が信用枠を使用してすでに使用した金額 +- `order.orders`: 注文情報を管理するテーブル +- `order.statements`: 注文明細情報を管理するテーブル +- `order.items`: 注文するアイテムの情報を管理するテーブル + +スキーマのエンティティリレーションシップダイアグラムは次のとおりです。 + +![ERD](images/ERD.png) + +### 初期データをロードする + +Docker コンテナが起動したら、次のコマンドを実行して初期データをロードします。 + +```console +./gradlew run --args="LoadInitialData" +``` + +初期データがロードされた後、次のレコードがテーブルに保存される必要があります。 + +**`customer.customers` テーブル** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`order.items` テーブル** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションでトランザクションを実行し、データを取得する + +次のセクションでは、サンプル電子商取引アプリケーションでトランザクションを実行し、データを取得する方法について説明します。 + +### 顧客情報を取得する + +次のコマンドを実行して、ID が `1` である顧客に関する情報を取得することから始めます。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 0} +... +``` + +### 注文する + +次に、次のコマンドを実行して、顧客 ID `1` にリンゴ3個とオレンジ2個を注文してもらいます。 + +:::note + +このコマンドの注文形式は `./gradlew run --args="PlaceOrder :,:,..."` です。 + +::: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す出力が表示されます。 + +```console +... +{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e"} +... +``` + +### 注文の詳細を確認する + +次のコマンドを実行して注文の詳細を確認します。`` は、前のコマンドを実行した後に表示される `order_id` の UUID に置き換えます。 + +```console +./gradlew run --args="GetOrder " +``` + +`order_id` と `timestamp` の UUID が異なる、以下のような出力が表示されます。 + +```console +... +{"order": {"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +### 別の注文をする + +次のコマンドを実行して、顧客 ID `1` の `credit_total` の残額を使用してメロン1個を注文します。 + +```console +./gradlew run --args="PlaceOrder 1 5:1" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す出力が表示されます。 + +```console +... +{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d"} +... +``` + +### 注文履歴を確認する + +次のコマンドを実行して、顧客 ID `1` のすべての注文履歴を取得します。 + +```console +./gradlew run --args="GetOrders 1" +``` + +`order_id` と `timestamp` の UUID が異なる以下のような出力が表示されます。これは、顧客 ID `1` のすべての注文履歴をタイムスタンプの降順で表示します。 + +```console +... +{"order": [{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000},{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d","timestamp": 1650948412766,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000}]} +... +``` + +### クレジット合計の確認 + +次のコマンドを実行して、顧客 ID `1` のクレジット合計を取得します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。これは、顧客 ID `1` が `credit_total` の `credit_limit` に達しており、これ以上注文できないことを示しています。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +``` + +次のコマンドを実行して、ブドウ1個とマンゴー1個を注文してみます。 + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +次の出力が表示されます。これは、`credit_total` 金額が `credit_limit` 金額を超えたために注文が失敗したことを示しています。 + +```console +... +java.lang.RuntimeException: Credit limit exceeded + at sample.Sample.placeOrder(Sample.java:205) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:33) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:8) + at picocli.CommandLine.executeUserObject(CommandLine.java:1783) + at picocli.CommandLine.access$900(CommandLine.java:145) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2141) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2108) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:1975) + at picocli.CommandLine.execute(CommandLine.java:1904) + at sample.command.SampleCommand.main(SampleCommand.java:35) +... +``` + +### 支払いを行う + +注文を続行するには、顧客 ID `1` が支払いを行って `credit_total` の金額を減らす必要があります。 + +次のコマンドを実行して支払いを行います。 + +```console +./gradlew run --args="Repayment 1 8000" +``` + +次に、次のコマンドを実行して、顧客 ID `1` の `credit_total` 金額を確認します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +次の出力が表示されます。これは、顧客 ID `1` に支払いが適用され、`credit_total` の金額が減ったことを示しています。 + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 2000} +... +``` + +顧客 ID `1` が支払いを済ませたので、次のコマンドを実行してブドウ1個とメロン1個を注文します。 + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +以下のように、`order_id` の UUID が異なる、注文が成功したことを示す出力が表示されます。 + +```console +... +{"order_id": "8911cab3-1c2b-4322-9386-adb1c024e078"} +... +``` + +## サンプルアプリケーションを停止します + +サンプルアプリケーションを停止するには、次のコマンドを実行して Docker コンテナを停止します。 + +```console +docker-compose down +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/ERD.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/ERD.png new file mode 100644 index 00000000..02100437 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/ERD.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/overview.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/overview.png new file mode 100644 index 00000000..16749f3b Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/overview.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/scalardb-analytics-postgresql-sample/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/scalardb-analytics-postgresql-sample/README.mdx new file mode 100644 index 00000000..8f0c7c95 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/scalardb-analytics-postgresql-sample/README.mdx @@ -0,0 +1,309 @@ +--- +tags: + - Community +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics with PostgreSQL を使用してサンプルデータに対して分析クエリを実行する + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、ScalarDB Analytics with PostgreSQL を使用してサンプルデータに対して分析クエリを実行する方法について説明します。 + +## 概要 + +このサンプルチュートリアルでは、単一テーブルクエリと複数テーブルクエリの2種類のクエリを実行する方法を示します。 + +### このサンプルチュートリアルで実行できること + +このサンプルチュートリアルでは、次の種類のクエリを実行する方法を示します。 + +- データを読み取り、要約を計算します。 +- 複数のストレージにまたがるテーブルを結合します。 + +:::note + +このサンプルチュートリアルでインポートされたテーブルに対して、PostgreSQL がサポートする任意のクエリを実行できます。ScalarDB Analytics with PostgreSQL は PostgreSQL がサポートするすべてのクエリをサポートしているため、例に示されている結合、集計、フィルタリング、順序付けだけでなく、ウィンドウ関数、ラテラル結合、さまざまな分析操作も使用できます。 + +PostgreSQL がサポートするクエリの種類を確認するには、[PostgreSQL ドキュメント](https://www.postgresql.org/docs/current/index.html)を参照してください。 + +::: + +## 前提条件 + +- [Docker](https://www.docker.com/get-started/) 20.10以降、および [Docker Compose](https://docs.docker.com/compose/install/) V2以降 +- [psql](https://www.postgresql.org/docs/current/app-psql.html) + +## ScalarDB Analytics with PostgreSQL を設定する + +まず、ScalarDB Analytics with PostgreSQL を使用して分析クエリを実行するためにデータベースを設定する必要があります。まだデータベースを設定していない場合は、[ScalarDB Analytics with PostgreSQL の使用開始](../../scalardb-analytics-postgresql/getting-started.mdx)の手順に従ってください。 + +### ScalarDB のスキーマの詳細 + +このサンプルチュートリアルでは、ScalarDB データベースに次のスキーマを持つテーブルがあります。 + +```mermaid +erDiagram + "dynamons.customer" ||--|{ "postgresns.orders" : "custkey" + "dynamons.customer" { + int c_custkey + text c_name + text c_address + int c_nationkey + text c_phone + double c_acctbal + text c_mktsegment + text c_comment + } + "postgresns.orders" ||--|{ "cassandrans.lineitem" : "orderkey" + "postgresns.orders" { + int o_orderkey + int o_custkey + text o_orderstatus + double o_totalprice + text o_orderdate + text o_orderpriority + text o_clerk + int o_shippriority + text o_comment + } + "cassandrans.lineitem" { + int l_orderkey + int l_partkey + int l_suppkey + int l_linenumber + double l_quantity + double l_extendedprice + double l_discount + double l_tax + text l_returnflag + text l_linestatus + text l_shipdate + text l_commitdate + text l_receiptdate + text l_shipinstruct + text l_shipmode + text l_comment + } +``` + +参考までに、この図には次の内容が示されています。 + +- `dynamons`、`postgresns`、`cassandrans`。それぞれ DynamoDB、PostgreSQL、Cassandra のバックエンドストレージにマップされる名前空間。 +- `dynamons.customer`。顧客に関する情報を表すテーブル。このテーブルには、顧客キー、名前、住所、電話番号、口座残高などの属性が含まれます。 +- `postgresns.orders`。顧客が行った注文に関する情報を含むテーブル。このテーブルには、注文キー、顧客キー、注文ステータス、注文日、注文優先度などの属性が含まれます。 +- `cassandrans.lineitem`。注文に関連付けられた明細項目を表すテーブル。このテーブルには、注文キー、部品キー、サプライヤーキー、数量、価格、出荷日などの属性が含まれます。 + +### PostgreSQL のスキーマの詳細 + +ScalarDB の設定時に Schema Importer を実行すると、ScalarDB データベースのテーブルスキーマを PostgreSQL データベースにインポートできます。より正確には、ScalarDB データベースの各 `namespace_name.table_name` テーブルに対して、PostgreSQL データベースに `namespace_name._table_name` の外部テーブルと `namespace_name.table_name` のビューが作成されます。 + +作成された外部テーブルには、ScalarDB テーブルと同じ列と、ScalarDB が内部で管理するトランザクションメタデータ列が含まれます。作成されたビューは、外部テーブルからトランザクションメタデータ列を除外するように定義されているため、作成されたビューには ScalarDB テーブルと同じ列のみが含まれます。 + +ScalarDB テーブルのスキーマは `schema.json` にあります。たとえば、`dynamons.customer` テーブルは次のように定義されています。 + +```json + "dynamons.customer": { + "transaction": true, + "partition-key": [ + "c_custkey" + ], + "columns": { + "c_custkey": "INT", + "c_name": "TEXT", + "c_address": "TEXT", + "c_nationkey": "INT", + "c_phone": "TEXT", + "c_acctbal": "DOUBLE", + "c_mktsegment": "TEXT", + "c_comment": "TEXT" + } + }, +``` + +PostgreSQL データベース内の `dynamons._customer` の外部テーブルを表示するには、次のコマンドを実行し、プロンプトが表示されたら PostgreSQL ユーザーパスワードを入力します。 + +```console +psql -U postgres -h localhost test -c '\d dynamons._customer'; +``` + +パスワードを入力すると、次の出力が表示されます。これには、`dynamons.customer` テーブルと同じ `c_` 列が表示されます。 + +```console + Foreign table "dynamons._customer" + Column | Type | Collation | Nullable | Default | FDW options +------------------------+------------------+-----------+----------+---------+------------- + c_custkey | integer | | | | + c_name | text | | | | + c_address | text | | | | + c_nationkey | integer | | | | + c_phone | text | | | | + c_acctbal | double precision | | | | + c_mktsegment | text | | | | + c_comment | text | | | | + tx_id | text | | | | + tx_version | integer | | | | + tx_state | integer | | | | + tx_prepared_at | bigint | | | | + tx_committed_at | bigint | | | | + before_tx_id | text | | | | + before_tx_version | integer | | | | + before_tx_state | integer | | | | + before_tx_prepared_at | bigint | | | | + before_tx_committed_at | bigint | | | | + before_c_name | text | | | | + before_c_address | text | | | | + before_c_nationkey | integer | | | | + before_c_phone | text | | | | + before_c_acctbal | double precision | | | | + before_c_mktsegment | text | | | | + before_c_comment | text | | | | +Server: multi_storage_dynamodb +FDW options: (namespace 'dynamons', table_name 'customer') +``` + +外部テーブルを見るとわかるように、テーブルにはトランザクションメタデータ列も含まれています。これらの列は、Read Committed 分離レベルを確保するために必要です。 + +`dynamons.customer` のビューを表示するには、次のコマンドを実行し、プロンプトが表示されたら PostgreSQL ユーザーパスワードを入力します。 + +```console +psql -U postgres -h localhost test -c '\d dynamons.customer'; +``` + +パスワードを入力すると、次の出力が表示されます。 + +```console + View "dynamons.customer" + Column | Type | Collation | Nullable | Default +--------------+------------------+-----------+----------+--------- + c_custkey | integer | | | + c_name | text | | | + c_address | text | | | + c_nationkey | integer | | | + c_phone | text | | | + c_acctbal | double precision | | | + c_mktsegment | text | | | + c_comment | text | | | +``` + +このビューの列定義は、ScalarDB データベースの元のテーブルと同じです。このビューは、トランザクションメタデータ列を解釈して、Read Committed 分離レベルで有効なデータのみを公開するために、上で説明した外部テーブルに基づいて作成されます。 + +:::note + +通常、外部テーブルに直接アクセスする必要はありません。代わりに、ビューを ScalarDB データベース内のテーブルと同等にすることができます。 + +::: + +ScalarDB と PostgreSQL 間の型マッピングの詳細については、[ScalarDB と他のデータベース間のデータ型マッピング](../../schema-loader.mdx#scalardb-と他のデータベース間のデータ型マッピング) を参照してください。 + +## 分析クエリを実行する + +次のセクションでは、データの読み取り、サマリーの計算、複数のストレージにまたがるテーブルの結合方法について説明します。 + +### データの読み取りとサマリーの計算 + +Cassandra バックエンドに保存されている実際のデータを使用して `cassandrans.lineitem` からデータを読み取り、データを集計して順序付けられた明細項目の複数のサマリーを計算するクエリを実行できます。 + +クエリを実行するには、次のコマンドを実行して psql ターミナルにログインします。 + +```console +psql -U postgres -h localhost test +``` + +パスワードを入力した後、psql ターミナルに次のクエリを入力します。 + +```console +SELECT + l_returnflag, + l_linestatus, + sum(l_quantity) AS sum_qty, + sum(l_extendedprice) AS sum_base_price, + sum(l_extendedprice * (1 - l_discount)) AS sum_disc_price, + sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) AS sum_charge, + avg(l_quantity) AS avg_qty, + avg(l_extendedprice) AS avg_price, + avg(l_discount) AS avg_disc, + count(*) AS count_order +FROM + cassandrans.lineitem +WHERE + to_date(l_shipdate, 'YYYY-MM-DD') <= date '1998-12-01' - 3 +GROUP BY + l_returnflag, + l_linestatus +ORDER BY + l_returnflag, + l_linestatus; +``` + +次の出力が表示されます。 + +```console + l_returnflag | l_linestatus | sum_qty | sum_base_price | sum_disc_price | sum_charge | avg_qty | avg_price | avg_disc | count_order +--------------+--------------+---------+--------------------+--------------------+--------------------+---------------------+--------------------+---------------------+------------- + A | F | 1519 | 2374824.6560430005 | 1387363.5818635763 | 1962762.9341866106 | 26.6491228070175439 | 41663.590456894744 | 0.4150182982456142 | 57 + N | F | 98 | 146371.22954200002 | 85593.92837883368 | 121041.52567369482 | 32.6666666666666667 | 48790.409847333336 | 0.4098473333333333 | 3 + N | O | 5374 | 8007373.247144971 | 4685645.630765834 | 6624209.157932242 | 24.4272727272727273 | 36397.15112338623 | 0.414759749999999 | 220 + R | F | 1461 | 2190869.967642001 | 1284177.8484816086 | 1814150.7929095028 | 25.1896551724137931 | 37773.62013175864 | 0.41323520689655185 | 58 +(4 rows) +``` + +### 複数のストレージにまたがるテーブルを結合する + +クエリを実行して、3つのバックエンドストレージに接続されているテーブルを結合し、特定の日付に最も高い収益を持つ未出荷の注文を計算することもできます。 + +クエリを実行するには、次のコマンドを実行して psql ターミナルにログインします。 + +```console +psql -U postgres -h localhost test +``` + +パスワードを入力した後、psql ターミナルに次のクエリを入力します。 + +```console +SELECT + l_orderkey, + sum(l_extendedprice * (1 - l_discount)) AS revenue, + o_orderdate, + o_shippriority +FROM + dynamons.customer, + postgresns.orders, + cassandrans.lineitem +WHERE + c_mktsegment = 'AUTOMOBILE' + AND c_custkey = o_custkey + AND l_orderkey = o_orderkey + AND o_orderdate < '1995-03-15' + AND l_shipdate > '1995-03-15' +GROUP BY + l_orderkey, + o_orderdate, + o_shippriority +ORDER BY + revenue DESC, + o_orderdate, + l_orderkey +LIMIT 10; +``` + +次の出力が表示されます。 + +```console + l_orderkey | revenue | o_orderdate | o_shippriority +------------+--------------------+-------------+---------------- + 1071617 | 128186.94002748765 | 1995-03-10 | 0 + 1959075 | 33104.49713665398 | 1994-12-23 | 0 + 430243 | 19476.107574179696 | 1994-12-24 | 0 +(3 rows) +``` + +## ScalarDB Analytics with PostgreSQL とデータベースを停止する + +ScalarDB Analytics with PostgreSQL とデータベースを停止するには、次のコマンドを実行して Docker コンテナを停止します。 + +```console +docker-compose down +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/scalardb-analytics-spark-sample/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/scalardb-analytics-spark-sample/README.mdx new file mode 100644 index 00000000..b76921e0 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/scalardb-analytics-spark-sample/README.mdx @@ -0,0 +1,457 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsJapanese +--- + +# ScalarDB Analytics をはじめよう + +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、ScalarDB Analytics を使用してサンプルデータに対して分析クエリを実行する方法について説明します。ソースコードは [https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-analytics-spark-sample](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-analytics-spark-sample) で入手できます。 + +現在のバージョンの ScalarDB Analytics は、実行エンジンとして Apache Spark を活用しています。Spark カスタムカタログを使用して、ScalarDB 管理下データソースと ScalarDB 管理外データソースの統合ビューを提供します。ScalarDB Analytics を使用すると、これらのデータソースのテーブルをネイティブ Spark テーブルとして扱うことができ、任意の Spark SQL クエリをシームレスに実行できます。たとえば、Cassandra に格納されているテーブルを PostgreSQL のテーブルと結合して、複数のデータソースにまたがる分析を簡単に実行できます。 + +## サンプルアプリケーションの概要 + +このサンプルチュートリアルでは、Sparkの設定によってScalarDB Analyticsを有効にし、ScalarDB Analytics から提供されるテーブルに対して `spark-sql` を用いたインタラクティブな分析を実行する方法をしめします。 + +## このサンプルアプリケーションの前提条件 + +- [Docker](https://www.docker.com/get-started/) 20.10以降と [Docker Compose](https://docs.docker.com/compose/install/) V2以降 + + + +## ステップ 1: ScalarDB Analytics をセットアップする + +### ScalarDB サンプルリポジトリをクローンする + +**ターミナル** を開き、次のコマンドを実行して ScalarDB サンプルリポジトリをクローンします: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行してサンプルアプリケーションを含むディレクトリに移動します: + +```console +cd scalardb-samples/scalardb-analytics-spark-sample +``` + +### ライセンス情報を設定する + +ScalarDB Analytics では、Spark 設定で有効なライセンス情報を指定する必要があります。ライセンスの詳細は、**spark-defaults.conf** ファイルで指定できます。 + +Spark インストールの **conf** ディレクトリにある **spark-defaults.conf** ファイルを開きます。次に、`` をライセンスキーに置き換え、`` をライセンス証明書の PEM エンコードされた内容に置き換えます。 + +```console +spark.sql.catalog.test_catalog.license.key +spark.sql.catalog.test_catalog.license.cert_pem +``` + +ScalarDB Analytics を設定するために **spark-defaults.conf** で必要な項目の詳細については、[ScalarDB Analytics の設定](#scalardb-analytics-の設定)を参照してください。 + +## ステップ 2: サンプルデータベースをセットアップする + +サンプルデータベースをセットアップするには、次のコマンドを実行します: + +```console +docker compose up -d --wait +``` + +このコマンドは、PostgreSQL、Cassandra、MySQL の3つのサービスをローカルで起動します。 + +- **PostgreSQL:** 単独で使用されます (ScalarDB 管理外)。 +- **Cassandra および MySQL:** ScalarDB のバックエンドデータベースとして使用されます (ScalarDB 管理下)。 + +このガイドでは、PostgreSQL は ScalarDB トランザクションによって管理されない **ScalarDB 管理外データベース** と呼ばれ、Cassandra および DynamoDB は ScalarDB トランザクションによって管理される **ScalarDB 管理下データベース** と呼ばれます。 + +ScalarDB 管理外データベースについては、Docker コンテナが初期化されるとサンプルデータが自動的に読み込まれるため、追加の手順は必要ありません。 ScalarDB 管理下データベースについては、コンテナを起動した後、次のコマンドを実行してサンプルデータをロードします: + +```console +docker compose run --rm sample-data-loader +``` + +セットアップが完了すると、次のテーブルが使用可能になります: + +- PostgreSQL: + - `sample_ns.customer` +- ScalarDB (Cassandra): + - `cassandrans.lineitem` +- ScalarDB (MySQL): + - `mysqlns.order` + +ScalarDB 内では、`cassandrans` と `mysqlns` がそれぞれ Cassandra と MySQL にマッピングされます。 + +列定義やデータ型を含むテーブルスキーマの詳細については、[スキーマの詳細](#スキーマの詳細)を参照してください。サンプルデータがこれらのテーブルに正常にロードされていることを確認してください。 + +## ステップ 3: Spark SQL コンソールを起動する + +Spark SQL コンソールを起動するには、次のコマンドを実行します: + +```console +docker compose run --rm spark-sql +``` + +Spark SQL コンソールを起動すると、**spark-defaults.conf** の設定で ScalarDB Analytics カタログが初期化され、`test_catalog` という名前の Spark カタログとして登録されます。 + +### 名前空間マッピング + +データソース内の各テーブルは、以下のようにSpark SQLのテーブルにマッピングされます。 + +- PostgreSQL: + - `test_catalog.postgresql.sample_ns.customer` +- ScalarDB (Cassandra ): + - `test_catalog.scalardb.cassandrans.lineitem` +- ScalarDB (MySQL): + - `test_catalog.scalardb.mysqlns.orders` + +各データソースのテーブル名をSpark SQLのテーブル名にマッピングする規則の詳細は、[名前空間マッピングの詳細](#名前空間マッピングの詳細)を参照してください。 + +さらに、ScalarDB Analytics は ScalarDB テーブルに対して、一般的なユースケースを簡単にするために、WAL 解釈ビューを提供します。このサンプルアプリケーションでは、次の WAL 解釈ビューが利用できます: + +- ScalarDB (Cassandra ): + - `test_catalog.view.scalardb.cassandrans.lineitem` +- ScalarDB (MySQL): + - `test_catalog.view.scalardb.mysqlns.orders` + +ほとんどの場合、WAL 解釈ビューは生のテーブルよりも便利です。このチュートリアルでは、ScalarDB のテーブルについては WAL 解釈ビューを使用します。WAL 解釈ビューの詳細な情報 (使用例や利点など) については、[ScalarDB テーブル用の WAL 解釈ビュー](#scalardb-テーブル用の-wal-解釈ビュー)を参照してください。 + +## ステップ 4: 分析クエリを実行する + +これですべての設定が完了し、Spark SQL コンソールを使用してサンプルデータに対して分析クエリを実行できます。 + +### データの読み取りとサマリーの計算 + +次のクエリを実行して、Cassandra の `test_catalog.scalardb.cassandrans.lineitem` からデータを取得し、返品フラグとラインステータス別にグループ化されたラインアイテムの合計数量、平均価格、合計収益などの集計メトリックを計算できます。 + +```sql +SELECT + l_returnflag, + l_linestatus, + sum(l_quantity) AS sum_qty, + sum(l_extendedprice) AS sum_base_price, + sum(l_extendedprice * (1 - l_discount)) AS sum_disc_price, + sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) AS sum_charge, + avg(l_quantity) AS avg_qty, + avg(l_extendedprice) AS avg_price, + avg(l_discount) AS avg_disc, + count(*) AS count_order +FROM + test_catalog.view.scalardb.cassandrans.lineitem +WHERE + to_date(l_shipdate, 'yyyy-MM-dd') <= date '1998-12-01' - 3 +GROUP BY + l_returnflag, + l_linestatus +ORDER BY + l_returnflag, + l_linestatus; +``` + +次の出力が表示されます: + +```console +A F 1519 2374824.6560278563 1387364.2207725341 1962763.4654265852 26.649122807017545 41663.590456629056 0.41501802923479575 57 +N F 98 146371.2295412012 85593.96776336085 121041.55837332775 32.666666666666664 48790.409847067065 0.40984706454007996 3 +N O 5374 8007373.247086477 4685647.785126835 6624210.945739046 24.427272727272726 36397.15112312035 0.4147594809559689 220 +RF 1461 2190869.9676265526 1284178.4378283697 1814151.2807494882 25.189655172413794 37773.62013149229 0.41323493790730753 58 +``` + +### 複数のデータソースにまたがるテーブルを結合 + +次のクエリを実行して、ScalarDB 管理下テーブルと ScalarDB 管理外テーブルの両方を含む複数のデータソースのテーブルを結合することもできます。このクエリは、PostgreSQL、MySQL、Cassandra の顧客、注文、明細データを結合し、特定の日付の収益が最も高い未出荷の注文を特定します。 + +```sql +SELECT + l_orderkey, + sum(l_extendedprice * (1 - l_discount)) AS revenue, + o_orderdate, + o_shippriority +FROM + test_catalog.postgresql.sample_ns.customer, + test_catalog.scalardb.mysqlns.orders, + test_catalog.scalardb.cassandrans.lineitem +WHERE + c_mktsegment = 'AUTOMOBILE' + AND c_custkey = o_custkey + AND l_orderkey = o_orderkey + AND o_orderdate < '1995-03-15' + AND l_shipdate > '1995-03-15' +GROUP BY + l_orderkey, + o_orderdate, + o_shippriority +ORDER BY + revenue DESC, + o_orderdate, + l_orderkey +LIMIT 10; +``` + +次の出力が表示されます: + +```console +1071617 128186.99915996166 1995-03-10 0 +1959075 33104.51278645416 1994-12-23 0 +430243 19476.115819260962 1994-12-24 0 +``` + +:::note + +このサンプルチュートリアルでインポートされたテーブルに対して、Apache Spark および Spark SQL がサポートする任意のクエリを実行することもできます。ScalarDB Analytics は Spark SQL がサポートするすべてのクエリをサポートしているため、例に示されている選択 (フィルタリング)、結合、集計、順序付けだけでなく、ウィンドウ関数、ラテラル結合、その他のさまざまな操作も実行できます。 + +Spark SQL がサポートするクエリの種類を確認するには、[Spark SQL ドキュメント](https://spark.apache.org/docs/latest/sql-ref.html)を参照してください。 + +::: + +## ステップ 5: サンプルアプリケーションを停止する + +サンプルアプリケーションを停止し、関連付けられているすべてのボリュームを削除するには、次のコマンドを実行します。このアクションにより、すべてのサービスがシャットダウンされ、ボリュームに保存されているすべての永続データが削除され、アプリケーションの状態がリセットされます: + +```console +docker compose down -v +``` + +## リファレンス + +このセクションには、設定やスキーマの詳細など、ScalarDB Analytics に関連するその他の詳細が含まれています。 + +### ScalarDB Analytics の設定 + +ScalarDB Analytics の設定は、`spark-defaults.conf` ファイルなどの Spark の設定によって行います。このセクションでは、このサンプルアプリケーションでの ScalarDB Analytics の設定について簡単に説明します。 + +#### 一般的な設定 + +以下は、ScalarDB Analytics の一般的な設定です: + +```console +spark.sql.catalog.test_catalog com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog +spark.sql.extensions com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions +``` + +最初の行は、Spark カタログプラグインの実装クラスを指定します。Spark SQL で ScalarDB Analytics カタログを有効にするには、常にこれを `com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog` に設定する必要があります。 + +:::note + +カタログ名として任意の文字列を設定できます。この例では `test_catalog` です。設定されたカタログ名は、Spark SQL クエリのテーブル識別子の一部として使用されます。 + +::: + +2 行目は、Spark SQL 拡張実装クラスを指定します。これは、前述の `spark.sql.catalog.test_catalog` 設定とともに、常に `com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions` に設定する必要があります。 + +#### ライセンス情報 + +以下は、ScalarDB Analytics のライセンス設定です: + +```apacheconf +spark.sql.catalog.test_catalog.license.key +spark.sql.catalog.test_catalog.license.cert_pem +``` + +これらの行は、ScalarDB Analytics のライセンス情報を提供します。上で説明したように、Spark SQL コンソールを起動する前に、プレースホルダーをライセンス情報に置き換える必要があります。 + +#### ScalarDB 管理データベースのデータソース設定 + +以下は、ScalarDB Analytics の ScalarDB 管理データベースのデータソース設定です。 + +```apacheconf +spark.sql.catalog.test_catalog.data_source.scalardb.type scalardb +spark.sql.catalog.test_catalog.data_source.scalardb.config_path /etc/scalardb.properties +``` + +最初の行は、データソースの種類を指定します。ScalarDB 管理下データベースをデータソースとして設定するには、常にこれを `scalardb` に設定する必要があります。2 行目は、ScalarDB データソースの設定ファイルへのパスを指定します。以上が ScalarDB データソースに必要な設定です。 + +:::note + +データソース名として任意の文字列を設定できます。この例では `scalardb` です。設定されたデータソース名は、Spark SQL クエリのテーブル識別子の一部として使用されます。 + +::: + +#### ScalarDB 管理外データベースのデータソース設定 + +ScalarDB Analytics の ScalarDB 管理外データベースのデータソース設定は次のとおりです: + +```apacheconf +spark.sql.catalog.test_catalog.data_source.postgresql.type postgresql +spark.sql.catalog.test_catalog.data_source.postgresql.host postgres +spark.sql.catalog.test_catalog.data_source.postgresql.port 5432 +spark.sql.catalog.test_catalog.data_source.postgresql.username postgres +spark.sql.catalog.test_catalog.data_source.postgresql.password postgres +spark.sql.catalog.test_catalog.data_source.postgresql.database sampledb +``` + +これらの行は、PostgreSQL を ScalarDB 管理外データベースのデータソースとして設定します。最初の行はデータソースの種類を指定し、残りの行はデータソース固有の設定、この例では PostgreSQL データソースの接続情報を指定します。データソース固有の設定は、データソースの種類によって異なります。 + +:::note + +ScalarDB データソースと同様に、データソース名として任意の文字列 (この例では `postgresql`) を設定できます。 + +::: + +### スキーマの詳細 + +次のエンティティ関係図は、PostgreSQL、MySQL、Cassandra のテーブル間の関係を示しており、外部キーによって顧客、注文、明細項目がリンクされています。 + +```mermaid +erDiagram + "postgresql.sample_ns.customer" ||--|{ "scalardb.mysqlns.orders" : "custkey" + "postgresql.sample_ns.customer" { + int c_custkey + text c_name + text c_address + int c_nationkey + text c_phone + double c_acctbal + text c_mktsegment + text c_comment + } + "scalardb.mysqlns.orders" ||--|{ "scalardb.cassandrans.lineitem" : "orderkey" + "scalardb.mysqlns.orders" { + int o_orderkey + int o_custkey + text o_orderstatus + double o_totalprice + text o_orderdate + text o_orderpriority + text o_clerk + int o_shippriority + text o_comment + } + "scalardb.cassandrans.lineitem" { + int l_orderkey + int l_partkey + int l_suppkey + int l_linenumber + double l_quantity + double l_extendedprice + double l_discount + double l_tax + text l_returnflag + text l_linestatus + text l_shipdate + text l_commitdate + text l_receiptdate + text l_shipinstruct + text l_shipmode + text l_comment + } +``` + +- `postgresql.sample_ns.customer` は PostgreSQL のテーブルであり、ScalarDB によって管理されていません。 +- `scalardb.mysqlns.orders` と `scalardb.cassandrans.lineitem` は ScalarDB のテーブルであり、それぞれ MySQL と Cassandra にマッピングされています。 + +テーブルの簡単な説明は次のとおりです: + +- **`postgresql.sample_ns.customer`.** 顧客に関する情報を表すテーブル。このテーブルには、顧客キー、名前、住所、電話番号、口座残高などの属性が含まれます。 +- **`scalardb.mysqlns.orders`.** 顧客が行った注文に関する情報を含むテーブル。このテーブルには、注文キー、顧客キー、注文ステータス、注文日、注文優先度などの属性が含まれます。 +- **`scalardb.cassandrans.lineitem`.** 注文に関連付けられた明細項目を表すテーブル。このテーブルには、注文キー、部品キー、サプライヤーキー、数量、価格、出荷日などの属性が含まれます。 + +### 名前空間マッピングの詳細 + +設定された各データソースのテーブルは、次のフォーマットで Spark SQL 識別子にマッピングされます: + +```console +...`. +``` + +テーブル識別子の各部分について、以下に説明します。 + +- **``.** spark-defaults.conf で設定されたカタログ名。これは、Spark SQL で ScalarDB Analytics カタログを識別します。 +- **``.** spark-defaults.conf で設定されたデータソース名。postgresql や scalardb など、特定の種類のデータソースを表します。 +- **``.** データソース内の名前空間名。例: + - PostgreSQL や MySQL などの RDBMS では、これはスキーマに対応します。 + - Cassandra などの NoSQL データベースでは、これはキースペースを参照する場合があります。 +- **``.** 名前空間内のテーブルの名前。 + +この例では、次のテーブルが利用可能です: + +- PostgreSQL: + - test_catalog.postgresql.sample_ns.customer +- ScalarDB (Cassandra): + - test_catalog.scalardb.cassandrans.lineitem +- ScalarDB (MySQL): + - test_catalog.scalardb.mysqlns.orders + +このマッピングにより、Spark SQL を使用して、さまざまなデータソースのテーブルにシームレスにアクセスしてクエリを実行できます。 + +### ScalarDB テーブル用の WAL 解釈ビュー + +トランザクション処理を有効にした ScalarDB のテーブルには、データベースに格納されている生のテーブルにトランザクションメタデータ列が含まれます。ScalarDB Analytics はデータベース内の生のテーブルを直接 Spark SQL テーブルにマッピングするため、Spark SQL からこれらのテーブルを参照するとトランザクションメタデータ列が含まれます。次のコマンドを実行すると、トランザクションメタデータ列が含まれていることが確認できます: + +```sql +DESCRIBE test_catalog.scalardb.mysqlns.orders; +``` + +次の出力が表示されます: + +```console +o_orderkey int +o_custkey int +o_orderstatus string +o_totalprice double +o_orderdate string +o_orderpriority string +o_clerk string +o_shippriority int +o_comment string +tx_id string +tx_state int +tx_version int +tx_prepared_at bigint +tx_committed_at bigint +before_tx_id string +before_tx_state int +before_tx_version int +before_tx_prepared_at bigint +before_tx_committed_at bigint +before_o_orderstatus string +before_o_clerk string +before_o_orderdate string +before_o_shippriority int +before_o_custkey int +before_o_totalprice double +before_o_comment string +before_o_orderpriority string +``` + +多くの場合、トランザクションメタデータ列は必要ありません。トランザクションメタデータ列を除く処理を簡単にするために、ScalarDB Analytics は WAL 解釈ビューを提供します。WAL 解釈ビューはトランザクションメタデータ列を非表示にし、ユーザー定義の列のみを公開して、クエリを簡素化します。たとえば、読み取り専用分析を実行する場合や、分析にトランザクションメタデータが必要ない場合は、WAL 解釈ビューを使用します。さらに、WAL 解釈ビューは、トランザクションメタデータ列を内部的に解釈することで、読み取りコミット一貫性を保証します。 + +#### Spark SQL での WAL 解釈ビューの命名規則 + +WAL 解釈ビューには、テーブル識別子のデータソース部分の前に `view.` というプレフィックスが付きます。たとえば、ScalarDB テーブルでは次の WAL 解釈ビューが使用できます: + +- ScalarDB (Cassandra): + - test_catalog.view.scalardb.cassandrans.lineitem +- ScalarDB (MySQL): + - test_catalog.view.scalardb.mysqlns.orders + +たとえば、Cassandra でサポートされる ScalarDB テーブルの WAL 解釈ビューを表示するには、次のコマンドを実行します: + +```sql +DESCRIBE test_catalog.view.scalardb.cassandrans.lineitem; +``` + +次の出力が表示されます: + +```console +l_orderkey int +l_linenumber int +l_comment string +l_commitdate string +l_discount double +l_extendedprice double +l_linestatus string +l_partkey int +l_quantity int +l_receiptdate string +l_returnflag string +l_shipdate string +l_shipinstruct string +l_shipmode string +l_suppkey int +l_tax double +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/README.mdx new file mode 100644 index 00000000..fb3b8ea3 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/README.mdx @@ -0,0 +1,533 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# マイクロサービストランザクションを使用した Spring Data JDBC for ScalarDB のサンプルアプリケーション + +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、Spring Data JDBC for ScalarDB を使用してマイクロサービストランザクション用のサンプル Spring Boot アプリケーションを作成する方法について説明します。 + +これらの機能の詳細については、[2フェーズコミットトランザクション](../../two-phase-commit-transactions.mdx) および [Spring Data JDBC for ScalarDB ガイド](../../scalardb-sql/spring-data-guide.mdx)を参照してください。 + +## このサンプルアプリケーションの前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10以降 ([Docker Compose](https://docs.docker.com/compose/install/) V2以降) + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../../requirements.mdx)を参照してください。 + +::: + + + +## サンプルアプリケーション + +### 概要 + +このチュートリアルでは、ScalarDB の[2フェーズコミットインターフェースを使用したトランザクション](../../two-phase-commit-transactions.mdx)を通じて、アイテムを注文し、信用枠で支払うことができるサンプル電子商取引アプリケーションを作成するプロセスについて説明します。 + +このサンプルアプリケーションには、[*Database-per-service* pattern](https://microservices.io/patterns/data/database-per-service.html) に基づく *Customer Service* と *Order Service* という2つのマイクロサービスがあります。 + +Customer Service は、クレジット限度額やクレジット合計などのクレジットカード情報を含む顧客情報を管理します。Order Service は、注文の確定や注文履歴の取得などの注文操作を担当します。 + +各サービスには gRPC エンドポイントがあります。クライアントはエンドポイントを呼び出し、サービスも互いにエンドポイントを呼び出します。Customer Service と Order Service は、それぞれ ScalarDB を介して MySQL と Cassandra を使用します。 + +![概要](images/overview.png) + +各サービスは、専用の ScalarDB Cluster を介してデータベースにアクセスします。 + +:::note + +両方の ScalarDB Cluster は、Consensus Commit プロトコルに使用される小さな Coordinator データベースにアクセスします。このサンプルアプリケーションでは、セットアップと説明を簡単にするために、Coordinator データベースは Order Service の同じ Cassandra インスタンスに共存していますが、もちろん、Coordinator データベースは別のデータベースとして管理できます。 + +また、サンプルアプリケーションでは ScalarDB の使用方法の説明に重点を置いているため、アプリケーション固有のエラー処理、認証処理などは省略されています。 + +ScalarDB での例外処理の詳細については、[例外の処理方法](../../two-phase-commit-transactions.mdx#例外の処理方法)を参照してください。 + +::: + +### サービスエンドポイント + +サービスで定義されているエンドポイントは次のとおりです。 + +- Customer Service + - `getCustomerInfo` + - `payment` + - `prepare` + - `validate` + - `commit` + - `rollback` + - `repayment` + +- Order Service + - `placeOrder` + - `getOrder` + - `getOrders` + +### このサンプルアプリケーションで実行できること + +サンプルアプリケーションは、次の種類のトランザクションをサポートしています。 + +- Customer Service の `getCustomerInfo` エンドポイントを介して顧客情報を取得します。 +- Order Service の `placeOrder` エンドポイントと、Customer Service の `payment`、`prepare`、`validate`、`commit`、`rollback` エンドポイントを介して、信用枠を使用して注文を行います。 + - 注文のコストが顧客の信用限度額を下回っているかどうかを確認します。 + - チェックに合格した場合、注文履歴を記録し、顧客が支払った金額を更新します。 +- Order Service の `getOrder` エンドポイントと、Customer Service の `getCustomerInfo`、`prepare`、`validate`、`commit`、`rollback` エンドポイントを介して、注文 ID で注文情報を取得します。 +- Order Service の `getOrders` エンドポイントと、Customer Service の `getCustomerInfo`、`prepare`、`validate`、`commit`、`rollback` エンドポイントを介して、顧客 ID で注文情報を取得します。 +- Customer Service の `repayment` エンドポイントを介して支払いを行います。 + - 顧客が支払った金額を減らします。 + +:::note + +`getCustomerInfo` エンドポイントは、コーディネーターからトランザクション ID を受信するときに、参加者サービスエンドポイントとして機能します。 + +::: + +## ScalarDB Cluster の設定 + +[Customer Service 用の ScalarDB Cluster の設定](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/scalardb-cluster-node-for-customer-service.properties)は次のとおりです。 + +```properties +scalar.db.storage=multi-storage +scalar.db.multi_storage.storages=cassandra,mysql +scalar.db.multi_storage.storages.cassandra.storage=cassandra +scalar.db.multi_storage.storages.cassandra.contact_points=cassandra-1 +scalar.db.multi_storage.storages.cassandra.username=cassandra +scalar.db.multi_storage.storages.cassandra.password=cassandra +scalar.db.multi_storage.storages.mysql.storage=jdbc +scalar.db.multi_storage.storages.mysql.contact_points=jdbc:mysql://mysql-1:3306/ +scalar.db.multi_storage.storages.mysql.username=root +scalar.db.multi_storage.storages.mysql.password=mysql +scalar.db.multi_storage.namespace_mapping=customer_service:mysql,coordinator:cassandra +scalar.db.multi_storage.default_storage=mysql +scalar.db.consensus_commit.isolation_level=SERIALIZABLE + +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.sql.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +- `scalar.db.sql.connection_mode`: この設定は、ScalarDB への接続方法を決定します。 +- `scalar.db.storage`: ScalarDB でマルチストレージトランザクションを使用するには、`multi-storage` を指定する必要があります。 +- `scalar.db.multi_storage.storages`: ここでストレージ名を定義する必要があります。 +- `scalar.db.multi_storage.storages.cassandra.*`: これらの設定は、`scalar.db.multi_storage.storages` で定義されているストレージ名の1つである `cassandra` ストレージ用です。`cassandra` ストレージのすべての `scalar.db.*` プロパティをここで設定できます。 +- `scalar.db.multi_storage.storages.mysql.*`: これらの設定は、`scalar.db.multi_storage.storages` で定義されているストレージ名の1つである `mysql` ストレージ用です。ここで、`mysql` ストレージのすべての `scalar.db.*` プロパティを設定できます。 +- `scalar.db.multi_storage.namespace_mapping`: この設定は、名前空間をストレージにマップします。このサンプルアプリケーションでは、`customer_service` 名前空間テーブルの操作は `mysql` ストレージにマップされ、`order_service` 名前空間テーブルの操作は `cassandra` ストレージにマップされます。また、Consensus Commit トランザクションで使用される `coordinator` 名前空間にマップされるストレージを定義することもできます。 +- `scalar.db.multi_storage.default_storage`: この設定は、マッピングされていない名前空間テーブルでの操作に使用されるデフォルトのストレージを設定します。 +- `scalar.db.sql.default_transaction_mode`: ScalarDB で2フェーズコミットトランザクションモードを使用するには、`two_phase_commit_transaction` を指定する必要があります。 +- `scalar.db.consensus_commit.isolation_level`: この設定は、ConsensusCommit に使用される分離レベルを決定します。 + +詳細については、[マルチストレージトランザクション](../../multi-storage-transactions.mdx)を参照してください。 + +[Order Service 用の ScalarDB Cluster の設定](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/scalardb-cluster-node-for-order-service.properties)は次のとおりです。 + +```properties +scalar.db.storage=cassandra +scalar.db.contact_points=cassandra-1 +scalar.db.username=cassandra +scalar.db.password=cassandra +scalar.db.consensus_commit.isolation_level=SERIALIZABLE + +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.sql.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +- `scalar.db.storage`: このサービスは Cassandra のみを基盤データベースとして使用するため、`cassandra` が指定されています。 +- `scalar.db.contact_points`: この設定では、Cassandra に接続するための連絡先 (ホストなど) を指定します。 +- `scalar.db.username`: この設定では、Cassandra に接続するためのユーザー名を指定します。 +- `scalar.db.password`: この設定では、Cassandra に接続するためのパスワードを指定します。 +- `scalar.db.sql.default_namespace_name`: この設定では、デフォルトの名前空間が `order_service` に設定されるため、アプリケーションで名前空間を指定する必要がなくなります。 +- `scalar.db.sql.default_transaction_mode`: ScalarDB で2フェーズコミットトランザクションモードを使用するには、`two_phase_commit_transaction` を指定する必要があります。 +- `scalar.db.consensus_commit.isolation_level`: この設定は、ConsensusCommit に使用される分離レベルを決定します。 + +このサンプルアプリケーションでは、ScalarDB Cluster はスタンドアロンモード (`scalar.db.cluster.node.standalone_mode.enabled=true`) で実行されています。 + +また、設定ファイルで ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) を設定する必要があります。詳細については、[製品ライセンスキーの設定方法](../../scalar-licensing/index.mdx)を参照してください。 + +## セットアップ + +### ScalarDB サンプルリポジトリのクローンを作成する + +ターミナルを開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、このサンプルがあるディレクトリに移動します。 + +```console +cd scalardb-samples/spring-data-microservice-transaction-sample +``` + +### ライセンスキーを設定する + +設定ファイル [`scalardb-cluster-node-for-customer-service.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/scalardb-cluster-node-for-customer-service.properties) および [`scalardb-cluster-node-for-order-service.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/scalardb-cluster-node-for-order-service.properties) で、ScalarDB Clusters のライセンスキー (試用ライセンスまたは商用ライセンス) を設定します。詳細については、[製品ライセンスキーの設定方法](../../scalar-licensing/index.mdx) を参照してください。 + +### Cassandra、MySQL、および ScalarDB Cluster を起動する + +Cassandra、MySQL、および ScalarDB Cluster を起動するには、次の `docker-compose` コマンドを実行する必要があります。 + +```console +docker-compose up -d cassandra mysql scalardb-cluster-node-for-customer-service scalardb-cluster-node-for-order-service +``` + +:::note + +コンテナが完全に起動するまで1分以上待つ必要があります。 + +::: + +### スキーマをロード + +サンプルアプリケーションのデータベーススキーマ (データを整理する方法) は、Customer Service の場合は [`schema-for-customer-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-customer-service.sql)、Order Service の場合は [`schema-for-order-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-order-service.sql) で既に定義されています。 + +スキーマを適用するには、[ScalarDB リリース](https://github.com/scalar-labs/scalardb/releases)ページに移動し、使用する ScalarDB のバージョンに一致する SQL CLI ツールをダウンロードします。 + +#### MySQL + +[`schema-for-customer-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-customer-service.sql) のスキーマを MySQL にロードするには、`` をダウンロードした ScalarDB Schema Loader のバージョンに置き換えて、次のコマンドを実行します。 + +```console +java -jar scalardb-cluster-sql-cli--all.jar --config scalardb-cluster-node-for-customer-service-client.properties --file schema-for-customer-service.sql +``` + +#### Cassandra + +[`schema-for-order-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-order-service.sql) のスキーマを Cassandra にロードするには、`` をダウンロードした ScalarDB Schema Loader のバージョンに置き換えて、次のコマンドを実行します。 + +```console +java -jar scalardb-cluster-sql-cli--all.jar --config scalardb-cluster-node-for-order-service-client.properties --file schema-for-order-service.sql +``` + +#### スキーマの詳細 + +[`schema-for-customer-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-customer-service.sql) に示されているように、Customer Service のすべてのテーブルは `customer_service` 名前空間に作成されます。 + +- `customer_service.customers`: 顧客の情報を管理するテーブル + - `credit_limit`: 貸し手が各顧客に信用枠の使用を許可する最大金額 + - `credit_total`: 各顧客が信用枠を使用してすでに使用した金額 + +[`schema-for-order-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-order-service.sql) に示されているように、Order Service のすべてのテーブルは `order_service` 名前空間に作成されます。 + +- `order_service.orders`: 注文情報を管理するテーブル +- `order_service.statements`: 注文明細情報を管理するテーブル +- `order_service.items`: 注文する商品の情報を管理するテーブル + +スキーマのエンティティリレーションシップダイアグラムは次のとおりです。 + +![ERD](images/ERD.png) + +### マイクロサービスを開始する + +まず、次のコマンドを使用してサンプルアプリケーションの Docker イメージをビルドする必要があります。 + +```console +./gradlew docker +``` + +次に、次の `docker-compose` コマンドを使用してマイクロサービスを起動できます。 + +```console +docker-compose up -d customer-service order-service +``` + +### 初期データ + +マイクロサービスが起動すると、初期データが自動的にロードされます。 + +初期データがロードされたら、次のレコードがテーブルに保存されます: + +- `customer_service.customers` テーブルの場合: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +- `order_service.items` テーブルの場合: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションを実行する + +まず、ID が `1` である顧客に関する情報を取得します。 + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000} +... +``` + +この時点では、`credit_total` は表示されません。つまり、`credit_total` の現在の値は `0` です。 + +次に、顧客 ID `1` を使用して、リンゴ3個とオレンジ2個を注文します。 + +注文の形式は `:,:,...` であることに注意してください。 + +```console +./gradlew :client:run --args="PlaceOrder 1 1:3,2:2" +... +{"order_id": "415a453b-cfee-4c48-b8f6-d103d3e10bdb"} +... +``` + +このコマンドを実行すると、注文 ID が表示されます。 + +注文 ID を使用して注文の詳細を確認してみましょう。 + +```console +./gradlew :client:run --args="GetOrder 415a453b-cfee-4c48-b8f6-d103d3e10bdb" +... +{"order": {"order_id": "415a453b-cfee-4c48-b8f6-d103d3e10bdb","timestamp": 1686555272435,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": $ +,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +次に、別の注文を出して、顧客 ID `1` の注文履歴を取得しましょう。 + +```console +./gradlew :client:run --args="PlaceOrder 1 5:1" +... +{"order_id": "069be075-98f7-428c-b2e0-6820693fc41b"} +... +./gradlew :client:run --args="GetOrders 1" +... +{"order": [{"order_id": "069be075-98f7-428c-b2e0-6820693fc41b","timestamp": 1686555279366,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000},{"order_id": "415a453b-cfee-4c48-b8f6-d103d3e10bdb","timestamp": 1686555272435,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}]} +... +``` + +この注文履歴は、タイムスタンプの降順で表示されます。 + +顧客の現在の `credit_total` は `10000` です。顧客は、情報を取得したときに表示された `credit_limit` に達したため、これ以上注文することはできません。 + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000,"credit_total": 10000} +... +./gradlew :client:run --args="PlaceOrder 1 3:1,4:1" +... +io.grpc.StatusRuntimeException: FAILED_PRECONDITION: Credit limit exceeded. creditTotal:10000, payment:7500 + at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:271) + at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:252) + at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:165) + at sample.rpc.OrderServiceGrpc$OrderServiceBlockingStub.placeOrder(OrderServiceGrpc.java:296) + at sample.client.command.PlaceOrderCommand.call(PlaceOrderCommand.java:38) + at sample.client.command.PlaceOrderCommand.call(PlaceOrderCommand.java:12) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.client.Client.main(Client.java:39) +... +``` + +支払いが完了すると、顧客は再度注文できるようになります。 + +```console +./gradlew :client:run --args="Repayment 1 8000" +... +./gradlew :client:run --args="GetCustomerInfo 1" +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000,"credit_total": 2000} +... +./gradlew :client:run --args="PlaceOrder 1 3:1,4:1" +... +{"order_id": "b6adabd8-0a05-4109-9618-3420fea3161f"} +... +``` + +## クリーンアップ + +Cassandra、MySQL、マイクロサービスを停止するには、次のコマンドを実行します。 + +```console +docker-compose down +``` + +## リファレンス - マイクロサービストランザクションの実現方法 + +注文、単一注文の取得、注文履歴の取得のトランザクションは、マイクロサービストランザクションを実現します。このセクションでは、注文を例に、Customer Service と Order Service にまたがるトランザクションの実装方法に焦点を当てます。 + +次のシーケンス図は、注文を行うトランザクションを示しています。 + +![シーケンス図](images/sequence_diagram.png) + +### 1. 2フェーズコミットインターフェースによるトランザクションが開始されます + +クライアントが Order Service に注文リクエストを送信すると、`OrderService.placeOrder()` が呼び出され、マイクロサービストランザクションが開始されます。 + +最初に、Order Service は次のように `ScalarDbTwoPcRepository.executeTwoPcTransaction()` を使用して2フェーズコミットインターフェースによるトランザクションを開始します。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +// Start a two-phase commit interface transaction +TwoPcResult result = orderRepository.executeTwoPcTransaction(txId -> { + ... +}, ...); +``` + +[CRUD 操作が実行される](#2-crud-operations-are-executed)、[2フェーズコミットプロトコルを使用してトランザクションがコミットされる](#3-トランザクションは2相コミットプロトコルを使用してコミットされます)、[エラー処理](#エラー処理)のアクションは、API によって自動的に実行されます。 + +### 2. CRUD 操作が実行される + +2フェーズコミットインターフェイスを使用したトランザクションが開始されると、`ScalarDbTwoPcRepository.executeTwoPcTransaction()` によって CRUD 操作が実行されます。Order Service は、注文情報を `order_service.orders` テーブルに、詳細情報を `order_service.statements` テーブルに次のように格納します。参考までに、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +// Put the order info into the `orders` table +orderRepository.insert(order); + +AtomicInteger amount = new AtomicInteger(); +for (ItemOrder itemOrder : request.getItemOrderList()) { + int itemId = itemOrder.getItemId(); + int count = itemOrder.getCount(); + // Retrieve the item info from the `items` table + Optional itemOpt = itemRepository.findById(itemId); + if (!itemOpt.isPresent()) { + String message = "Item not found: " + itemId; + responseObserver.onError( + Status.NOT_FOUND.withDescription(message).asRuntimeException()); + throw new ScalarDbNonTransientException(message); + } + Item item = itemOpt.get(); + + int cost = item.price * count; + // Put the order statement into the `statements` table + statementRepository.insert(new Statement(itemId, orderId, count)); + // Calculate the total amount + amount.addAndGet(cost); +} +``` + +次に、Order Service は、トランザクション ID とともに Customer Service の `payment` gRPC エンドポイントを呼び出します。参考については、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +customerServiceStub.payment( + PaymentRequest.newBuilder() + .setTransactionId(transactionId) + .setCustomerId(customerId) + .setAmount(amount) + .build()); +``` + +Customer Service の `payment` エンドポイントは、まず次のように `ScalarDbTwoPcRepository.joinTransactionOnParticipant()` を使用してトランザクションを結合します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +customerRepository.joinTransactionOnParticipant(request.getTransactionId(), ...); +``` + +次に、エンドポイントは顧客情報を取得し、支払い後に顧客のクレジット合計がクレジット限度額を超えているかどうかを確認します。クレジット合計がクレジット限度額を超えていない場合、エンドポイントは顧客のクレジット合計を更新します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +Customer customer = getCustomer(responseObserver, request.getCustomerId()); + +int updatedCreditTotal = customer.creditTotal + request.getAmount(); +// Check if the credit total exceeds the credit limit after payment +if (updatedCreditTotal > customer.creditLimit) { + String message = String.format( + "Credit limit exceeded. creditTotal:%d, payment:%d", customer.creditTotal, request.getAmount()); + responseObserver.onError( + Status.FAILED_PRECONDITION.withDescription(message).asRuntimeException()); + throw new ScalarDbNonTransientException(message); +} + +// Reduce `credit_total` for the customer +customerRepository.update(customer.withCreditTotal(updatedCreditTotal)); +``` + +### 3. トランザクションは2相コミットプロトコルを使用してコミットされます + +Order Service は、支払いが成功したという更新を受け取った後、トランザクションをコミットしようとします。 + +Order Service で呼び出された `ScalarDbTwoPcRepository.executeTwoPcTransaction()` API は、ローカル Order Service とリモート Customer Service の両方の準備、検証、およびコミットを自動的に実行します。これらの手順は、上記の CRUD 操作が正常に終了した後に順番に実行されます。Customer Service の `prepare`、`validate`、および `commit` gRPC エンドポイントを呼び出す実装は、API にパラメーターとして渡す必要があります。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +TwoPcResult result = orderRepository.executeTwoPcTransaction(txId ->{ + ... + }, + + Collections.singletonList( + RemotePrepareCommitPhaseOperations.createSerializable( + this::callPrepareEndpoint, + this::callValidateEndpoint, + this::callCommitEndpoint, + this::callRollbackEndpoint + ) + ) +); +``` + +![高レベル 2PC API のシーケンス図](images/seq-diagram-high-level-2pc-api.png) + +Customer Service の `prepare` エンドポイントでは、エンドポイントは `ScalarDbTwoPcRepository.prepareTransactionOnParticipant()` を使用してトランザクションを再開し、準備します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +customerRepository.prepareTransactionOnParticipant(request.getTransactionId()); +``` + +Customer Service の `validate` エンドポイントでは、エンドポイントは `ScalarDbTwoPcRepository.validateTransactionOnParticipant()` を使用してトランザクションを再開し、検証します。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +customerRepository.validateTransactionOnParticipant(request.getTransactionId()); +``` + +Customer Service の `commit` エンドポイントでは、エンドポイントは `ScalarDbTwoPcRepository.commitTransactionOnParticipant()` を使用してトランザクションを再開し、コミットします。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +customerRepository.commitTransactionOnParticipant(request.getTransactionId()); +``` + +### エラー処理 + +トランザクションの実行中にエラーが発生した場合、`ScalarDbTwoPcRepository.executeTwoPcTransaction()` は、ローカルの Order Service とリモートの Customer Service の両方でトランザクションを自動的にロールバックします。Customer Service の `rollback` gRPC エンドポイントを呼び出す実装も、他の実装とともに API にパラメータとして渡す必要があります。参考として、[`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) を参照してください。 + +```java +TwoPcResult result = orderRepository.executeTwoPcTransaction(txId ->{ + ... + }, + + Collections.singletonList( + RemotePrepareCommitPhaseOperations.createSerializable( + this::callPrepareEndpoint, + this::callValidateEndpoint, + this::callCommitEndpoint, + this::callRollbackEndpoint + ) + ) +); +``` + +Customer Service の `rollback` エンドポイントでは、エンドポイントがトランザクションを再開してロールバックします。参考として、[`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) を参照してください。 + +```java +customerRepository.rollbackTransactionOnParticipant(request.getTransactionId()); +``` + +ScalarDB で例外を処理する方法の詳細については、[例外の処理方法](../../two-phase-commit-transactions.mdx#例外の処理方法)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/ERD.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/ERD.png new file mode 100644 index 00000000..c0468efa Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/ERD.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/overview.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/overview.png new file mode 100644 index 00000000..223c8ad7 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/overview.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/seq-diagram-high-level-2pc-api.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/seq-diagram-high-level-2pc-api.png new file mode 100644 index 00000000..724e52b5 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/seq-diagram-high-level-2pc-api.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/sequence_diagram.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/sequence_diagram.png new file mode 100644 index 00000000..0317b5f3 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/sequence_diagram.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx new file mode 100644 index 00000000..dec8f76f --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx @@ -0,0 +1,335 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# マルチストレージトランザクションを備えた Spring Data JDBC for ScalarDB のサンプルアプリケーション + +import WarningLicenseKeyContact from '/src/components/ja-jp/_warning-license-key-contact.mdx'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このチュートリアルでは、マルチストレージトランザクションを備えた Spring Data JDBC for ScalarDB を使用してサンプル Spring Boot アプリケーションを作成する方法について説明します。 + +## このサンプルアプリケーションの前提条件 + +- [Eclipse Temurin](https://adoptium.net/temurin/releases/) の OpenJDK LTS バージョン (8、11、17、または 21) +- [Docker](https://www.docker.com/get-started/) 20.10以降 ([Docker Compose](https://docs.docker.com/compose/install/) V2以降) + +:::note + +このサンプルアプリケーションは、Eclipse Temurin の OpenJDK でテストされています。ただし、ScalarDB 自体は、さまざまなベンダーの JDK ディストリビューションでテストされています。互換性のある JDK ディストリビューションを含む ScalarDB の要件の詳細については、[要件](../../requirements.mdx)を参照してください。 + +::: + + + +## サンプルアプリケーション + +### 概要 + +このチュートリアルでは、ScalarDB の [マルチストレージトランザクション](../../multi-storage-transactions.mdx)機能を使用して、アイテムを注文し、信用枠で支払いを行うことができるサンプル電子商取引アプリケーションを作成するプロセスについて説明します。 + +:::note + +このチュートリアルでは、マルチストレージトランザクションで Spring Data JDBC for ScalarDB を使用する方法を説明することに重点を置いているため、サンプルアプリケーションではアプリケーション固有のエラー処理、認証処理などは省略されています。 + +詳細については、[Spring Data JDBC for ScalarDB ガイド](../../scalardb-sql/spring-data-guide.mdx)を参照してください。 + +::: + +![概要](images/overview.png) + +アプリケーションは、ScalarDB Cluster を介してデータベースにアクセスします。 + +### スキーマ + +[スキーマ](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-multi-storage-transaction-sample/schema.sql)は次のとおりです。 + +```sql +CREATE COORDINATOR TABLES IF NOT EXIST; + +CREATE NAMESPACE IF NOT EXISTS customer; + +CREATE TABLE IF NOT EXISTS customer.customers ( + customer_id INT PRIMARY KEY, + name TEXT, + credit_limit INT, + credit_total INT +); + +CREATE NAMESPACE IF NOT EXISTS "order"; + +CREATE TABLE IF NOT EXISTS "order".orders ( + customer_id INT, + timestamp BIGINT, + order_id TEXT, + PRIMARY KEY (customer_id, timestamp) +); + +CREATE INDEX IF NOT EXISTS ON "order".orders (order_id); + +CREATE TABLE IF NOT EXISTS "order".statements ( + order_id TEXT, + item_id INT, + count INT, + PRIMARY KEY (order_id, item_id) +); + +CREATE TABLE IF NOT EXISTS "order".items ( + item_id INT PRIMARY KEY, + name TEXT, + price INT +); +``` + +すべてのテーブルは、`customer` および `order` 名前空間に作成されます。 + +- `customer.customers`: 顧客の情報を管理するテーブル + - `credit_limit`: 貸し手が各顧客にクレジットカードの使用を許可する最大金額 + - `credit_total`: 各顧客がクレジットカードを使用してすでに使用した金額 +- `order.orders`: 注文情報を管理するテーブル +- `order.statements`: 注文明細情報を管理するテーブル +- `order.items`: 注文するアイテムの情報を管理するテーブル + +スキーマのエンティティ関係図は次のとおりです。 + +![ERD](images/ERD.png) + +### トランザクション + +このサンプルアプリケーションでは、次の5つのトランザクションが実装されています: + +1. 顧客情報の取得 +2. クレジットカードによる注文 (注文のコストがクレジット限度額を下回っているかどうかを確認し、注文履歴を記録して、チェックに合格した場合は `credit_total` を更新します) +3. 注文 ID による注文情報の取得 +4. 顧客 ID による注文情報の取得 +5. 返済 (`credit_total` の金額を減らします) + +## ScalarDB Cluster の設定 + +[ScalarDB Cluster の設定](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-multi-storage-transaction-sample/scalardb-cluster-node.properties)は次のとおりです: + +```properties +scalar.db.storage=multi-storage +scalar.db.multi_storage.storages=cassandra,mysql +scalar.db.multi_storage.storages.cassandra.storage=cassandra +scalar.db.multi_storage.storages.cassandra.contact_points=cassandra-1 +scalar.db.multi_storage.storages.cassandra.username=cassandra +scalar.db.multi_storage.storages.cassandra.password=cassandra +scalar.db.multi_storage.storages.mysql.storage=jdbc +scalar.db.multi_storage.storages.mysql.contact_points=jdbc:mysql://mysql-1:3306/ +scalar.db.multi_storage.storages.mysql.username=root +scalar.db.multi_storage.storages.mysql.password=mysql +scalar.db.multi_storage.namespace_mapping=customer:mysql,order:cassandra,coordinator:cassandra +scalar.db.multi_storage.default_storage=cassandra + +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.sql.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +- `scalar.db.storage`: ScalarDB でマルチストレージトランザクションを使用するには、`multi-storage` を指定する必要があります。 +- `scalar.db.multi_storage.storages`: ここでストレージ名を定義する必要があります。 +- `scalar.db.multi_storage.storages.cassandra.*`: これらの設定は、`scalar.db.multi_storage.storages` で定義されているストレージ名の1つである `cassandra` ストレージ用です。ここで、`cassandra` ストレージのすべての `scalar.db.*` プロパティを設定できます。 +- `scalar.db.multi_storage.storages.mysql.*`: これらの設定は、`scalar.db.multi_storage.storages` で定義されているストレージ名の1つである `mysql` ストレージ用です。ここで、`mysql` ストレージのすべての `scalar.db.*` プロパティを設定できます。 +- `scalar.db.multi_storage.namespace_mapping`: この設定は、名前空間をストレージにマップします。このサンプルアプリケーションでは、`customer` 名前空間テーブルの操作は `mysql` ストレージにマップされ、`order` 名前空間テーブルの操作は `cassandra` ストレージにマップされます。また、Consensus Commit トランザクションで使用される `coordinator` 名前空間にマップされるストレージを定義することもできます。 +- `scalar.db.multi_storage.default_storage`: この設定は、マップされていない名前空間テーブルの操作に使用されるデフォルトのストレージを設定します。 + +詳細については、[マルチストレージトランザクション](../../multi-storage-transactions.mdx)を参照してください。 + +このサンプルアプリケーションでは、ScalarDB Cluster はスタンドアロンモード (`scalar.db.cluster.node.standalone_mode.enabled=true`) で実行されています。 + +また、設定ファイルで ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) を設定する必要があります。 詳細については、[製品ライセンスキーの設定方法](../../scalar-licensing/index.mdx)を参照してください。 + +## クライアント設定 + +[クライアント設定](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-multi-storage-transaction-sample/scalardb-sql.properties)は次のとおりです。 + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost +``` + +## セットアップ + +### ScalarDB サンプルリポジトリのクローンを作成する + +ターミナルを開き、次のコマンドを実行して ScalarDB サンプルリポジトリのクローンを作成します。 + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +次に、次のコマンドを実行して、このサンプルがあるディレクトリに移動します。 + +```console +cd scalardb-samples/spring-data-multi-storage-transaction-sample +``` + +### ライセンスキーを設定する + +設定ファイル [`scalardb-cluster-node.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-multi-storage-transaction-sample/scalardb-cluster-node.properties) で ScalarDB Cluster のライセンスキー (試用ライセンスまたは商用ライセンス) を設定します。詳細については、[製品ライセンスキーの設定方法](../../scalar-licensing/index.mdx)を参照してください。 + +### Cassandra、MySQL、および ScalarDB Cluster を起動する + +Cassandra、MySQL、および ScalarDB Cluster を起動するには、次の `docker-compose` コマンドを実行する必要があります。 + +```console +docker-compose up -d +``` + +コンテナの起動には1分以上かかる場合があることに注意してください。 + +### スキーマをロード + +次に、次のコマンドでスキーマを適用する必要があります。SQL CLI ツール `scalardb-cluster-sql-cli--all.jar` をダウンロードするには、ScalarDB の [リリース](https://github.com/scalar-labs/scalardb/releases)を参照して、使用するバージョンをダウンロードしてください。 + +```console +java -jar scalardb-cluster-sql-cli--all.jar --config scalardb-sql.properties --file schema.sql +``` + +### 初期データをロードする + +コンテナが起動したら、次のコマンドを実行して初期データをロードする必要があります。 + +```console +./gradlew run --args="LoadInitialData" +``` + +初期データがロードされた後、次のレコードがテーブルに保存されます: + +- `customer.customers` テーブルの場合: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +- `order.items` テーブルの場合: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## サンプルアプリケーションを実行する + +まず、ID が `1` である顧客に関する情報を取得します。 + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":0} +... +``` + +次に、顧客 ID `1` を使用して、リンゴ3個とオレンジ2個を注文します。注文形式は `:,:,...` であることに注意してください。 + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +... +{"order_id":"5d49eb62-fcb9-4dd2-9ae5-e714d989937f","customer_id":1,"timestamp":1677564659810} +... +``` + +このコマンドを実行すると、注文 ID が表示されます。 + +注文 ID を使用して注文の詳細を確認してみましょう。 + +```console +./gradlew run --args="GetOrder 5d49eb62-fcb9-4dd2-9ae5-e714d989937f" +... +{"order_id":"5d49eb62-fcb9-4dd2-9ae5-e714d989937f","timestamp":1677564659810,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":1,"item_name":"Apple","price":1000,"count":3,"total":3000},{"item_id":2,"item_name":"Orange","price":2000,"count":2,"total":4000}],"total":7000} +... +``` + +次に、別の注文を出して、顧客 ID `1` の注文履歴を取得しましょう。 + +```console +./gradlew run --args="PlaceOrder 1 5:1" +... +{"order_id":"ccd97d75-ee57-4393-a0bb-5230c4a8c68a","customer_id":1,"timestamp":1677564776069} +... +./gradlew run --args="GetOrders 1" +... +[{"order_id":"ccd97d75-ee57-4393-a0bb-5230c4a8c68a","timestamp":1677564776069,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":5,"item_name":"Melon","price":3000,"count":1,"total":3000}],"total":3000},{"order_id":"5d49eb62-fcb9-4dd2-9ae5-e714d989937f","timestamp":1677564659810,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":1,"item_name":"Apple","price":1000,"count":3,"total":3000},{"item_id":2,"item_name":"Orange","price":2000,"count":2,"total":4000}],"total":7000}] +... +``` + +この注文履歴は、タイムスタンプの降順で表示されます。 + +顧客の現在の `credit_total` は `10000` です。顧客は、情報を取得したときに表示された `credit_limit` に達したため、これ以上注文することはできません。 + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":10000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +java.lang.RuntimeException: Credit limit exceeded. limit:10000, total:17500 + at sample.SampleService.placeOrder(SampleService.java:102) + at sample.SampleService$$FastClassBySpringCGLIB$$1123c447.invoke() + at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793) + at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) + at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) + at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) + at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) + at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) + at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708) + at sample.SampleService$$EnhancerBySpringCGLIB$$1cb0cc8c.placeOrder() + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:37) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:13) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.SampleApp.run(SampleApp.java:26) + at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:768) + at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:752) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) + at sample.SampleApp.main(SampleApp.java:35) +... +``` + +支払いが完了すると、顧客は再度注文できるようになります。 + +```console +./gradlew run --args="Repayment 1 8000" +... +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":2000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +{"order_id":"3ac4a1bf-a724-4f26-b948-9f03281a971e","customer_id":1,"timestamp":1677565028204} +... +``` + +## クリーンアップ + +Cassandra、MySQL、および ScalarDB Cluster を停止するには、次のコマンドを実行します。 + +```console +docker-compose down +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/ERD.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/ERD.png new file mode 100644 index 00000000..02100437 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/ERD.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/overview.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/overview.png new file mode 100644 index 00000000..360b26c6 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/overview.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/grammar.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/grammar.mdx new file mode 100644 index 00000000..f08aec85 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/grammar.mdx @@ -0,0 +1,3800 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB SQL 文法 + +- DDL + - [CREATE NAMESPACE](#create-namespace) + - [CREATE TABLE](#create-table) + - [CREATE INDEX](#create-index) + - [TRUNCATE TABLE](#truncate-table) + - [DROP INDEX](#drop-index) + - [DROP TABLE](#drop-table) + - [DROP NAMESPACE](#drop-namespace) + - [CREATE COORDINATOR TABLES](#create-coordinator-tables) + - [TRUNCATE COORDINATOR TABLES](#truncate-coordinator-tables) + - [DROP COORDINATOR TABLES](#drop-coordinator-tables) + - [ALTER TABLE](#alter-table) +- DML + - [SELECT](#select) + - [INSERT](#insert) + - [UPSERT](#upsert) + - [UPDATE](#update) + - [DELETE](#delete) +- DCL + - [CREATE USER](#create-user) + - [ALTER USER](#alter-user) + - [DROP USER](#drop-user) + - [GRANT](#grant) + - [REVOKE](#revoke) + - [CREATE ABAC_POLICY](#create-abac_policy) + - [ENABLE ABAC_POLICY](#enable-abac_policy) + - [DISABLE ABAC_POLICY](#disable-abac_policy) + - [CREATE ABAC_LEVEL](#create-abac_level) + - [DROP ABAC_LEVEL](#drop-abac_level) + - [CREATE ABAC_COMPARTMENT](#create-abac_compartment) + - [DROP ABAC_COMPARTMENT](#drop-abac_compartment) + - [CREATE ABAC_GROUP](#create-abac_group) + - [DROP ABAC_GROUP](#drop-abac_group) + - [SET ABAC_LEVEL](#set-abac_level) + - [ADD ABAC_COMPARTMENT](#add-abac_compartment) + - [REMOVE ABAC_COMPARTMENT](#remove-abac_compartment) + - [ADD ABAC_GROUP](#add-abac_group) + - [REMOVE ABAC_GROUP](#remove-abac_group) + - [DROP ABAC_USER_TAG_INFO](#drop-abac_user_tag_info) + - [CREATE ABAC_NAMESPACE_POLICY](#create-abac_namespace_policy) + - [ENABLE ABAC_NAMESPACE_POLICY](#enable-abac_namespace_policy) + - [DISABLE ABAC_NAMESPACE_POLICY](#disable-abac_namespace_policy) + - [CREATE ABAC_TABLE_POLICY](#create-abac_table_policy) + - [ENABLE ABAC_TABLE_POLICY](#enable-abac_table_policy) + - [DISABLE ABAC_TABLE_POLICY](#disable-abac_table_policy) +- Others + - [USE](#use) + - [BEGIN](#begin) + - [START TRANSACTION](#start-transaction) + - [JOIN](#join) + - [PREPARE](#prepare) + - [VALIDATE](#validate) + - [COMMIT](#commit) + - [ROLLBACK](#rollback) + - [ABORT](#abort) + - [SET MODE](#set-mode) + - [SHOW NAMESPACES](#show-namespaces) + - [SHOW TABLES](#show-tables) + - [DESCRIBE](#describe) + - [SUSPEND](#suspend) + - [RESUME](#resume) + - [SHOW USERS](#show-users) + - [SHOW GRANTS](#show-grants) + - [SHOW ABAC_POLICY](#show-abac_policy) + - [SHOW ABAC_POLICIES](#show-abac_policies) + - [SHOW ABAC_LEVEL](#show-abac_level) + - [SHOW ABAC_LEVELS](#show-abac_levels) + - [SHOW ABAC_COMPARTMENT](#show-abac_compartment) + - [SHOW ABAC_COMPARTMENTS](#show-abac_compartments) + - [SHOW ABAC_GROUP](#show-abac_group) + - [SHOW ABAC_GROUPS](#show-abac_groups) + - [SHOW ABAC_USER_TAG_INFO](#show-abac_user_tag_info) + - [SHOW ABAC_NAMESPACE_POLICY](#show-abac_namespace_policy) + - [SHOW ABAC_NAMESPACE_POLICIES](#show-abac_namespace_policies) + - [SHOW ABAC_TABLE_POLICY](#show-abac_table_policy) + - [SHOW ABAC_TABLE_POLICIES](#show-abac_table_policies) +- リテラル + - [テキスト](#テキスト) + - [数字](#数値) + - [日付と時刻](#日付と時刻) + +## DDL + +### CREATE NAMESPACE + +テーブルは1つの名前空間に属しているため、テーブルを作成する前に名前空間を作成する必要があります。`CREATE NAMESPACE` コマンドは名前空間を作成します。 + +#### 文法 + +```sql +CREATE NAMESPACE [IF NOT EXISTS] [WITH creation_options] + +creation_options:
( + data_type PRIMARY KEY, + data_type, + ... +) [WITH creation_options] + +data_type: BOOLEAN | INT | BIGINT | FLOAT | DOUBLE | TEXT | BLOB | DATE | TIME | TIMESTAMP | TIMESTAMPTZ +creation_options:
( + data_type, + data_type, + ..., + data_type [ENCRYPTED], + ..., + PRIMARY KEY (, [, ] ...) +) [WITH [clustering_order_definition [AND creation_options]] | creation_options] + +clustering_order_definition: CLUSTERING ORDER BY ( [clustering_order] [, [clustering_order]] ...) +clustering_order: ASC | DESC +``` + +- `clustering_order` を省略すると、デフォルトのクラスタリング順序 `ASC` が使用されます。 + +複数のパーティションキー列と複数のクラスタリングキー列で構成される主キーを持つテーブルを作成します。 + +```sql +CREATE TABLE [IF NOT EXISTS] [.]
( + data_type, + ..., + data_type, + ..., + data_type [ENCRYPTED], + data_type [ENCRYPTED], + ..., + PRIMARY KEY (( [, ] ...), [, ] ...) +) [WITH [clustering_order_definition [AND creation_options]] | creation_options] +``` + +#### 例 + +`CREATE TABLE` の例は次のとおりです。 + +```sql +-- Create a table with a primary key ("c1") and creation options +CREATE TABLE ns.tbl ( + c1 INT PRIMARY KEY, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN +) WITH 'option1' = 'value1' AND 'option2' = 'value2' AND 'option3' = 'value3'; + +-- Create a table with a partition key ("c1") and a clustering key ("c2" and "c3") with clustering order definition only if it does not already exist +CREATE TABLE IF NOT EXISTS tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY (c1, c2, c3) +) WITH CLUSTERING ORDER BY (c2 DESC, c3 ASC); + +-- Create a table with a partition key ("c1", "c2") and a clustering key ("c3" and "c4") with clustering order definition and creation options +CREATE TABLE ns.tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY ((c1, c2), c3, c4) +) WITH CLUSTERING ORDER BY (c3 DESC, c4 ASC) AND 'option1' = 'value1' AND 'option2' = 'value2' AND 'option3' = 'value3'; + +-- Create a table with a primary key ("c1") and encrypted columns ("c2", "c3", "c4", and "c5") +CREATE TABLE ns.tbl ( + c1 INT PRIMARY KEY, + c2 TEXT ENCRYPTED, + c3 FLOAT ENCRYPTED, + c4 BIGINT ENCRYPTED, + c5 BOOLEAN ENCRYPTED +); +``` + +`CREATE TABLE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create a table with a primary key ("c1") and creation options +CreateTableStatement statement1 = + StatementBuilder.createTable("ns", "tbl") + .withPartitionKey("c1", DataType.INT) + .withColumn("c2", DataType.TEXT) + .withColumn("c3", DataType.FLOAT) + .withColumn("c4", DataType.BIGINT) + .withColumn("c5", DataType.BOOLEAN) + .withOption("option1", "value1") + .withOption("option2", "value2") + .withOption("option3", "value3") + .build(); + +// Create a table with a partition key ("c1") and a clustering key ("c2" and "c3") with clustering order definition +CreateTableStatement statement2 = + StatementBuilder.createTable("tbl") + .ifNotExists() + .withPartitionKey("c1", DataType.INT) + .withClusteringKey("c2", DataType.TEXT) + .withClusteringKey("c3", DataType.FLOAT) + .withColumn("c4", DataType.BIGINT) + .withColumn("c5", DataType.BOOLEAN) + .withClusteringOrder("c2", ClusteringOrder.DESC) + .withClusteringOrder("c3", ClusteringOrder.ASC) + .build(); + +// Create a table with a partition key ("c1", "c2") and a clustering key ("c3" and "c4") with clustering order definition and creation options +CreateTableStatement statement3 = + StatementBuilder.createTable("ns", "tbl") + .withPartitionKey("c1", DataType.INT) + .withPartitionKey("c2", DataType.TEXT) + .withClusteringKey("c3", DataType.FLOAT) + .withClusteringKey("c4", DataType.BIGINT) + .withColumn("c5", DataType.BOOLEAN) + .withClusteringOrder("c3", ClusteringOrder.DESC) + .withClusteringOrder("c4", ClusteringOrder.ASC) + .withOption("option1", "value1") + .withOption("option2", "value2") + .withOption("option3", "value3") + .build(); + +// Create a table with a primary key ("c1") and encrypted columns ("c2", "c3", "c4", and "c5") +CreateTableStatement statement4 = + StatementBuilder.createTable("ns", "tbl") + .withPartitionKey("c1", DataType.INT) + .withColumn("c2", DataType.TEXT, true) + .withColumn("c3", DataType.FLOAT, true) + .withColumn("c4", DataType.BIGINT, true) + .withColumn("c5", DataType.BOOLEAN, true) + .build(); +``` + +### CREATE INDEX + +`CREATE INDEX` コマンドは、テーブルにセカンダリインデックスを作成します。 + +:::note + +暗号化された列にセカンダリインデックスを作成することはできません。 + +::: + +#### 文法 + +```sql +CREATE INDEX [IF NOT EXISTS] ON [.]
() +``` + +#### 例 + +`CREATE INDEX` の例は次のとおりです。 + +```sql +-- Create a secondary index on a column "c4" of a table "ns.tbl" +CREATE INDEX ON ns.tbl (c4); + +-- Create a secondary index only if it does not already exist +CREATE INDEX IF NOT EXISTS ON tbl (c4); + +-- Create a secondary index with options +CREATE INDEX ON ns.tbl (c4) WITH 'option1' = 'value1' AND 'option2' = 'value2' AND 'option3' = 'value3'; +``` + +`CREATE INDEX` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create a secondary index on a column "c4" of a table "ns.tbl" +CreateIndexStatement statement1 = + StatementBuilder.createIndex().onTable("ns", "tbl").column("c4").build(); + +// Create a secondary index only if it does not already exist +CreateIndexStatement statement2 = + StatementBuilder.createIndex().ifNotExists().onTable("tbl").column("c4").build(); + +// Create a secondary index with options +CreateIndexStatement statement3 = + StatementBuilder.createIndex() + .onTable("ns", "tbl") + .column("c4") + .withOption("option1", "value1") + .withOption("option2", "value2") + .withOption("option3", "value3") + .build(); +``` + +### TRUNCATE TABLE + +`TRUNCATE TABLE` コマンドはテーブルのすべての行を削除します。 + +#### 文法 + +```sql +TRUNCATE TABLE [.]
+``` + +#### 例 + +`TRUNCATE TABLE` の例は次のとおりです。 + +```sql +-- Truncate a table "ns.tbl" +TRUNCATE TABLE ns.tbl; +``` + +`TRUNCATE TABLE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Truncate a table "ns.tbl" +TruncateTableStatement statement = StatementBuilder.truncateTable("ns", "tbl").build(); +``` + +### DROP INDEX + +`DROP INDEX` コマンドはセカンダリインデックスを削除します。 + +#### 文法 + +```sql +DROP INDEX [IF EXISTS] ON [.]
() +``` + +#### 例 + +`DROP INDEX` の例は次のとおりです。 + +```sql +-- Drop a secondary index on a column "c4" of a table "ns.tbl" +DROP INDEX ON ns.tbl (c4); + +-- Drop a secondary index only if it exists +DROP INDEX IF EXISTS ON tbl (c4); +``` + +`DROP INDEX` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Drop a secondary index on a column "c4" of a table "ns.tbl" +DropIndexStatement statement1 = + StatementBuilder.dropIndex().onTable("ns", "tbl").column("c4").build(); + +// Drop a secondary index only if it exists +DropIndexStatement statement2 = + StatementBuilder.dropIndex().ifExists().onTable("ns", "tbl").column("c4").build(); +``` + +### DROP TABLE + +`DROP TABLE` コマンドはテーブルを削除します。 + +#### 文法 + +```sql +DROP TABLE [IF EXISTS] [.]
+``` + +#### 例 + +`DROP TABLE` の例は次のとおりです。 + +```sql +-- Drop a table "ns.tbl" +DROP TABLE ns.tbl; + +-- Drop a table only if it exists +DROP TABLE IF EXISTS tbl; +``` + +`DROP TABLE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Drop a table "ns.tbl" +DropTableStatement statement1 = StatementBuilder.dropTable("ns", "tbl").build(); + +// Drop a table only if it exists +DropTableStatement statement2 = StatementBuilder.dropTable("ns", "tbl").ifExists().build(); +``` + +### DROP NAMESPACE + +`DROP NAMESPACE` コマンドは名前空間を削除します。 + +#### 文法 + +```sql +DROP NAMESPACE [IF EXISTS] [CASCADE] +``` + +#### 例 + +`DROP NAMESPACE` の例は次のとおりです。 + +```sql +-- Drop a namespace "ns" +DROP NAMESPACE ns; + +-- Drop a namespace only if it exists +DROP NAMESPACE IF EXISTS ns; + +-- Drop a namespace with cascade +DROP NAMESPACE ns CASCADE; +``` + +`DROP NAMESPACE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Drop a namespace "ns" +DropNamespaceStatement statement1 = StatementBuilder.dropNamespace("ns").build(); + +// Drop a namespace only if it exists +DropNamespaceStatement statement2 = StatementBuilder.dropNamespace("ns").ifExists().build(); + +// Drop a namespace with cascade +DropNamespaceStatement statement3 = StatementBuilder.dropNamespace("ns").cascade().build(); +``` + +### CREATE COORDINATOR TABLES + +`CREATE COORDINATOR TABLES` コマンドは Coordinator テーブルを作成します。 + +#### 文法 + +```sql +CREATE COORDINATOR TABLES [IF NOT {EXIST|EXISTS}] [WITH creation_options] + +creation_options:
ADD [COLUMN] data_type [ENCRYPTED] + +data_type: BOOLEAN | INT | BIGINT | FLOAT | DOUBLE | TEXT | BLOB | DATE | TIME | TIMESTAMP | TIMESTAMPTZ +``` + +- 列に `ENCRYPTED` を指定して、その列のデータを暗号化できます。 + +#### 例 + +`ALTER TABLE` の例は次のとおりです。 + +```sql +-- Add a new column "new_col" to "ns.tbl" +ALTER TABLE ns.tbl ADD COLUMN new_col INT; + +-- Add a new encrypted column "new_col" to "ns.tbl" +ALTER TABLE ns.tbl ADD COLUMN new_col TEXT ENCRYPTED; +``` + +`ALTER TABLE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Add a new column "new_col" to "ns.tbl" +AlterTableAddColumnStatement statement = + StatementBuilder.alterTable("ns", "tbl").addColumn("new_col", DataType.INT).build(); + +// Add a new encrypted column "new_col" to "ns.tbl" +AlterTableAddColumnStatement statement = + StatementBuilder.alterTable("ns", "tbl").addColumn("new_col", DataType.TEXT, true).build(); +``` + +## DML + +### SELECT + +`SELECT` コマンドは、データベースからレコードを取得します。ScalarDB SQL は、ScalarDB の `Get`、パーティション `Scan`、およびクロスパーティション `Scan` 操作のいずれかを使用して、データベースからレコードを取得し、`SELECT` コマンドの実行プランを作成します。最良の結果を得るには、クロスパーティションスキャンの使用を避けるため、`WHERE` 句で主キー列を可能な限り一意に指定します。クロスパーティションスキャンを使用すると、特に非 JDBC データベースでパフォーマンスと一貫性の問題が発生する可能性があります。操作の選択については、次のルールを参照してください。前者は後者よりも優先され、より効率的です。[ScalarDB データモデル](../data-modeling.mdx)は、データのモデリングとアクセスに関するベストプラクティスを理解するのにも役立ちます。 + +1. `WHERE` 句で主キー列を完全に指定すると、`SELECT` コマンドは単一パーティション内の単一レコードに対して `Get` 操作を使用します。 +2. パーティションキーを完全に指定し、`WHERE` 句と `ORDER BY` 句でクラスタリングキーと順序を適切に指定すると、`SELECT` コマンドは単一パーティション内のレコードに対して `Scan` 操作を使用します。詳細については、[パーティションスキャンとインデックススキャンの例](#パーティションスキャンとインデックススキャンの例)を参照してください。 +3. `ORDER BY` 句を使用せずに `WHERE` 句で `equal to` (`=`) 演算子を使用してインデックス列の値を指定すると、`SELECT` コマンドはインデックス `Scan` 操作を使用します。 +4. その他の場合、`SELECT` コマンドはクロスパーティション `Scan` 操作に変換されます。 + +任意の条件と順序でパーティション間でレコードを柔軟に取得したい場合は、クロスパーティションスキャンオプションと、フィルタリングおよび順序付けオプション付きのクロスパーティションスキャンを有効にする必要があります。現在、順序付けオプションは JDBC データベースでのみ使用できます。設定の詳細については、[クロスパーティションスキャン設定](../configurations.mdx#クロスパーティションスキャン設定)および [ScalarDB Cluster SQL クライアント設定](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +:::warning + +非 JDBC データベースの場合、`SERIALIZABLE` 分離レベルでクロスパーティションスキャンを有効にした場合でも、トランザクションは読み取りコミットスナップショット分離 (`SNAPSHOT`) で実行される可能性があります。これは、より低い分離レベルです。非 JDBC データベースを使用する場合は、トランザクションの一貫性が重要でない場合にのみ、クロスパーティションスキャンを使用してください。 + +::: + +#### 文法 + +```sql +SELECT projection [, projection] ... + FROM [.]
[AS ] [join_specification [join_specification] ...] + [WHERE and_predicates [OR and_predicates ...] | or_predicates [AND or_predicates ...]] + [ORDER BY identifier [order] [, identifier [order]] ...] + [LIMIT ] + [WITH operation_attributes_or_abac_read_tags] + +projection: * | identifier [AS ] +join_specification: [INNER] JOIN [.]
[AS ] ON join_predicate [AND join_predicate] ... | {LEFT|RIGHT} [OUTER] JOIN [.]
[AS ] ON join_predicate [AND join_predicate] ... +join_predicate: identifier = identifier +and_predicates: predicate | (predicate [AND predicate ...]) +or_predicates: predicate | (predicate [OR predicate ...]) +predicate: identifier operator | identifier BETWEEN AND | identifier [NOT] LIKE [ESCAPE ] | identifier IS [NOT] NULL +identifier: [[.]
.] | [alias.] +operator: = | <> | != | > | >= | < | <= +order: ASC | DESC +operation_attributes_or_abac_read_tags: operation_attribute_or_abac_read_tag [AND operation_attribute_or_abac_read_tag] ... +operation_attribute_or_abac_read_tag: operation_attribute | abac_read_tag +operation_attribute: = +abac_read_tag: ABAC_READ_TAG FOR [POLICY] +``` + +##### 注記 + +`JOIN` 句: + +- `[INNER] JOIN` および `LEFT [OUTER] JOIN` の場合: + - `join_predicate` には、右側のテーブルのすべての主キー列またはセカンダリインデックス列のいずれかが含まれている必要があります。 + - `WHERE` 述語および `ORDER BY` 句には、`FROM` 句で指定されたテーブルの列のみを含めることができます。 +- `RIGHT [OUTER] JOIN` の場合: + - 最初の `join_specification` として指定する必要があります。 + - `join_predicate` には、左側のテーブルのすべての主キー列またはセカンダリインデックス列が含まれている必要があります。 + - `WHERE` 述語および `ORDER BY` 句には、`RIGHT OUTER JOIN` 句で指定されたテーブルの列のみを指定できます。 + +`WHERE` 句: + +- `WHERE` 句の任意の列に任意の述語を使用できます。 +- `WHERE` 句では、述語は `and_predicates` の OR 形式 (論理和標準形と呼ばれます) または `or_predicates` の AND 形式 (論理積標準形と呼ばれます) である必要があります。 +- 複数の述語を持つ複数の `and_predicates` または `or_predicates` を接続する場合は、`and_predicates` と `or_predicates` を括弧で囲む必要があります。 +- バインドマーカー (位置指定 `?` および名前指定 `:`) に `` を指定できます。リテラル文法については、[リテラル](#リテラル)セクションを参照してください。 +- `WHERE` 句で暗号化された列を指定することはできません。 + +`LIKE` 述語: + +- `` 内の `_` は任意の1文字に一致します。 +- `` 内の `%` は0個以上の文字の任意のシーケンスに一致します。 +- `` 内の `\` はデフォルトでエスケープ文字として機能します。 + - `ESCAPE` 句を指定してエスケープ文字を変更できます。 + - 空のエスケープ文字 `ESCAPE ''` を指定してエスケープ文字を無効にすることができます。 + +`ORDER BY` 句: + +- `ORDER BY` 句の任意の列に `order` を指定できます。 +- `order` を省略すると、デフォルトの順序 `ASC` が使用されます。 +- `ORDER BY` 句では暗号化された列を指定できません。 + +`LIMIT` 句: + +- バインドマーカー (位置指定 `?` および名前指定 `:`) に `` を指定できます。 + +ScalarDB のデータベースからデータを取得する方法の詳細については、[Get 操作](../api-guide.mdx#get-操作)および [Scan 操作](../api-guide.mdx#操作)を参照してください。 + +#### パーティションスキャンとインデックススキャンの例 + +次のようなテーブルとインデックスがあるとします。 + +```sql +CREATE TABLE ns.tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY (c1, c2, c3) +) WITH CLUSTERING ORDER BY (c2 DESC, c3 ASC); + +CREATE INDEX ON ns.tbl (c4); +``` + +`SELECT` の例は次のとおりです。 + +```sql +-- With a full primary key +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23; + +-- With a full primary key and predicates for non-primary-key columns +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 AND c4 < 100; + +-- With a partial primary key +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa'; + +-- With a partial primary key and predicates for non-primary-key columns +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND (c4 < 100 OR c4 > 500); + +-- With projections and a partition key and clustering-key boundaries +SELECT c1, c2, c3, c5 FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 >= 1.23 AND c3 < 4.56; + +-- With projections and a partition key and clustering-key boundaries and orders and limit +SELECT c1 AS a, c2 AS b, c3 AS c, c5 FROM ns.tbl WHERE c1 = 10 AND c2 > 'aaa' AND c2 <= 'ddd' ORDER BY c2 ASC, c3 DESC LIMIT 10; + +-- With an equality predicate for an indexed column +SELECT * FROM ns.tbl WHERE c4 = 100; + +-- With an equality predicate for an indexed column and predicates for non-primary-key columns +SELECT * FROM ns.tbl WHERE c4 = 100 AND c5 = false; + +-- With projections and an indexed column and limit +SELECT c1, c2, c3, c4 FROM ns.tbl WHERE c4 = 100 LIMIT 10; + +-- With positional bind markers +SELECT * FROM ns.tbl WHERE c1 = ? AND c2 > ? AND c2 <= ? ORDER BY c2 ASC, c3 DESC LIMIT ?; + +-- With operations attributes +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2'; + +-- With an ABAC read tag +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH ABAC_READ_TAG 'read_tag1' FOR POLICY policy1; + +-- With operations attributes and an ABAC read tag +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2' AND ABAC_READ_TAG 'read_tag1' FOR POLICY policy1; +``` + +`SELECT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// With a full primary key +SelectStatement statement1 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .and(Predicate.column("c4").isLessThan(Value.of(100))) + .build(); + +// With a full primary key and predicates for non-primary-key columns +SelectStatement statement1 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c4").isEqualTo(Value.of(1.23F))) + .and(Predicate.column("c4").isLessThan(Value.of(100))) + .build(); + +// With a partial primary key +SelectStatement statement2 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .build(); + +// With a partial primary key and predicates for non-primary-key columns +SelectStatement statement2 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and( + AndPredicateList.predicate(Predicate.column("c4").isLessThan(Value.of(100))) + .and(Predicate.column("c4").isGreaterThan(Value.of(500))) + .build()) + .build(); + +// With projections and a partition key and clustering-key boundaries +SelectStatement statement3 = + StatementBuilder.select("c1", "c2", "c3", "c5") + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isGreaterThanOrEqualTo(Value.of(1.23F))) + .and(Predicate.column("c3").isLessThan(Value.of(4.56F))) + .build(); + +// With projections and a partition key and clustering key boundaries and orders and limit +SelectStatement statement4 = + StatementBuilder.select( + Projection.column("c1").as("a"), + Projection.column("c2").as("b"), + Projection.column("c3").as("c"), + Projection.column("c5").as("d")) + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isGreaterThan(Value.of("aaa"))) + .and(Predicate.column("c2").isLessThanOrEqualTo(Value.of("ddd"))) + .orderBy(Ordering.column("c2").asc(), Ordering.column("c3").desc()) + .limit(10) + .build(); + +// With an equality predicate for an indexed column +SelectStatement statement5 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c4").isEqualTo(Value.of(100))) + .build(); + +// With an equality predicate for an indexed column and predicates for non-primary-key columns +SelectStatement statement5 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c4").isEqualTo(Value.of(100))) + .and(Predicate.column("c5").isEqualTo(Value.of(false))) + .build(); + +// With projections and an indexed column and limit +SelectStatement statement6 = + StatementBuilder.select("c1", "c2", "c3", "c4") + .from("ns", "tbl") + .where(Predicate.column("c4").isEqualTo(Value.of(100))) + .limit(10) + .build(); + +// With positional bind markers +SelectStatement statement7 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c2").isGreaterThan(BindMarker.positional())) + .and(Predicate.column("c2").isLessThanOrEqualTo(BindMarker.positional())) + .orderBy(Ordering.column("c2").asc(), Ordering.column("c3").desc()) + .limit(BindMarker.positional()) + .build(); + +// With operations attributes +SelectStatement statement8 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .build(); + +// With an ABAC read tag +SelectStatement statement9 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAbacReadTag("read_tag1", "policy1") + .build(); + +// With operations attributes and an ABAC read tag +SelectStatement statement10 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .withAbacReadTag("read_tag1", "policy1") + .build(); +``` + +`JOIN` を使用した `SELECT` の例は次のとおりです。 + +```sql +-- For INNER JOIN and LEFT OUTER JOIN: +SELECT * FROM tbl1 as t1 + INNER JOIN tbl2 as t2 on t1.col1=t2.id1 and t1.col2=t2.id2 -- This part must have all primary key columns or a secondary index column of `tbl2`. + WHERE t1.pkey=1 -- Only columns of `tbl1` can be specified here. + ORDER BY t1.ckey DESC; -- Only columns of `tbl1` can be specified here. + +SELECT * FROM tbl1 as t1 + INNER JOIN tbl2 as t2 on t1.col1=t2.id -- This part must have all primary key columns or a secondary index column of `tbl2`. + LEFT OUTER JOIN tbl3 as t3 on t1.col2=t3.id -- This part must have all primary key columns or a secondary index column of `tbl3`. + WHERE t1.pkey=1 -- Only columns of `tbl1` can be specified here. + ORDER BY t1.ckey DESC; -- Only columns of `tbl1` can be specified here. + +-- For RIGHT OUTER JOIN: +SELECT * FROM tbl1 as t1 + RIGHT OUTER JOIN tbl2 as t2 on t1.id=t2.col -- Acceptable as the first join. And this part must have all primary key columns or a secondary index column of `tbl1`. + LEFT OUTER JOIN tbl3 as t3 on t1.col2=t3.id + WHERE t2.pkey=1 -- Only columns of `tbl2` can be specified here. + ORDER BY t2.ckey DESC; -- Only columns of `tbl2` can be specified here. + +SELECT * FROM tbl1 as t1 + RIGHT OUTER JOIN tbl2 as t2 on t1.id1=t2.col1 and t1.id2=t2.col2 -- This part must have all primary key columns or a secondary index column of `tbl1`. + WHERE t2.pkey=1 -- Only columns of `tbl2` can be specified here. + ORDER BY t2.ckey DESC; -- Only columns of `tbl2` can be specified here. +``` + +`JOIN` を使用して `SELECT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// For INNER JOIN and LEFT OUTER JOIN: +SelectStatement statement1 = + StatementBuilder.select() + .from("tbl1", "t1") + .innerJoin("tbl2", "t2") + .on(JoinPredicate.column("t1", "col1").isEqualTo("t2", "id1")) + .and(JoinPredicate.column("t1", "col2").isEqualTo("t2", "id2")) // This part must have all primary key columns or a secondary index column of `tbl2`. + .where(Predicate.column("t1", "pkey").isEqualTo(Value.of(1))) // Only columns of `tbl1` can be specified here. + .orderBy(Ordering.column("t1", "ckey").desc()) // Only columns of `tbl1` can be specified here. + .build(); + +SelectStatement statement2 = + StatementBuilder.select() + .from("tbl1", "t1") + .innerJoin("tbl2", "t2") + .on(JoinPredicate.column("t1", "col1").isEqualTo("t2", "id")) // This part must have all primary key columns or a secondary index column of `tbl2`. + .leftOuterJoin("tbl3", "t3") + .on(JoinPredicate.column("t1", "col2").isEqualTo("t3", "id")) // This part must have all primary key columns or a secondary index column of `tbl3`. + .where(Predicate.column("t1", "pkey").isEqualTo(Value.of(1))) // Only columns of `tbl1` can be specified here. + .orderBy(Ordering.column("t1", "ckey").desc()) // Only columns of `tbl1` can be specified here. + .build(); + +// For RIGHT OUTER JOIN: +SelectStatement statement3 = + StatementBuilder.select() + .from("tbl1", "t1") + .rightOuterJoin("tbl2", "t2") + .on(JoinPredicate.column("t1", "id").isEqualTo("t2", "col")) // Acceptable as the first join. And this part must have all primary key columns or a secondary index column of `tbl1`. + .leftOuterJoin("tbl3", "t3") + .on(JoinPredicate.column("t1", "col2").isEqualTo("t3", "id")) + .where(Predicate.column("t2", "pkey").isEqualTo(Value.of(1))) // Only columns of `tbl2` can be specified here. + .orderBy(Ordering.column("t2", "ckey").desc()) // Only columns of `tbl2` can be specified here. + .build(); + +SelectStatement statement4 = + StatementBuilder.select() + .from("tbl1", "t1") + .rightOuterJoin("tbl2", "t2") + .on(JoinPredicate.column("t1", "id1").isEqualTo("t2", "col1")) + .and(JoinPredicate.column("t1", "id2").isEqualTo("t2", "col2")) // This part must have all primary key columns or a secondary index column of `tbl1`. + .where(Predicate.column("t2", "pkey").isEqualTo(Value.of(1))) // Only columns of `tbl2` can be specified here. + .orderBy(Ordering.column("t2", "ckey").desc()) // Only columns of `tbl2` can be specified here. + .build(); +``` + +#### クロスパーティションスキャンの例 + +たとえば、次のテーブルがあるとします。 + +```sql +CREATE TABLE ns.user ( + id INT, + name TEXT, + age INT, + height FLOAT, + PRIMARY KEY (id) +) +``` + +クロスパーティションスキャンを使用した `SELECT` の例は次のとおりです。 + +```sql +-- Without the WHERE clause to retrieve all the records of a table +SELECT * FROM ns.user; + +-- Without the WHERE clause and with projections and a limit +SELECT id, name FROM ns.user LIMIT 10; + +-- With AND predicates for non-primary-key columns +SELECT * FROM ns.user WHERE age > 10 AND height > 140; + +-- With OR predicates for non-primary key columns +SELECT * FROM ns.user WHERE age > 10 OR height > 140; + +-- With OR-wise of AND predicates +SELECT * FROM ns.user WHERE (age > 10 AND height > 150) OR (age > 15 AND height > 145); + +-- With AND-wise of OR predicates +SELECT * FROM ns.user WHERE (age < 10 OR age > 65) AND (height < 145 OR height > 175); + +-- With LIKE predicates +SELECT * FROM ns.user WHERE name LIKE 'A%' OR name NOT LIKE 'B_b'; + +-- With LIKE predicates with an escape character +SELECT * FROM ns.user WHERE name LIKE '+%Alice' ESCAPE '+'; + +-- With IS NULL predicates +SELECT * FROM ns.user WHERE name IS NOT NULL AND age IS NULL; + +-- With projections +SELECT name, age, height FROM ns.user WHERE (age < 10 OR age > 65) AND age <> 0; + +-- With limit +SELECT name, age, height FROM ns.user WHERE age < 10 OR age > 65 LIMIT 10; + +-- With orderings +SELECT * FROM ns.user WHERE age < 10 ORDER BY height DESC; + +-- With orderings without the WHERE clause +SELECT * FROM ns.user ORDER BY height; + +-- With positional bind markers +SELECT * FROM ns.user WHERE age < ? ORDER BY age ASC, height DESC LIMIT ?; +``` + +`JOIN` 句を使用する例については、[パーティションスキャンとインデックススキャンの例](#パーティションスキャンとインデックススキャンの例)を参照してください。 + +`SELECT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Without the WHERE clause to retrieve all the records of a table +SelectStatement statement1 = StatementBuilder.select().from("ns", "user").build(); + +// Without the WHERE clause and with projections and a limit +SelectStatement statement2 = + StatementBuilder.select("id", "name").from("ns", "user").limit(10).build(); + +// With AND predicates for non-primary-key columns +SelectStatement statement2 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR predicates for non-primary key columns +SelectStatement statement3 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .or(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR-wise of AND predicates +SelectStatement statement4 = + StatementBuilder.select() + .from("ns", "user") + .where( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build()) + .or( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(15))) + .and(Predicate.column("height").isGreaterThan(Value.of(145.0F))) + .build()) + .build(); + +// With AND-wise of OR predicates +SelectStatement statement5 = + StatementBuilder.select() + .from("ns", "user") + .where( + OrPredicateList.predicate(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .build()) + .and( + OrPredicateList.predicate(Predicate.column("height").isLessThan(Value.of(145.0F))) + .or(Predicate.column("height").isGreaterThan(Value.of(175.0F))) + .build()) + .build(); + +// With LIKE predicates +SelectStatement statement6 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("name").isLike(Value.of("A%"))) + .or(Predicate.column("name").isNotLike(Value.of("B_b"))) + .build(); + +// With LIKE predicates with an escape character +SelectStatement statement7 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("name").isLike(Value.of("+%Alice"), Value.of("+"))) + .build(); + +// With IS NULL predicates +SelectStatement statement8 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("name").isNotNull()) + .and(Predicate.column("age").isNull()) + .build(); + +// With projections +SelectStatement statement9 = + StatementBuilder.select("name", "age", "height") + .from("ns", "user") + .where( + OrPredicateList.predicate(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .build()) + .and(Predicate.column("height").isNotEqualTo(Value.of(0))) + .build(); + +// With limit +SelectStatement statement10 = + StatementBuilder.select("name", "age", "height") + .from("ns", "user") + .where(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .limit(10) + .build(); + +// With orderings +SelectStatement statement11 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("age").isLessThan(Value.of(10))) + .orderBy(Ordering.column("height").desc()) + .build(); + +// With orderings without the WHERE clause +SelectStatement statement12 = + StatementBuilder.select() + .from("ns", "user") + .orderBy(Ordering.column("height").desc()) + .build(); + +// With positional bind markers +SelectStatement statement13 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("age").isLessThan(BindMarker.positional())) + .orderBy(Ordering.column("age").asc(), Ordering.column("height").desc()) + .limit(BindMarker.positional()) + .build(); +``` + +`JOIN` 句を使用する例については、[パーティションスキャンとインデックススキャンの例](#パーティションスキャンとインデックススキャンの例)を参照してください。 + +### INSERT + +`INSERT` コマンドは、データベースに新しいレコードを挿入します。対象レコードのいずれかがすでに存在する場合、トランザクション競合エラーがスローされます。 + +このコマンドは次の列を返します: + +- `updateCount`: `INT` - 挿入されたレコードの数 + +#### 文法 + +```sql +INSERT INTO [.]
[( [, ] ...)] + VALUES ( [, ] ...) [, ( [, ] ...)] ... + [WITH operation_attributes_or_abac_read_tags_or_abac_write_tags] + +operation_attributes_or_abac_read_tags_or_abac_write_tags: operation_attribute_or_abac_read_tag_or_abac_write_tag [AND operation_attribute_or_abac_read_tag_or_abac_write_tag] ... +operation_attribute_or_abac_read_tag_or_abac_write_tag: operation_attribute | abac_read_tag | abac_write_tag +operation_attribute: = +abac_read_tag: ABAC_READ_TAG FOR [POLICY] +abac_write_tag: ABAC_WRITE_TAG FOR [POLICY] +``` + +- `INSERT` では完全な主キーを指定する必要があります。 +- バインドマーカー (位置 `?` および名前 `:`) に `` を指定できます。リテラル文法については、[リテラル](#リテラル)セクションを参照してください。 + +#### 例 + +`INSERT` の例は次のとおりです。 + +```sql +-- Insert a record without specifying column names +INSERT INTO ns.tbl VALUES (10, 'aaa', 1.23, 100, true); + +-- Insert a record with column names +INSERT INTO ns.tbl (c1, c2, c3, c4) VALUES (10, 'aaa', 1.23, 100); + +-- With positional bind markers +INSERT INTO tbl VALUES (?, ?, ?, ?, ?); + +-- Insert multiple records +INSERT INTO ns.tbl (c1, c2, c3, c4) VALUES (10, 'aaa', 1.23, 100), (20, 'bbb', 4.56, 200); +``` + +`INSERT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Insert a record without specifying column names. +InsertStatement statement1 = StatementBuilder.insertInto("ns", "tbl") + .values(Value.ofInt(10), Value.ofText("aaa"), Value.of(1.23F), Value.of(100L), Value.of(true)) + .build(); + +// Insert a record with column names. +InsertStatement statement2 = StatementBuilder.insertInto("ns", "tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values(Value.ofInt(10), Value.ofText("aaa"), Value.of(1.23F), Value.of(100L), Value.of(true)) + .build(); + +// With positional bind markers +InsertStatement statement3 = + StatementBuilder.insertInto("tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values( + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional()) + .build(); + +// Insert multiple records. +InsertStatement statement4 = StatementBuilder.insertInto("ns", "tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values(Value.ofInt(10), Value.ofText("aaa"), Value.of(1.23F), Value.of(100L), Value.of(true)) + .values(Value.ofInt(20), Value.ofText("bbb"), Value.of(2.46F), Value.of(200L), Value.of(false)) + .build(); +``` + +### UPSERT + +`UPSERT` コマンドは、データベースに新しいレコードが存在しない場合はそれを挿入し、すでに存在する場合はターゲットレコードを更新します。 + +このコマンドは次の列を返します: + +- `updateCount`: `INT` - 挿入または更新されたレコードの数 + +#### 文法 + +```sql +UPSERT INTO [.]
[( [, ] ...)] + VALUES ( [, ] ...) [, ( [, ] ...)] ... + [WITH operation_attributes] + +operation_attributes: = [AND =] ... +``` + +- `INSERT` では完全な主キーを指定する必要があります。 +- バインドマーカー (位置 `?` および名前 `:`) に `` を指定できます。リテラル文法については、[リテラル](#リテラル)セクションを参照してください。 + +#### 例 + +`UPSERT` の例は次のとおりです。 + +```sql +-- Upsert a record without specifying column names. +UPSERT INTO ns.tbl VALUES (10, 'aaa', 1.23, 100, true); + +-- Upsert a record with column names. +UPSERT INTO ns.tbl (c1, c2, c3, c4) VALUES (10, 'aaa', 1.23, 100); + +-- With positional bind markers +UPSERT INTO tbl VALUES (?, ?, ?, ?, ?); + +-- Upsert multiple records. +UPSERT INTO ns.tbl (c1, c2, c3, c4) VALUES (10, 'aaa', 1.23, 100), (20, 'bbb', 4.56, 200); + +-- With operations attributes +UPSERT INTO ns.tbl VALUES (10, 'aaa', 1.23, 100, true) WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2'; + +-- With an ABAC read tag and an ABAC write tag +UPSERT INTO ns.tbl VALUES (10, 'aaa', 1.23, 100, true) WITH ABAC_READ_TAG 'read_tag1' FOR POLICY policy1 AND ABAC_WRITE_TAG 'write_tag1' FOR POLICY policy1; + +-- With operations attributes and ABAC read and write tags +UPSERT INTO ns.tbl VALUES (10, 'aaa', 1.23, 100, true) WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2' AND ABAC_READ_TAG 'read_tag1' FOR POLICY policy1 AND ABAC_WRITE_TAG 'write_tag1' FOR POLICY policy1; +``` + +`UPSERT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Upsert a record without specifying column names. +UpsertStatement statement1 = + StatementBuilder.upsertInto("ns", "tbl") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .build(); + +// Upsert a record with column names. +UpsertStatement statement2 = + StatementBuilder.upsertInto("ns", "tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .build(); + +// With positional bind markers +UpsertStatement statement3 = + StatementBuilder.upsertInto("tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values( + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional()) + .build(); + +// Upsert multiple records. +UpsertStatement statement4 = + StatementBuilder.upsertInto("ns", "tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .values( + Value.ofInt(20), + Value.ofText("bbb"), + Value.of(2.46F), + Value.of(200L), + Value.of(false)) + .build(); + +// With operations attributes +UpsertStatement statement5 = + StatementBuilder.upsertInto("ns", "tbl") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .build(); + +// With an ABAC read tag and an ABAC write tag +UpsertStatement statement6 = + StatementBuilder.upsertInto("ns", "tbl") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .withAbacReadTag("read_tag1", "policy1") + .withAbacWriteTag("write_tag1", "policy1") + .build(); + +// With operations attributes and ABAC read and write tags +UpsertStatement statement7 = + StatementBuilder.upsertInto("ns", "tbl") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .withAbacReadTag("read_tag1", "policy1") + .withAbacWriteTag("write_tag1", "policy1") + .build(); +``` + +### UPDATE + +`UPDATE` コマンドは、データベース内の既存のレコードを更新します。`WHERE` 句に任意の条件を指定してレコードをフィルタリングできます。ただし、特に非 JDBC データベースでは、クロスパーティション操作によってパフォーマンスと一貫性の問題が発生する可能性があるため、クロスパーティション操作を回避するには、主キーを可能な限り一意に指定することをお勧めします。ScalarDB SQL は、`Get` または `Scan` 操作を使用してターゲットレコードを識別する `UPDATE` コマンドの実行プランを作成するため、レコードの選択にも同じルールが適用されます。クロスパーティション操作を引き起こす `WHERE` 句の種類を理解し、そのような操作を回避するには、[SELECT](#select) を参照してください。 + +`WHERE` 句を指定せずにパーティション全体のすべてのレコードを更新する場合は、クロスパーティションスキャンオプションを有効にする必要があります。また、`WHERE` 句で任意の条件を使用してパーティション全体のレコードを柔軟に更新する場合は、フィルタリングオプション付きのクロスパーティションスキャンを有効にする必要があります。設定の詳細については、[クロスパーティションスキャン設定](../configurations.mdx#クロスパーティションスキャン設定)および [ScalarDB Cluster SQL クライアント設定](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +:::warning + +非 JDBC データベースの場合、`SERIALIZABLE` 分離レベルでクロスパーティションスキャンを有効にした場合でも、トランザクションは読み取りコミットスナップショット分離 (`SNAPSHOT`) で実行される可能性があります。これは、より低い分離レベルです。非 JDBC データベースを使用する場合は、トランザクションの一貫性が重要でない場合にのみ、クロスパーティションスキャンを使用してください。 + +::: + +このコマンドは次の列を返します: + +- `updateCount`: `INT` - 更新されたレコードの数 + +#### 文法 + +```sql +UPDATE [.]
[AS ] + SET = [, = ] ... + [WHERE and_predicates [OR and_predicates ...] | or_predicates [AND or_predicates ...]] + [WITH operation_attributes_or_abac_read_tags_or_abac_write_tags] + +identifier: [[.]
.] | [alias.] +and_predicates: predicate | (predicate [AND predicate ...]) +or_predicates: predicate | (predicate [OR predicate ...]) +predicate: operator | BETWEEN AND | [NOT] LIKE [ESCAPE ] | IS [NOT] NULL +operator: = | <> | != | > | >= | < | <= +operation_attributes_or_abac_read_tags_or_abac_write_tags: operation_attribute_or_abac_read_tag_or_abac_write_tag [AND operation_attribute_or_abac_read_tag_or_abac_write_tag] ... +operation_attribute_or_abac_read_tag_or_abac_write_tag: operation_attribute | abac_read_tag | abac_write_tag +operation_attribute: = +abac_read_tag: ABAC_READ_TAG FOR [POLICY] +abac_write_tag: ABAC_WRITE_TAG FOR [POLICY] +``` + +##### 注記 + +`WHERE` 句: + +- `WHERE` 句の任意の列に任意の述語を使用できます。 +- `WHERE` 句では、述語は `and_predicates` の OR 形式 (論理和標準形と呼ばれます) または `or_predicates` の AND 形式 (論理積標準形と呼ばれます) である必要があります。 +- 複数の述語を持つ複数の `and_predicates` または `or_predicates` を接続する場合は、`and_predicates` と `or_predicates` を括弧で囲む必要があります。 +- バインドマーカー (位置 `?` および名前 `:`) に `` を指定できます。リテラル文法については、[リテラル](#リテラル)セクションを参照してください。 +- `WHERE` 句で暗号化された列を指定することはできません。 + +`LIKE` 述語: + +- `` 内の `_` は任意の1文字に一致します。 +- `` 内の `%` は0個以上の文字の任意のシーケンスに一致します。 +- `` 内の `\` はデフォルトでエスケープ文字として機能します。 + - `ESCAPE` 句を指定してエスケープ文字を変更できます。 + - 空のエスケープ文字 `ESCAPE ''` を指定してエスケープ文字を無効にすることができます。 + +#### 主キーを指定した例 + +たとえば、次のテーブルがあるとします。 + +```sql +CREATE TABLE ns.tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY (c1, c2, c3) +) WITH CLUSTERING ORDER BY (c2 DESC, c3 ASC); +``` + +完全な主キーを指定した `UPDATE` の例は次のとおりです。 + +```sql +-- Update a record +UPDATE ns.tbl SET c4 = 200, c5 = false WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23; + +-- With positional bind markers +UPDATE ns.tbl SET c4 = ?, c5 = ? WHERE c1 = ? AND c2 = ? AND c3 = ?; + +-- With operations attributes +UPDATE ns.tbl SET c4 = 200, c5 = false WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2'; + +-- With an ABAC read tag and an ABAC write tag +UPDATE ns.tbl SET c4 = 200, c5 = false WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH ABAC_READ_TAG 'read_tag1' FOR POLICY policy1 AND ABAC_WRITE_TAG 'write_tag1' FOR POLICY policy1; + +-- With operations attributes and ABAC read and write tags +UPDATE ns.tbl SET c4 = 200, c5 = false WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2' AND ABAC_READ_TAG 'read_tag1' FOR POLICY policy1 AND ABAC_WRITE_TAG 'write_tag1' FOR POLICY policy1; +``` + +`UPDATE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Update a record +UpdateStatement statement1 = + StatementBuilder.update("ns", "tbl") + .set( + Assignment.column("c4").value(Value.of(200L)), + Assignment.column("c5").value(Value.of(false))) + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .build(); + +// With positional bind markers +UpdateStatement statement2 = + StatementBuilder.update("tbl") + .set( + Assignment.column("c4").value(BindMarker.positional()), + Assignment.column("c5").value(BindMarker.positional())) + .where(Predicate.column("c1").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c2").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c3").isEqualTo(BindMarker.positional())) + .build(); + +// With operations attributes +UpdateStatement statement3 = + StatementBuilder.update("ns", "tbl") + .set( + Assignment.column("c4").value(Value.of(200L)), + Assignment.column("c5").value(Value.of(false))) + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .build(); + +// With an ABAC read tag and an ABAC write tag +UpdateStatement statement4 = + StatementBuilder.update("ns", "tbl") + .set( + Assignment.column("c4").value(Value.of(200L)), + Assignment.column("c5").value(Value.of(false))) + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAbacReadTag("read_tag1", "policy1") + .withAbacWriteTag("write_tag1", "policy1") + .build(); + +// With operations attributes and ABAC read and write tags +UpdateStatement statement5 = + StatementBuilder.update("ns", "tbl") + .set( + Assignment.column("c4").value(Value.of(200L)), + Assignment.column("c5").value(Value.of(false))) + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .withAbacReadTag("read_tag1", "policy1") + .withAbacWriteTag("write_tag1", "policy1") + .build(); +``` + +#### 完全な主キーが指定されていない例 + +たとえば、次のテーブルがあるとします。 + +```sql +CREATE TABLE ns.user ( + id INT, + name TEXT, + age INT, + height FLOAT, + PRIMARY KEY (id) +) +``` + +完全な主キーを指定しない `UPDATE` の例は次のとおりです。 + +```sql +-- Without the WHERE clause to update all the records of a table +UPDATE ns.user SET age = 31; + +-- With AND predicates for non-primary key columns +UPDATE ns.user SET age = 31 WHERE age > 10 AND height > 140; + +-- With OR predicates for non-primary key columns +UPDATE ns.user SET age = 31 WHERE age > 10 OR height > 140; + +-- With OR-wise of AND predicates +UPDATE ns.user SET age = 31 WHERE (age > 10 AND height > 150) OR (age > 15 AND height > 145); + +-- With AND-wise of OR predicates +UPDATE ns.user SET age = 31 WHERE (age < 10 OR age > 65) AND (height < 145 OR height > 175); + +-- With LIKE predicates +UPDATE ns.user SET age = 31 WHERE name LIKE 'A%' OR name NOT LIKE 'B_b'; + +-- With LIKE predicates with an escape character +UPDATE ns.user SET age = 31 WHERE name LIKE '+%Alice' ESCAPE '+'; + +-- With IS NULL predicates +UPDATE ns.user SET age = 31 WHERE name IS NOT NULL AND age IS NULL; + +-- With positional bind markers +UPDATE ns.user SET age = ? WHERE age < ?; +``` + +`UPDATE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Without the WHERE clause to update all the records of a table +UpdateStatement statement1 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .build(); + +// With AND predicates for non-primary key columns +UpdateStatement statement2 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR predicates for non-primary key columns +UpdateStatement statement3 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .or(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR-wise of AND predicates +UpdateStatement statement4 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build()) + .or( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(15))) + .and(Predicate.column("height").isGreaterThan(Value.of(145.0F))) + .build()) + .build(); + +// With AND-wise of OR predicates +UpdateStatement statement5 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where( + OrPredicateList.predicate(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .build()) + .and( + OrPredicateList.predicate(Predicate.column("height").isLessThan(Value.of(145.0F))) + .or(Predicate.column("height").isGreaterThan(Value.of(175.0F))) + .build()) + .build(); + +// With LIKE predicates +UpdateStatement statement6 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("name").isLike(Value.of("A%"))) + .or(Predicate.column("name").isNotLike(Value.of("B_b"))) + .build(); + +// With LIKE predicates with an escape character +UpdateStatement statement7 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("name").isLike(Value.of("+%Alice"), Value.of("+"))) + .build(); + +// With IS NULL predicates +UpdateStatement statement8 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("name").isNotNull()) + .and(Predicate.column("age").isNull()) + .build(); + +// With positional bind markers +UpdateStatement statement9 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(BindMarker.positional())) + .where(Predicate.column("age").isLessThan(BindMarker.positional())) + .build(); +``` + +### DELETE + +`DELETE` コマンドは、データベース内のレコードを削除します。`WHERE` 句に任意の条件を指定してレコードをフィルターできます。ただし、特に非 JDBC データベースでは、クロスパーティション操作によってパフォーマンスと一貫性の問題が発生する可能性があるため、クロスパーティション操作を回避するには、可能な限り主キーを一意に指定することをお勧めします。ScalarDB SQL は、ターゲットレコードを識別するために `Get` または `Scan` 操作を使用する `DELETE` コマンドの実行プランを作成するため、レコードの選択にも同じルールが適用されます。クロスパーティション操作を引き起こす `WHERE` 句の種類を理解し、そのような操作を回避するには、[SELECT](#select) を参照してください。 + +`WHERE` 句を指定せずにパーティション全体のすべてのレコードを削除する場合は、クロスパーティションスキャンオプションを有効にする必要があります。また、`WHERE` 句で任意の条件を使用してパーティション全体のレコードを柔軟に削除する場合は、フィルタリングオプションを使用したクロスパーティションスキャンを有効にする必要があります。設定の詳細については、[クロスパーティションスキャン設定](../configurations.mdx#クロスパーティションスキャン設定)および [ScalarDB Cluster SQL クライアント設定](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +:::warning + +非 JDBC データベースの場合、`SERIALIZABLE` 分離レベルでクロスパーティションスキャンを有効にした場合でも、トランザクションは読み取りコミットスナップショット分離 (`SNAPSHOT`) で実行される可能性があります。これは、より低い分離レベルです。非 JDBC データベースを使用する場合は、トランザクションの一貫性が重要でない場合にのみ、クロスパーティションスキャンを使用してください。 + +::: + +このコマンドは次の列を返します: + +- `updateCount`: `INT` - 削除されたレコードの数 + +#### 文法 + +```sql +DELETE FROM [.]
[AS ] + [WHERE and_predicates [OR and_predicates ...] | or_predicates [AND or_predicates ...]] + [WITH operation_attributes_or_abac_read_tags_or_abac_write_tags] + +identifier: [[.]
.] | [alias.] +and_predicates: predicate | (predicate [AND predicate ...]) +or_predicates: predicate | (predicate [OR predicate ...]) +predicate: operator | BETWEEN AND | [NOT] LIKE [ESCAPE ] | IS [NOT] NULL +operator: = | <> | != | > | >= | < | <= +operation_attributes_or_abac_read_tags_or_abac_write_tags: operation_attribute_or_abac_read_tag_or_abac_write_tag [AND operation_attribute_or_abac_read_tag_or_abac_write_tag] ... +operation_attribute_or_abac_read_tag_or_abac_write_tag: operation_attribute | abac_read_tag | abac_write_tag +operation_attribute: = +abac_read_tag: ABAC_READ_TAG FOR [POLICY] +abac_write_tag: ABAC_WRITE_TAG FOR [POLICY] +``` + +##### 注記 + +`WHERE` 句: + +- `WHERE` 句の任意の列に任意の述語を使用できます。 +- `WHERE` 句では、述語は `and_predicates` の OR 形式 (論理和標準形と呼ばれます) または `or_predicates` の AND 形式 (論理積標準形と呼ばれます) である必要があります。 +- 複数の述語を持つ複数の `and_predicates` または `or_predicates` を接続する場合は、`and_predicates` と `or_predicates` を括弧で囲む必要があります。 +- バインドマーカー (位置 `?` および名前 `:`) に `` を指定できます。リテラル文法については、[リテラル](#リテラル)セクションを参照してください。 +- `WHERE` 句で暗号化された列を指定することはできません。 + +`LIKE` 述語: + +- `` 内の `_` は任意の1文字に一致します。 +- `` 内の `%` は0個以上の文字の任意のシーケンスに一致します。 +- `` 内の `\` はデフォルトでエスケープ文字として機能します。 + - `ESCAPE` 句を指定してエスケープ文字を変更できます。 + - 空のエスケープ文字 `ESCAPE ''` を指定してエスケープ文字を無効にすることができます。 + +#### 主キーを指定した例 + +たとえば、次のテーブルがあるとします。 + +```sql +CREATE TABLE ns.tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY (c1, c2, c3) +) WITH CLUSTERING ORDER BY (c2 DESC, c3 ASC); +``` + +`DELETE` の例は次のとおりです。 + +```sql +-- Delete a record +DELETE FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23; + +-- With positional bind markers +DELETE FROM tbl WHERE c1 = ? AND c2 = ? AND c3 = ?; + +-- With operations attributes +DELETE FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2'; + +-- With an ABAC read tag and an ABAC write tag +DELETE FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH ABAC_READ_TAG 'read_tag1' FOR POLICY policy1 AND ABAC_WRITE_TAG 'write_tag1' FOR POLICY policy1; + +-- With operations attributes and ABAC read and write tags +DELETE FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2' AND ABAC_READ_TAG 'read_tag1' FOR POLICY policy1 AND ABAC_WRITE_TAG 'write_tag1' FOR POLICY policy1; +``` + +`DELETE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Delete a record +DeleteStatement statement1 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .build(); + +// With positional bind markers +DeleteStatement statement2 = + StatementBuilder.deleteFrom("tbl") + .where(Predicate.column("c1").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c2").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c3").isEqualTo(BindMarker.positional())) + .build(); + +// With operations attributes +DeleteStatement statement3 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .build(); + +// With an ABAC read tag and an ABAC write tag +DeleteStatement statement4 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAbacReadTag("read_tag1", "policy1") + .withAbacWriteTag("write_tag1", "policy1") + .build(); + +// With operations attributes and ABAC read and write tags +DeleteStatement statement5 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .withAbacReadTag("read_tag1", "policy1") + .withAbacWriteTag("write_tag1", "policy1") + .build(); +``` + +#### 完全な主キーが指定されていない例 + +たとえば、次のテーブルがあるとします。 + +```sql +CREATE TABLE ns.user ( + id INT, + name TEXT, + age INT, + height FLOAT, + PRIMARY KEY (id) +) +``` + +クロスパーティションスキャンフィルタリングを使用した `DELETE` の例は次のとおりです。 + +```sql +-- Without the WHERE clause to delete all the records of a table +DELETE FROM ns.user; + +-- With AND predicates for non-primary key columns +DELETE FROM ns.user WHERE age > 10 AND height > 140; + +-- With OR predicates for non-primary key columns +DELETE FROM ns.user WHERE age > 10 OR height > 140; + +-- With OR-wise of AND predicates +DELETE FROM ns.user WHERE (age > 10 AND height > 150) OR (age > 15 AND height > 145); + +-- With AND-wise of OR predicates +DELETE FROM ns.user WHERE (age < 10 OR age > 65) AND (height < 145 OR height > 175); + +-- With LIKE predicates +DELETE FROM ns.user WHERE name LIKE 'A%' OR name NOT LIKE 'B_b'; + +-- With LIKE predicates with an escape character +DELETE FROM ns.user WHERE name LIKE '+%Alice' ESCAPE '+'; + +-- With IS NULL predicates +DELETE FROM ns.user WHERE name IS NOT NULL AND age IS NULL; + +-- With positional bind markers +DELETE FROM ns.user WHERE age < ?; +``` + +`DELETE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Without the WHERE clause to delete all the records of a table +DeleteStatement statement1 = StatementBuilder.deleteFrom("ns", "tbl").build(); + +// With AND predicates for non-primary key columns +DeleteStatement statement2 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR predicates for non-primary key columns +DeleteStatement statement3 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .or(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR-wise of AND predicates +DeleteStatement statement4 = + StatementBuilder.deleteFrom("ns", "tbl") + .where( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build()) + .or( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(15))) + .and(Predicate.column("height").isGreaterThan(Value.of(145.0F))) + .build()) + .build(); + +// With AND-wise of OR predicates +DeleteStatement statement5 = + StatementBuilder.deleteFrom("ns", "tbl") + .where( + OrPredicateList.predicate(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .build()) + .and( + OrPredicateList.predicate(Predicate.column("height").isLessThan(Value.of(145.0F))) + .or(Predicate.column("height").isGreaterThan(Value.of(175.0F))) + .build()) + .build(); + +// With LIKE predicates +DeleteStatement statement6 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("name").isLike(Value.of("A%"))) + .or(Predicate.column("name").isNotLike(Value.of("B_b"))) + .build(); + +// With LIKE predicates with an escape character +DeleteStatement statement7 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("name").isLike(Value.of("+%Alice"), Value.of("+"))) + .build(); + +// With IS NULL predicates +DeleteStatement statement8 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("name").isNotNull()) + .and(Predicate.column("age").isNull()) + .build(); + +// With positional bind markers +DeleteStatement statement9 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("age").isLessThan(BindMarker.positional())) + .build(); +``` + +## DCL + +### CREATE USER + +`CREATE USER` コマンドは、指定されたユーザー名、パスワード、およびユーザー属性を持つ新しいユーザーを作成します。 + +#### 文法 + +```sql +CREATE USER [WITH] {PASSWORD | SUPERUSER | NO_SUPERUSER} ... +``` + +- ユーザーにパスワードを指定しない場合、ユーザーはパスワードなしで作成されます。 +- ユーザーに `SUPERUSER` 属性を指定すると、ユーザーはスーパーユーザーになります。 +- ユーザーに `NO_SUPERUSER` 属性を指定すると、ユーザーは通常のユーザーになります。 +- ユーザーに `SUPERUSER` または `NO_SUPERUSER` のどちらも指定しない場合、ユーザーは通常のユーザーになります。 + +#### 例 + +`CREATE USER` の例は次のとおりです。 + +```sql +-- Create a user with a password as a superuser. +CREATE USER user1 WITH PASSWORD 'password1' SUPERUSER; + +-- Create a user with a password. +CREATE USER user2 WITH PASSWORD 'password2'; + +-- Create a user without a password. +CREATE USER user3; +``` + +`CREATE USER` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create a user with a password and the `SUPERUSER` attribute. +CreateUserStatement statement1 = + StatementBuilder.createUser("user1").with("password", UserOption.SUPERUSER).build(); + +// Create a user with a password. +CreateUserStatement statement2 = StatementBuilder.createUser("user1").with("password").build(); + +// Create a user without a password. +CreateUserStatement statement3 = StatementBuilder.createUser("user1").build(); +``` + +### ALTER USER + +`ALTER USER` コマンドは、指定されたユーザーのパスワードとユーザー属性を変更します。 + +#### 文法 + +```sql +ALTER USER [WITH] {PASSWORD | SUPERUSER | NO_SUPERUSER} ... +``` + +- ユーザーに `SUPERUSER` 属性を指定すると、ユーザーはスーパーユーザーになります。 +- ユーザーに `NO_SUPERUSER` 属性を指定すると、ユーザーは通常のユーザーになります。 + +#### 例 + +`ALTER USER` の例は次のとおりです。 + +```sql +-- Change the password of a user. +ALTER USER user1 WITH PASSWORD 'password1'; + +-- Change a user to a superuser. +ALTER USER user1 WITH SUPERUSER; +``` + +`ALTER USER` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Change the password of a user. +AlterUserStatement statement1 = StatementBuilder.alterUser("user1").with("password2").build(); + +// Change a user to a superuser. +AlterUserStatement statement2 = + StatementBuilder.alterUser("user1").with(UserOption.SUPERUSER).build(); +``` + +### DROP USER + +`DROP USER` コマンドは指定されたユーザーを削除します。 + +#### 文法 + +```sql +DROP USER +``` + +#### 例 + +`DROP USER` の例は次のとおりです。 + +```sql +-- Delete a user. +DROP USER user1; +``` + +`DROP USER` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Delete a user. +DropUserStatement statement = StatementBuilder.dropUser("user1").build(); +``` + +### GRANT + +`GRANT` コマンドは指定されたユーザーに権限を付与します。 + +#### 文法 + +```sql +GRANT {privilege [, privilege] ... | ALL [PRIVILEGES]} ON [TABLE]
[,
] ... TO [USER] [, ] ... [WITH GRANT OPTION] +GRANT {privilege [, privilege] ... | ALL [PRIVILEGES]} ON NAMESPACE [, ] ... TO [USER] [, ] ... [WITH GRANT OPTION] + +privilege: SELECT | INSERT | UPDATE | DELETE | CREATE | DROP | TRUNCATE | ALTER +``` + +- `INSERT` 権限と `UPDATE` 権限を一緒に付与する必要があります。 +- ユーザーに `UPDATE` 権限または `DELETE` 権限を付与するには、対象ユーザーに `SELECT` 権限が必要です。 +- `WITH GRANT OPTION` オプションを指定すると、ユーザーは他のユーザーに権限を付与できます。 + +#### 例 + +`GRANT` の例は次のとおりです。 + +```sql +-- Grant the SELECT privilege on a table to a user. +GRANT SELECT ON ns.tbl TO user1; + +-- Grant the SELECT privilege on tables to users. +GRANT SELECT ON ns.tbl1, ns.tbl2 TO user1, user2; + +-- Grant the SELECT privilege on all tables in a namespace to a user. +GRANT SELECT ON NAMESPACE ns TO user1; + +-- Grant all privileges and GRANT OPTION on a table to a user. +GRANT ALL ON ns.tbl TO user1 WITH GRANT OPTION; + +-- Grant all privileges and GRANT OPTION on all tables in a namespace to a user. +GRANT ALL ON NAMESPACE ns TO user1 WITH GRANT OPTION; +``` + +`GRANT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Grant the SELECT privilege on a table to a user. +GrantStatement statement1 = + StatementBuilder.grant(Privilege.SELECT).onTable("ns", "tbl").toUser("user1").build(); + +// Grant the SELECT privilege on tables to users. +GrantStatement statement2 = + StatementBuilder.grant(Privilege.SELECT) + .onTable("ns", "tbl1", "ns", "tbl2") + .toUser("user1", "user2") + .build(); + +// Grant the SELECT privilege on all tables in a namespace to a user. +GrantStatement statement3 = + StatementBuilder.grant(Privilege.SELECT).onNamespace("ns").toUser("user1").build(); + +// Grant all privileges and GRANT OPTION on a table to a user. +GrantStatement statement4 = + StatementBuilder.grant(Privilege.values()) + .onTable("ns", "tbl") + .toUser("user1") + .withGrantOption() + .build(); + +// Grant all privileges and GRANT OPTION on all tables in a namespace to a user. +GrantStatement statement5 = + StatementBuilder.grant(Privilege.values()) + .onNamespace("ns") + .toUser("user1") + .withGrantOption() + .build(); +``` + +### REVOKE + +`REVOKE` コマンドは、指定されたユーザーの権限を取り消します。 + +#### 文法 + +```sql +REVOKE {privilege [, privilege] ... | ALL [PRIVILEGES]} [, GRANT OPTION] ON [TABLE]
[,
] ... FROM [USER] [, ] ... +REVOKE GRANT OPTION ON [TABLE]
[,
] ... FROM [USER] [, ] ... +REVOKE {privilege [, privilege] ... | ALL [PRIVILEGES]} [, GRANT OPTION] ON NAMESPACE [, ] ... FROM [USER] [, ] ... +REVOKE GRANT OPTION ON NAMESPACE [, ] ... FROM [USER] [, ] ... + +privilege: SELECT | INSERT | UPDATE | DELETE | CREATE | DROP | TRUNCATE | ALTER +``` + +- `INSERT` 権限と `UPDATE` 権限は同時に取り消す必要があります。 +- 対象ユーザーが `INSERT` 権限または `UPDATE` 権限を持っている場合、それらのユーザーから `SELECT` 権限を取り消すことはできません。 + +#### 例 + +`REVOKE` の例は次のとおりです。 + +```sql +-- Revoke the SELECT privilege on a table from a user. +REVOKE SELECT ON ns.tbl FROM user1; + +-- Revoke the SELECT privilege on tables from users. +REVOKE SELECT ON ns.tbl1, ns.tbl2 FROM user1, user2; + +-- Revoke the SELECT privilege on all tables in a namespace from a user. +REVOKE SELECT ON NAMESPACE ns FROM user1; + +-- Revoke all privileges and GRANT OPTION on a table from a user. +REVOKE ALL, GRANT OPTION ON ns.tbl FROM user1; + +-- Revoke all privileges and GRANT OPTION on all tables in a namespace from a user. +REVOKE ALL, GRANT OPTION ON NAMESPACE ns FROM user1; +``` + +`REVOKE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Revoke the SELECT privilege on a table from a user. +RevokeStatement statement1 = + StatementBuilder.revoke(Privilege.SELECT).onTable("ns", "tbl").fromUser("user1").build(); + +// Revoke the SELECT privilege on tables from users. +RevokeStatement statement2 = + StatementBuilder.revoke(Privilege.SELECT) + .onTable("ns", "tbl1", "ns", "tbl2") + .fromUser("user1", "user2") + .build(); + +// Revoke the SELECT privilege on all tables in a namespace from a user. +RevokeStatement statement3 = + StatementBuilder.revoke(Privilege.SELECT).onNamespace("ns").fromUser("user1").build(); + +// Revoke all privileges and GRANT OPTION on a table from a user. +RevokeStatement statement4 = + StatementBuilder.revoke(Privilege.values()) + .onTable("ns", "tbl") + .fromUser("user1") + .build(); + +// Revoke all privileges and GRANT OPTION on all tables in a namespace from a user. +RevokeStatement statement5 = + StatementBuilder.revoke(Privilege.values()) + .onNamespace("ns") + .fromUser("user1") + .build(); +``` + +### CREATE ABAC_POLICY + +`CREATE ABAC_POLICY` コマンドは、指定されたポリシー名とデータタグ列名を使用して新しい ABAC ポリシーを作成します。新しく追加されたポリシーはデフォルトで有効になります。 + +#### 文法 + +```sql +CREATE ABAC_POLICY [WITH [DATA_TAG_COLUMN] ]; +``` + +- データタグ列名を指定しない場合、デフォルトのデータタグ列名は `_data_tag` になります。 + +#### 例 + +`CREATE ABAC_POLICY` の例は次のとおりです。 + +```sql +-- Create an ABAC policy with the default data tag column name. +CREATE ABAC_POLICY policy1; + +-- Create an ABAC policy with a custom data tag column name. +CREATE ABAC_POLICY policy2 WITH DATA_TAG_COLUMN data_tag; +``` + +`CREATE ABAC_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create an ABAC policy with the default data tag column name. +CreateAbacPolicyStatement statement1 = StatementBuilder.createAbacPolicy("policy1").build(); + +// Create an ABAC policy with a custom data tag column name. +CreateAbacPolicyStatement statement2 = + StatementBuilder.createAbacPolicy("policy1") + .withDataTagColumn("data_tag") + .build(); +``` + +### ENABLE ABAC_POLICY + +`ENABLE ABAC_POLICY` コマンドは、指定された ABAC ポリシーを有効にします。 + +#### 文法 + +```sql +ENABLE ABAC_POLICY ; +``` + +#### 例 + +`ENABLE ABAC_POLICY` の例は次のとおりです。 + +```sql +-- Enable an ABAC policy. +ENABLE ABAC_POLICY policy1; +``` + +`ENABLE ABAC_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Enable an ABAC policy. +EnableAbacPolicyStatement statement = StatementBuilder.enableAbacPolicy("policy1").build(); +``` + +### DISABLE ABAC_POLICY + +`DISABLE ABAC_POLICY` コマンドは、指定された ABAC ポリシーを無効にします。このコマンドは、指定されたポリシーに関連付けられたすべての名前空間およびテーブルの ABAC 機能を実質的に無効にします。 + +#### 文法 + +```sql +DISABLE ABAC_POLICY ; +``` + +#### 例 + +`DISABLE ABAC_POLICY` の例は次のとおりです。 + +```sql +-- Disable an ABAC policy. +DISABLE ABAC_POLICY policy1; +``` + +`DISABLE ABAC_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Disable an ABAC policy. +DisableAbacPolicyStatement statement = StatementBuilder.disableAbacPolicy("policy1").build(); +``` + +### CREATE ABAC_LEVEL + +`CREATE ABAC_LEVEL` コマンドは、指定されたポリシー内で指定されたレベルの短縮名、長い名前、およびレベル番号を使用して新しい ABAC レベルを作成します。 + +#### 文法 + +```sql +CREATE ABAC_LEVEL WITH [LONG_NAME] AND [LEVEL_NUMBER] IN [POLICY] ; +``` + +#### 例 + +`CREATE ABAC_LEVEL` の例は次のとおりです。 + +```sql +-- Create an ABAC level. +CREATE ABAC_LEVEL l1 WITH LONG_NAME level1 AND LEVEL_NUMBER 10 IN POLICY policy1; +``` + +`CREATE ABAC_LEVEL` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create an ABAC level. +CreateAbacLevelStatement statement = + StatementBuilder.createAbacLevel("l1") + .withLongName("level1") + .andLevelNumber(10) + .inPolicy("policy1") + .build(); +``` + +### DROP ABAC_LEVEL + +`DROP ABAC_LEVEL` コマンドは、指定されたポリシー内の指定された ABAC レベルを削除します。 + +#### 文法 + +```sql +DROP ABAC_LEVEL IN [POLICY] ; +``` + +#### 例 + +`DROP ABAC_LEVEL` の例は次のとおりです。 + +```sql +-- Drop an ABAC level. +DROP ABAC_LEVEL l1 IN POLICY policy1; +``` + +`DROP ABAC_LEVEL` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Drop an ABAC level. +DropAbacLevelStatement statement = + StatementBuilder.dropAbacLevel("l1").inPolicy("policy1").build(); +``` + +### CREATE ABAC_COMPARTMENT + +`CREATE ABAC_COMPARTMENT` コマンドは、指定されたポリシー内で指定されたコンパートメントの短縮名と長い名前を使用して新しい ABAC コンパートメントを作成します。 + +#### 文法 + +```sql +CREATE ABAC_COMPARTMENT WITH [LONG_NAME] IN [POLICY] ; +``` + +#### 例 + +`CREATE ABAC_COMPARTMENT` の例は次のとおりです。 + +```sql +-- Create an ABAC compartment. +CREATE ABAC_COMPARTMENT c1 WITH LONG_NAME compartment1 IN POLICY policy1; +``` + +`CREATE ABAC_COMPARTMENT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create an ABAC compartment. +CreateAbacCompartmentStatement statement = + StatementBuilder.createAbacCompartment("c1") + .withLongName("compartment1") + .inPolicy("policy1") + .build(); +``` + +### DROP ABAC_COMPARTMENT + +`DROP ABAC_COMPARTMENT` コマンドは、指定されたポリシー内の指定された ABAC コンパートメントを削除します。 + +#### 文法 + +```sql +DROP ABAC_COMPARTMENT IN [POLICY] ; +``` + +#### 例 + +`DROP ABAC_COMPARTMENT` の例は次のとおりです。 + +```sql +-- Drop an ABAC compartment. +DROP ABAC_COMPARTMENT c1 IN POLICY policy1; +``` + +`DROP ABAC_COMPARTMENT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Drop an ABAC compartment. +DropAbacCompartmentStatement statement = + StatementBuilder.dropAbacCompartment("c1").inPolicy("policy1").build(); +``` + +### CREATE ABAC_GROUP + +`CREATE ABAC_GROUP` コマンドは、指定されたポリシー内で指定された短縮名、長い名前、およびオプションで親グループを使用して新しい ABAC グループを作成します。 + +#### 文法 + +```sql +CREATE ABAC_GROUP WITH [LONG_NAME] [AND [PARENT_GROUP] ] IN [POLICY] ; +``` + +#### 例 + +`CREATE ABAC_GROUP` の例は次のとおりです。 + +```sql +-- Create an ABAC group with a parent group. +CREATE ABAC_GROUP g1 WITH LONG_NAME group1 AND PARENT_GROUP g0 IN POLICY policy1; + +-- Create an ABAC group without a parent group. +CREATE ABAC_GROUP g2 WITH LONG_NAME group2 IN POLICY policy1; +``` + +`CREATE ABAC_GROUP` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create an ABAC group with a parent group. +CreateAbacGroupStatement statement1 = + StatementBuilder.createAbacGroup("g1") + .withLongName("group1") + .andParentGroup("g0") + .inPolicy("policy1") + .build(); + +// Create an ABAC group without a parent group. +CreateAbacGroupStatement statement2 = + StatementBuilder.createAbacGroup("g2").withLongName("group2").inPolicy("policy1").build(); +``` + +### DROP ABAC_GROUP + +`DROP ABAC_GROUP` コマンドは、指定されたポリシー内の指定された ABAC グループを削除します。 + +#### 文法 + +```sql +DROP ABAC_GROUP IN [POLICY] ; +``` + +#### 例 + +`DROP ABAC_GROUP` の例は次のとおりです。 + +```sql +-- Drop an ABAC group. +DROP ABAC_GROUP g1 IN POLICY policy1; +``` + +`DROP ABAC_GROUP` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Drop an ABAC group. +DropAbacGroupStatement statement = + StatementBuilder.dropAbacGroup("g1").inPolicy("policy1").build(); +``` + +### SET ABAC_LEVEL + +`SET ABAC_LEVEL` コマンドは、指定されたポリシー内の指定されたユーザーに対して指定された ABAC レベルを設定します。 + +#### 文法 + +```sql +SET ABAC_LEVEL [AND [DEFAULT_LEVEL] ] [AND [ROW_LEVEL] ] FOR [USER] IN [POLICY] ; +``` + +- デフォルトレベルを省略すると、`` で指定されたレベルがデフォルトレベルとして使用されます。 +- 行レベルを省略すると、デフォルトレベルが行レベルとして使用されます。 + +#### 例 + +`SET ABAC_LEVEL` の例は次のとおりです。 + +```sql +-- Set the levels for a user. +SET ABAC_LEVEL l1 AND DEFAULT_LEVEL l2 AND ROW_LEVEL l3 FOR USER user1 IN POLICY policy1; + +-- Set the levels for a user without a row level. +SET ABAC_LEVEL l1 AND DEFAULT_LEVEL l2 FOR USER user1 IN POLICY policy1; + +-- Set the levels for a user without a default level and a row level. +SET ABAC_LEVEL l1 FOR USER user1 IN POLICY policy1; +``` + +`SET ABAC_LEVEL` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Set the levels for a user. +SetAbacLevelsForUserStatement statement1 = + StatementBuilder.setAbacLevel("l1") + .andDefaultLevel("l2") + .andRowLevel("l3") + .forUser("user1") + .inPolicy("policy1") + .build(); + +// Set the levels for a user without a row level. +SetAbacLevelsForUserStatement statement2 = + StatementBuilder.setAbacLevel("l1") + .andDefaultLevel("l2") + .forUser("user1") + .inPolicy("policy1") + .build(); + +// Set the levels for a user without a default level and a row level. +SetAbacLevelsForUserStatement statement3 = + StatementBuilder.setAbacLevel("l1").forUser("user1").inPolicy("policy1").build(); +``` + +### ADD ABAC_COMPARTMENT + +`ADD ABAC_COMPARTMENT` コマンドは、指定されたポリシー内の指定されたユーザーに指定された ABAC コンパートメントを追加します。 + +#### 文法 + +```sql +ADD ABAC_COMPARTMENT TO [USER] [WITH {accessMode [AND default] [AND row] | default [AND row] | row}] IN [POLICY] ; + +accessMode: READ_ONLY_ACCESS | READ_WRITE_ACCESS +default: DEFAULT [= {TRUE | FALSE}] +row: ROW [= {TRUE | FALSE}] +``` + +- アクセスモードを省略すると、デフォルトのアクセスモードは `READ_ONLY_ACCESS` になります。 +- デフォルト部分を省略すると、コンパートメントはデフォルトのコンパートメントに含まれます。 +- 行部分を省略すると、コンパートメントは行コンパートメントに含まれません。 +- `default` または `row` のブーリアンリテラルを省略すると、`default` または `row` の値は `TRUE` に設定されます。 + +#### 例 + +`ADD ABAC_COMPARTMENT` の例は次のとおりです。 + +```sql +-- Add a compartment to a user without specifying the access mode, default, and row. +ADD ABAC_COMPARTMENT c1 TO USER user1 IN POLICY policy1; + +-- Add a compartment to a user with the READ_WRITE_ACCESS access mode. +ADD ABAC_COMPARTMENT c1 TO USER user1 WITH READ_WRITE_ACCESS IN POLICY policy1; + +-- Add a compartment to a user with specifying the default. +ADD ABAC_COMPARTMENT c1 TO USER user1 WITH DEFAULT IN POLICY policy1; + +-- Add a compartment to a user with specifying the row to TRUE. +ADD ABAC_COMPARTMENT c1 TO USER user1 WITH ROW = TRUE IN POLICY policy1; +``` + +`ADD ABAC_COMPARTMENT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Add a compartment to a user without specifying the access mode, default, and row. +AddAbacCompartmentToUserStatement statement1 = + StatementBuilder.addAbacCompartment("c1").toUser("user1").inPolicy("policy1").build(); + +// Add a compartment to a user with the READ_WRITE_ACCESS access mode. +AddAbacCompartmentToUserStatement statement2 = + StatementBuilder.addAbacCompartment("c1") + .toUser("user1") + .withReadWriteAccess() + .inPolicy("policy1") + .build(); + +// Add a compartment to a user with specifying the default. +AddAbacCompartmentToUserStatement statement3 = + StatementBuilder.addAbacCompartment("c1") + .toUser("user1") + .withDefault() + .inPolicy("policy1") + .build(); + +// Add a compartment to a user with specifying the row to TRUE. +AddAbacCompartmentToUserStatement statement4 = + StatementBuilder.addAbacCompartment("c1") + .toUser("user1") + .withRow(true) + .inPolicy("policy1") + .build(); +``` + +### REMOVE ABAC_COMPARTMENT + +`REMOVE ABAC_COMPARTMENT` コマンドは、指定されたポリシー内の指定されたユーザーから指定されたコンパートメントを削除します。 + +#### 文法 + +```sql +REMOVE ABAC_COMPARTMENT FROM [USER] IN [POLICY] ; +``` + +#### 例 + +`REMOVE ABAC_COMPARTMENT` の例は次のとおりです。 + +```sql +-- Remove a compartment from a user. +REMOVE ABAC_COMPARTMENT c1 FROM USER user1 IN POLICY policy1; +``` + +`REMOVE ABAC_COMPARTMENT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Remove a compartment from a user. +RemoveAbacCompartmentFromUserStatement statement = + StatementBuilder.removeAbacCompartment("c1").fromUser("user1").inPolicy("policy1").build(); +``` + +### ADD ABAC_GROUP + +`ADD ABAC_GROUP` コマンドは、指定されたポリシー内の指定されたユーザーに指定された ABAC グループを追加します。 + +#### 文法 + +```sql +ADD ABAC_GROUP TO [USER] [WITH {accessMode [AND default] [AND row] | default [AND row] | row}] IN [POLICY] ; + +accessMode: READ_ONLY_ACCESS | READ_WRITE_ACCESS +default: DEFAULT [= {TRUE | FALSE}] +row: ROW [= {TRUE | FALSE}] +``` + +- アクセスモードを省略すると、デフォルトのアクセスモードは `READ_ONLY_ACCESS` になります。 +- デフォルト部分を省略すると、グループはデフォルトのコンパートメントに含まれます。 +- 行部分を省略すると、グループは行コンパートメントに含まれません。 +- `default` または `row` のブーリアンリテラルを省略すると、`default` または `row` の値は `TRUE` に設定されます。 + +#### 例 + +`ADD ABAC_GROUP` の例は次のとおりです。 + +```sql +-- Add a group to a user without specifying the access mode, default, and row. +ADD ABAC_GROUP g1 TO USER user1 IN POLICY policy1; + +-- Add a group to a user with the READ_WRITE_ACCESS access mode. +ADD ABAC_GROUP g1 TO USER user1 WITH READ_WRITE_ACCESS IN POLICY policy1; + +-- Add a group to a user with specifying the default. +ADD ABAC_GROUP g1 TO USER user1 WITH DEFAULT IN POLICY policy1; + +-- Add a group to a user with specifying the row to TRUE. +ADD ABAC_GROUP g1 TO USER user1 WITH ROW = TRUE IN POLICY policy1; +``` + +`ADD ABAC_GROUP` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Add a group to a user without specifying the access mode, default, and row. +AddAbacGroupToUserStatement statement1 = + StatementBuilder.addAbacGroup("g1").toUser("user1").inPolicy("policy1").build(); + +// Add a group to a user with the READ_WRITE_ACCESS access mode. +AddAbacGroupToUserStatement statement2 = + StatementBuilder.addAbacGroup("g1") + .toUser("user1") + .withReadWriteAccess() + .inPolicy("policy1") + .build(); + +// Add a group to a user with specifying the default. +AddAbacGroupToUserStatement statement3 = + StatementBuilder.addAbacGroup("g1") + .toUser("user1") + .withDefault() + .inPolicy("policy1") + .build(); + +// Add a group to a user with specifying the row to TRUE. +AddAbacGroupToUserStatement statement4 = + StatementBuilder.addAbacGroup("g1") + .toUser("user1") + .withRow(true) + .inPolicy("policy1") + .build(); +``` + +### REMOVE ABAC_GROUP + +`REMOVE ABAC_GROUP` コマンドは、指定されたポリシー内の指定されたユーザーから指定された ABAC グループを削除します。 + +#### 文法 + +```sql +REMOVE ABAC_GROUP FROM [USER] IN [POLICY] ; +``` + +#### 例 + +`REMOVE ABAC_GROUP` の例は次のとおりです。 + +```sql +-- Remove a group from a user. +REMOVE ABAC_GROUP g1 FROM USER user1 IN POLICY policy1; +``` + +`REMOVE ABAC_GROUP` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Remove a group from a user. +RemoveAbacGroupFromUserStatement statement = + StatementBuilder.removeAbacGroup("g1").fromUser("user1").inPolicy("policy1").build(); +``` + +### DROP ABAC_USER_TAG_INFO + +`DROP ABAC_USER_TAG_INFO` コマンドは、指定されたポリシー内の指定されたユーザーから指定された ABAC ユーザータグ情報を削除します。 + +#### 文法 + +```sql +DROP ABAC_USER_TAG_INFO FROM [USER] IN [POLICY] ; +``` + +#### 例 + +`DROP ABAC_USER_TAG_INFO` の例は次のとおりです。 + +```sql +-- Drop user tag information from a user. +DROP ABAC_USER_TAG_INFO FROM USER user1 IN POLICY policy1; +``` + +`DROP ABAC_USER_TAG_INFO` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Drop user tag information from a user. +DropAbacUserTagInfoFromUserStatement statement = + StatementBuilder.dropAbacUserTagInfoFromUser("user1").inPolicy("policy1").build(); +``` + +### CREATE ABAC_NAMESPACE_POLICY + +`CREATE ABAC_NAMESPACE_POLICY` コマンドは、指定されたポリシーと名前空間を使用して、指定された名前空間ポリシー名で新しい ABAC 名前空間ポリシーを作成します。このコマンドは、ポリシーを指定された名前空間に適用するために使用されます。新しく追加された名前空間ポリシーはデフォルトで有効になります。 + +#### 文法 + +```sql +CREATE ABAC_NAMESPACE_POLICY USING [POLICY] AND [NAMESPACE] ; +``` + +#### 例 + +`CREATE ABAC_NAMESPACE_POLICY` の例は次のとおりです。 + +```sql +-- Create an ABAC namespace policy. +CREATE ABAC_NAMESPACE_POLICY ns_policy1 USING POLICY policy1 AND NAMESPACE ns; +``` + +`CREATE ABAC_NAMESPACE_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create an ABAC namespace policy. +CreateAbacNamespacePolicyStatement statement = + StatementBuilder.createAbacNamespacePolicy("ns_policy1") + .usingPolicy("policy1") + .andNamespace("ns") + .build(); +``` + +### ENABLE ABAC_NAMESPACE_POLICY + +`ENABLE ABAC_NAMESPACE_POLICY` コマンドは、指定された ABAC 名前空間ポリシーを有効にします。 + +#### 文法 + +```sql +ENABLE ABAC_NAMESPACE_POLICY ; +``` + +#### 例 + +`ENABLE ABAC_NAMESPACE_POLICY` の例は次のとおりです。 + +```sql +-- Enable an ABAC namespace policy. +ENABLE ABAC_NAMESPACE_POLICY ns_policy1; +``` + +`ENABLE ABAC_NAMESPACE_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Enable an ABAC namespace policy. +EnableAbacNamespacePolicyStatement statement = + StatementBuilder.enableAbacNamespacePolicy("ns_policy1").build(); +``` + +### DISABLE ABAC_NAMESPACE_POLICY + +`DISABLE ABAC_NAMESPACE_POLICY` コマンドは、指定された ABAC 名前空間ポリシーを無効にします。このコマンドは、指定された名前空間ポリシーに関連付けられた名前空間の ABAC 機能を実質的に無効にします。 + +#### 文法 + +```sql +DISABLE ABAC_NAMESPACE_POLICY ; +``` + +#### 例 + +`DISABLE ABAC_NAMESPACE_POLICY` の例は次のとおりです。 + +```sql +-- Disable an ABAC namespace policy. +DISABLE ABAC_NAMESPACE_POLICY ns_policy1; +``` + +`DISABLE ABAC_NAMESPACE_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Disable an ABAC namespace policy. +DisableAbacNamespacePolicyStatement statement = + StatementBuilder.disableAbacNamespacePolicy("ns_policy1").build(); +``` + +### CREATE ABAC_TABLE_POLICY + +`CREATE ABAC_TABLE_POLICY` コマンドは、指定されたポリシーとテーブルを使用して、指定されたテーブルポリシー名で新しい ABAC テーブルポリシーを作成します。このコマンドは、ポリシーを指定されたテーブルに適用するために使用されます。新しく追加されたテーブルポリシーはデフォルトで有効になります。 + +#### 文法 + +```sql +CREATE ABAC_TABLE_POLICY USING [POLICY] AND [TABLE] .; +``` + +#### 例 + +`CREATE ABAC_TABLE_POLICY` の例は次のとおりです。 + +```sql +-- Create an ABAC table policy. +CREATE ABAC_TABLE_POLICY tbl_policy1 USING POLICY policy1 AND TABLE ns.tbl; +``` + +`CREATE ABAC_TABLE_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Create an ABAC table policy. +CreateAbacTablePolicyStatement statement = + StatementBuilder.createAbacTablePolicy("tbl_policy1") + .usingPolicy("policy1") + .andTable("ns", "tbl") + .build(); +``` + +### ENABLE ABAC_TABLE_POLICY + +`ENABLE ABAC_TABLE_POLICY` コマンドは、指定された ABAC テーブルポリシーを有効にします。 + +#### 文法 + +```sql +ENABLE ABAC_TABLE_POLICY ; +``` + +#### 例 + +`ENABLE ABAC_TABLE_POLICY` の例は次のとおりです。 + +```sql +-- Enable an ABAC table policy. +ENABLE ABAC_TABLE_POLICY tbl_policy1; +``` + +`ENABLE ABAC_TABLE_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Enable an ABAC table policy. +EnableAbacTablePolicyStatement statement = + StatementBuilder.enableAbacTablePolicy("tbl_policy1").build(); +``` + +### DISABLE ABAC_TABLE_POLICY + +`DISABLE ABAC_TABLE_POLICY` コマンドは、指定された ABAC テーブルポリシーを無効にします。このコマンドは、指定されたテーブルポリシーに関連付けられたテーブルの ABAC 機能を実質的に無効にします。 + +#### 文法 + +```sql +DISABLE ABAC_TABLE_POLICY ; +``` + +#### 例 + +`DISABLE ABAC_TABLE_POLICY` の例は次のとおりです。 + +```sql +-- Disable an ABAC table policy. +DISABLE ABAC_TABLE_POLICY tbl_policy1; +``` + +`DISABLE ABAC_TABLE_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Disable an ABAC table policy. +DisableAbacTablePolicyStatement statement = + StatementBuilder.disableAbacTablePolicy("tbl_policy1").build(); +``` + +## その他 + +### USE + +`USE` コマンドはデフォルトの名前空間を指定します。SQL で名前空間名が省略されている場合は、デフォルトの名前空間が使用されます。 + +#### 文法 + +```sql +USE +``` + +#### 例 + +`USE` の例は次のとおりです。 + +```sql +-- Specify a default namespace name "ns" +USE ns; +``` + +`USE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Specify a default namespace name "ns" +UseStatement statement = StatementBuilder.use("ns").build(); +``` + +### BEGIN + +`BEGIN` コマンドはトランザクションを開始します。 + +このコマンドは次の列を返します: + +- `transactionId`: `TEXT` - 開始したトランザクションに関連付けられたトランザクション ID + +#### 文法 + +```sql +BEGIN +``` + +#### 例 + +`BEGIN` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Begin a transaction +BeginStatement statement = StatementBuilder.begin().build(); +``` + +### START TRANSACTION + +`START TRANSACTION` コマンドはトランザクションを開始します。このコマンドは `BEGIN` の別名です。 + +このコマンドは次の列を返します: + +- `transactionId`: `TEXT` - 開始したトランザクションに関連付けられたトランザクション ID + +#### 文法 + +```sql +START TRANSACTION +``` + +#### 例 + +`START TRANSACTION` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Start a transaction. +StartTransactionStatement statement = StatementBuilder.startTransaction().build(); +``` + +### JOIN + +`JOIN` コマンドは、指定されたトランザクション ID に関連付けられたトランザクションを結合します。 + +#### 文法 + +```sql +JOIN +``` + +#### 例 + +`JOIN` の例は次のとおりです。 + +```sql +-- Join a transaction +JOIN 'id'; +``` + +`JOIN` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Join a transaction +JoinStatement statement = StatementBuilder.join("id").build(); +``` + +### PREPARE + +`PREPARE` コマンドは現在のトランザクションを準備します。 + +#### 文法 + +```sql +PREPARE +``` + +#### 例 + +`PREPARE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Prepare the current transaction +PrepareStatement statement = StatementBuilder.prepare().build(); +``` + +### VALIDATE + +`VALIDATE` コマンドは現在のトランザクションを検証します。 + +#### 文法 + +```sql +VALIDATE +``` + +#### 例 + +`VALIDATE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Validate the current transaction +ValidateStatement statement = StatementBuilder.validate().build(); +``` + +### COMMIT + +`COMMIT` コマンドは現在のトランザクションをコミットします。 + +#### 文法 + +```sql +COMMIT +``` + +#### 例 + +`COMMIT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Commit the current transaction +CommitStatement statement = StatementBuilder.commit().build(); +``` + +### ROLLBACK + +`ROLLBACK` コマンドは現在のトランザクションをロールバックします。 + +#### 文法 + +```sql +ROLLBACK +``` + +#### 例 + +`ROLLBACK` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Rollback the current transaction +RollbackStatement statement = StatementBuilder.rollback().build(); +``` + +### ABORT + +`ABORT` コマンドは現在のトランザクションをロールバックします。このコマンドは `ROLLBACK` の別名です。 + +#### 文法 + +```sql +ABORT +``` + +#### 例 + +`ABORT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Abort the current transaction. +AbortStatement statement = StatementBuilder.abort().build(); +``` + +### SET MODE + +`SET MODE` コマンドは、現在のトランザクションモードを切り替えます。 + +#### 文法 + +```sql +SET MODE transaction_mode + +transaction_mode: TRANSACTION | TWO_PHASE_COMMIT_TRANSACTION +``` + +#### 例 + +`SET MODE` の例は次のとおりです。 + +```sql +-- Switch the current transaction mode to Two-phase Commit Transaction +SET MODE TWO_PHASE_COMMIT_TRANSACTION; +``` + +`SET MODE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Switch the current transaction mode to Two-phase Commit Transaction +SetModeStatement statement = + StatementBuilder.setMode(TransactionMode.TWO_PHASE_COMMIT_TRANSACTION).build(); +``` + +### SHOW NAMESPACES + +`SHOW NAMESPACES` コマンドは名前空間名を表示します。 + +このコマンドは次の列を返します: + +- `namespaceName`: `TEXT` - 名前空間名 + +#### 文法 + +```sql +SHOW NAMESPACES +``` + +#### 例 + +`SHOW NAMESPACES` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show namespace names. +ShowNamespacesStatement statement = StatementBuilder.showNamespaces().build(); +``` + +### SHOW TABLES + +`SHOW TABLES` コマンドは、名前空間内のテーブル名を表示します。名前空間名を省略すると、デフォルトの名前空間が使用されます。 + +このコマンドは次の列を返します: + +- `tableName`: `TEXT` - テーブル名 + +#### 文法 + +```sql +SHOW TABLES [FROM ] +``` + +#### 例 + +`SHOW TABLES` の例は次のとおりです。 + +```sql +-- Show table names in the default namespace +SHOW TABLES; + +-- Show table names in a namespace "ns" +SHOW TABLES FROM ns; +``` + +`SHOW TABLES` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show table names in the default namespace +ShowTablesStatement statement1 = StatementBuilder.showTables().build(); + +// Show table names in a namespace "ns" +ShowTablesStatement statement2 = StatementBuilder.showTables().from("ns").build(); +``` + +### DESCRIBE + +`DESCRIBE` コマンドは、指定されたテーブルの列メタデータを返します。 + +このコマンドは次の列を返します: + +- `columnName`: `TEXT` - テーブル名 +- `type`: `TEXT` - タイプ名 +- `isPrimaryKey`: `BOOLEAN` - 主キーに含まれるかどうか +- `isPartitionKey`: `BOOLEAN` - パーティションキーの列部分であるかどうか +- `isClusteringKey`: `BOOLEAN` - クラスタリングキーの列部分であるかどうか +- `clusteringOrder`: `TEXT` - クラスタリング順序 +- `isIndexed`: `BOOLEAN` - インデックス付き列であるかどうか + +#### 文法 + +```sql +DESCRIBE [.]
+ +DESC [.]
+``` + +#### 例 + +`DESCRIBE` の例は次のとおりです。 + +```sql +-- Returns column metadata for "ns.tbl" +DESCRIBE ns.tbl; + +-- Returns column metadata for "tbl" +DESC tbl; +``` + +`DESCRIBE` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Returns column metadata for "ns.tbl" +DescribeStatement statement1 = StatementBuilder.describe("ns", "tbl").build(); + +// Returns column metadata for "tbl" +DescribeStatement statement2 = StatementBuilder.describe("tbl").build(); +``` + +### SUSPEND + +`SUSPEND` コマンドは、現在のセッションで進行中のトランザクションを一時停止します。 + +#### 文法 + +```sql +SUSPEND +``` + +#### 例 + +`SUSPEND` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Suspend the ongonig transaction in the current session +SuspendStatement statement = StatementBuilder.suspend().build(); +``` + +### RESUME + +`RESUME` コマンドは、現在のセッションで指定されたトランザクション ID に関連付けられたトランザクションを再開します。 + +#### 文法 + +```sql +RESUME +``` + +#### 例 + +`RESUME` の例は次のとおりです。 + +```sql +-- Resume a transaction +RESUME 'id'; +``` + +`RESUME` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Resume a transaction +ResumeStatement statement = StatementBuilder.resume("id").build(); +``` + +### SHOW USERS + +`SHOW USERS` コマンドは、ユーザー名とユーザー属性を表示します。スーパーユーザーの場合は、すべてのユーザーを表示できます。通常のユーザーの場合は、自分のユーザー名と属性のみを表示できます。 + +このコマンドは次の列を返します: + +- `username`: `TEXT` - ユーザー名 +- `isSuperuser`: `BOOLEAN` - ユーザーがスーパーユーザーであるかどうか + +#### 文法 + +```sql +SHOW USERS +``` + +#### 例 + +`SHOW USERS` の例は次のとおりです。 + +```sql +-- Show usernames and user attributes +SHOW USERS; +``` + +`SHOW USERS` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show usernames and user attributes +ShowUsersStatement statement = StatementBuilder.showUsers().build(); +``` + +### SHOW GRANTS + +`SHOW GRANTS` コマンドは、現在のユーザーまたは指定されたユーザーに付与された権限を表示します。 + +このコマンドは次の列を返します: + +- `name`: `TEXT` - タイプに応じて名前空間名またはテーブル名 +- `type`: `TEXT` - オブジェクトのタイプ (`NAMESPACE` または `TABLE`) +- `privilege`: `TEXT` - 権限 + +#### 文法 + +```sql +-- Show privileges granted to the current user +SHOW GRANTS + +-- Show privileges granted to the specified user +SHOW GRANTS FOR [USER] +``` + +#### 例 + +`SHOW GRANTS` の例は次のとおりです。 + +```sql +-- Show privileges granted to the current user +SHOW GRANTS; + +-- Show privileges granted to user1 +SHOW GRANTS FOR user1; +``` + +`SHOW GRANTS` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show privileges granted to the current user +ShowGrantsStatement statement1 = StatementBuilder.showGrants().build(); + +// Show privileges granted to user1 +ShowGrantsStatement statement2 = StatementBuilder.showGrants().forUser("user1").build(); +``` + +### SHOW ABAC_POLICY + +`SHOW ABAC_POLICY` コマンドは、指定された ABAC ポリシーを表示します。 + +このコマンドは次の列を返します: + +- `name`: `TEXT` - ポリシー名 +- `dataTagColumnName`: `TEXT` - データタグ列名 +- `state`: `TEXT` - ポリシーの状態 (`ENABLED` または `DISABLED`) + +#### 文法 + +```sql +SHOW ABAC_POLICY ; +``` + +#### 例 + +`SHOW ABAC_POLICY` の例は次のとおりです。 + +```sql +-- Show the specified ABAC policy +SHOW ABAC_POLICY policy1; +``` + +`SHOW ABAC_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show the specified ABAC policy +ShowAbacPolicyStatement statement = StatementBuilder.showAbacPolicy("policy1").build(); +``` + +### SHOW ABAC_POLICIES + +`SHOW ABAC_POLICIES` コマンドは、すべての ABAC ポリシーを表示します。 + +このコマンドは次の列を返します: + +- `name`: `TEXT` - ポリシー名 +- `dataTagColumnName`: `TEXT` - データタグ列名 +- `state`: `TEXT` - ポリシーの状態 (`ENABLED` または `DISABLED`) + +#### 文法 + +```sql +SHOW ABAC_POLICIES; +``` + +#### 例 + +`SHOW ABAC_POLICIES` の例は次のとおりです。 + +```sql +-- Show all ABAC policies +SHOW ABAC_POLICIES; +``` + +`SHOW ABAC_POLICIES` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show all ABAC policies +ShowAbacPoliciesStatement statement = StatementBuilder.showAbacPolicies().build(); +``` + +### SHOW ABAC_LEVEL + +`SHOW ABAC_LEVEL` コマンドは、指定されたポリシー内の指定された ABAC レベルを表示します。 + +このコマンドは次の列を返します: + +- `policyName`: `TEXT` - ポリシー名 +- `shortName`: `TEXT` - レベルの短縮名 +- `longName`: `TEXT` - レベルの長い名前 +- `levelNumber`: `INTEGER` - レベルのレベル番号 + +#### 文法 + +```sql +SHOW ABAC_LEVEL IN [POLICY] ; +``` + +#### 例 + +`SHOW ABAC_LEVEL` の例は次のとおりです。 + +```sql +-- Show the specified ABAC level in the specified policy +SHOW ABAC_LEVEL l1 IN POLICY policy1; +``` + +`SHOW ABAC_LEVEL` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show the specified ABAC level in the specified policy +ShowAbacLevelStatement statement = StatementBuilder.showAbacLevel("l1").inPolicy("policy1").build(); +``` + +### SHOW ABAC_LEVELS + +`SHOW ABAC_LEVELS` コマンドは、指定されたポリシー内のすべての ABAC レベルを表示します。 + +このコマンドは次の列を返します: + +- `policyName`: `TEXT` - ポリシー名 +- `shortName`: `TEXT` - レベルの短縮名 +- `longName`: `TEXT` - レベルの長い名前 +- `levelNumber`: `INTEGER` - レベルのレベル番号 + +#### 文法 + +```sql +SHOW ABAC_LEVELS IN [POLICY] ; +``` + +#### 例 + +`SHOW ABAC_LEVELS` の例は次のとおりです。 + +```sql +-- Show all ABAC levels in the specified policy +SHOW ABAC_LEVELS IN POLICY policy1; +``` + +`SHOW ABAC_LEVELS` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show all ABAC levels in the specified policy +ShowAbacLevelsStatement statement = StatementBuilder.showAbacLevelsInPolicy("policy1").build(); +``` + +### SHOW ABAC_COMPARTMENT + +`SHOW ABAC_COMPARTMENT` コマンドは、指定されたポリシー内の指定された ABAC コンパートメントを表示します。 + +このコマンドは次の列を返します: + +- `policyName`: `TEXT` - ポリシー名 +- `shortName`: `TEXT` - コンパートメントの短縮名 +- `longName`: `TEXT` - コンパートメントの長い名前 + +#### 文法 + +```sql +SHOW ABAC_COMPARTMENT IN [POLICY] ; +``` + +#### 例 + +`SHOW ABAC_COMPARTMENT` の例は次のとおりです。 + +```sql +-- Show the specified ABAC compartment in the specified policy +SHOW ABAC_COMPARTMENT c1 IN POLICY policy1; +``` + +`SHOW ABAC_COMPARTMENT` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show the specified ABAC compartment in the specified policy +ShowAbacCompartmentStatement statement = + StatementBuilder.showAbacCompartment("c1").inPolicy("policy1").build(); +``` + +### SHOW ABAC_COMPARTMENTS + +`SHOW ABAC_COMPARTMENTS` コマンドは、指定されたポリシー内のすべての ABAC コンパートメントを表示します。 + +このコマンドは次の列を返します: + +- `policyName`: `TEXT` - ポリシー名 +- `shortName`: `TEXT` - コンパートメントの短縮名 +- `longName`: `TEXT` - コンパートメントの長い名前 + +#### 文法 + +```sql +SHOW ABAC_COMPARTMENTS IN [POLICY] ; +``` + +#### 例 + +`SHOW ABAC_COMPARTMENTS` の例は次のとおりです。 + +```sql +-- Show all ABAC compartments in the specified policy +SHOW ABAC_COMPARTMENTS IN POLICY policy1; +``` + +`SHOW ABAC_COMPARTMENTS` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show all ABAC compartments in the specified policy +ShowAbacCompartmentsStatement statement = + StatementBuilder.showAbacCompartmentsInPolicy("policy1").build(); +``` + +### SHOW ABAC_GROUP + +`SHOW ABAC_GROUP` コマンドは、指定されたポリシー内の指定された ABAC グループを表示します。 + +このコマンドは次の列を返します: + +- `policyName`: `TEXT` - ポリシー名 +- `shortName`: `TEXT` - グループの短縮名 +- `longName`: `TEXT` - グループの長い名前 +- `parentGroupShortName`: `TEXT` - 親グループの短縮名。グループに親グループがない場合、この列は `null` になります。 + +#### 文法 + +```sql +SHOW ABAC_GROUP IN [POLICY] ; +``` + +#### 例 + +`SHOW ABAC_GROUP` の例は次のとおりです。 + +```sql +-- Show the specified ABAC group in the specified policy +SHOW ABAC_GROUP g1 IN POLICY policy1; +``` + +`SHOW ABAC_GROUP` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show the specified ABAC group in the specified policy +ShowAbacGroupStatement statement = + StatementBuilder.showAbacGroup("g1").inPolicy("policy1").build(); +``` + +### SHOW ABAC_GROUPS + +`SHOW ABAC_GROUPS` コマンドは、指定されたポリシー内のすべての ABAC グループを表示します。 + +このコマンドは次の列を返します: + +- `policyName`: `TEXT` - ポリシー名 +- `shortName`: `TEXT` - グループの短縮名 +- `longName`: `TEXT` - グループの長い名前 +- `parentGroupShortName`: `TEXT` - 親グループの短縮名。グループに親グループがない場合、この列は `null` になります。 + +#### 文法 + +```sql +SHOW ABAC_GROUPS IN [POLICY] ; +``` + +#### 例 + +`SHOW ABAC_GROUPS` の例は次のとおりです。 + +```sql +-- Show all ABAC groups in the specified policy +SHOW ABAC_GROUPS IN POLICY policy1; +``` + +`SHOW ABAC_GROUPS` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show all ABAC groups in the specified policy +ShowAbacGroupsStatement statement = StatementBuilder.showAbacGroupsInPolicy("policy1").build(); +``` + +### SHOW ABAC_USER_TAG_INFO + +`SHOW ABAC_USER_TAG_INFO` コマンドは、指定されたポリシー内の指定されたユーザーの ABAC ユーザータグ情報を表示します。 + +このコマンドは次の列を返します: + +- `policyName`: `TEXT` - ポリシー名 +- `username`: `TEXT` - ユーザー名 +- `readTag`: `TEXT` - 読み取りタグ +- `writeTag`: `TEXT` - 書き込みタグ +- `defaultReadTag`: `TEXT` - デフォルトの読み取りタグ +- `defaultWriteTag`: `TEXT` - デフォルトの書き込みタグ +- `rowTag`: `TEXT` - 行タグ + +#### 文法 + +```sql +SHOW ABAC_USER_TAG_INFO [FOR USER ] IN [POLICY] ; +``` + +- ユーザーを省略すると、現在のユーザーのユーザータグ情報が表示されます。 + +#### 例 + +`SHOW ABAC_USER_TAG_INFO` の例は次のとおりです。 + +```sql +-- Show the ABAC user tag information for the current user in the specified policy +SHOW ABAC_USER_TAG_INFO IN POLICY policy1; + +-- Show the ABAC user tag information for user1 in the specified policy +SHOW ABAC_USER_TAG_INFO FOR USER user1 IN POLICY policy1; +``` + +`SHOW ABAC_USER_TAG_INFO` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show the ABAC user tag information for the current user in the specified policy +ShowAbacUserTagInfoStatement statement1 = + StatementBuilder.showAbacUserTagInfo().inPolicy("policy1").build(); + +// Show the ABAC user tag information for user1 in the specified policy +ShowAbacUserTagInfoStatement statement2 = + StatementBuilder.showAbacUserTagInfo().forUser("user1").inPolicy("policy1").build(); +``` + +### SHOW ABAC_NAMESPACE_POLICY + +`SHOW ABAC_NAMESPACE_POLICY` コマンドは、指定された ABAC 名前空間ポリシーを表示します。 + +このコマンドは次の列を返します: + +- `name`: `TEXT` - 名前空間ポリシーの名前 +- `policyName`: `TEXT` - ポリシー名 +- `namespaceName`: `TEXT` - 名前空間名 +- `state`: `TEXT` - ポリシーの状態 (`ENABLED` または `DISABLED`) + +#### 文法 + +```sql +SHOW ABAC_NAMESPACE_POLICY ; +``` + +#### 例 + +`SHOW ABAC_NAMESPACE_POLICY` の例は次のとおりです。 + +```sql +-- Show the specified ABAC namespace policy +SHOW ABAC_NAMESPACE_POLICY ns_policy1; +``` + +`SHOW ABAC_NAMESPACE_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show the specified ABAC namespace policy +ShowAbacNamespacePolicyStatement statement = + StatementBuilder.showAbacNamespacePolicy("ns_policy1").build(); +``` + +### SHOW ABAC_NAMESPACE_POLICIES + +`SHOW ABAC_NAMESPACE_POLICIES` コマンドは、すべての ABAC 名前空間ポリシーを表示します。 + +このコマンドは次の列を返します: + +- `name`: `TEXT` - 名前空間ポリシーの名前 +- `policyName`: `TEXT` - ポリシー名 +- `namespaceName`: `TEXT` - 名前空間名 +- `state`: `TEXT` - ポリシーの状態 (`ENABLED` または `DISABLED`) + +#### 文法 + +```sql +SHOW ABAC_NAMESPACE_POLICIES +``` + +#### 例 + +`SHOW ABAC_NAMESPACE_POLICIES` の例は次のとおりです。 + +```sql +-- Show all ABAC namespace policies +SHOW ABAC_NAMESPACE_POLICIES; +``` + +`SHOW ABAC_NAMESPACE_POLICIES` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show all ABAC namespace policies +ShowAbacNamespacePoliciesStatement statement = + StatementBuilder.showAbacNamespacePolicies().build(); +``` + +### SHOW ABAC_TABLE_POLICY + +`SHOW ABAC_TABLE_POLICY` コマンドは、指定された ABAC テーブルポリシーを表示します。 + +このコマンドは次の列を返します: + +- `name`: `TEXT` - テーブルポリシーの名前 +- `policyName`: `TEXT` - ポリシー名 +- `namespaceName`: `TEXT` - 名前空間名 +- `tableName`: `TEXT` - テーブル名 +- `state`: `TEXT` - ポリシーの状態 (`ENABLED` または `DISABLED`) + +#### 文法 + +```sql +SHOW ABAC_TABLE_POLICY ; +``` + +#### 例 + +`SHOW ABAC_TABLE_POLICY` の例は次のとおりです。 + +```sql +-- Show the specified ABAC table policy +SHOW ABAC_TABLE_POLICY tbl_policy1; +``` + +`SHOW ABAC_TABLE_POLICY` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show the specified ABAC table policy +ShowAbacTablePolicyStatement statement = + StatementBuilder.showAbacTablePolicy("tbl_policy1").build(); +``` + +### SHOW ABAC_TABLE_POLICIES + +`SHOW ABAC_TABLE_POLICIES` コマンドは、すべての ABAC テーブルポリシーを表示します。 + +このコマンドは次の列を返します: + +- `name`: `TEXT` - テーブルポリシーの名前 +- `policyName`: `TEXT` - ポリシー名 +- `namespaceName`: `TEXT` - 名前空間名 +- `tableName`: `TEXT` - テーブル名 +- `state`: `TEXT` - ポリシーの状態 (`ENABLED` または `DISABLED`) + +#### 文法 + +```sql +SHOW ABAC_TABLE_POLICIES; +``` + +#### 例 + +`SHOW ABAC_TABLE_POLICIES` の例は次のとおりです。 + +```sql +-- Show all ABAC table policies +SHOW ABAC_TABLE_POLICIES; +``` + +`SHOW ABAC_TABLE_POLICIES` のステートメントオブジェクトを構築する例は次のとおりです。 + +```java +// Show all ABAC table policies +ShowAbacTablePoliciesStatement statement = StatementBuilder.showAbacTablePolicies().build(); +``` + +## リテラル + +リテラルと列の値は同義であり、SQL ステートメントを記述するときに使用される固定データ値を参照します。たとえば、`1`、`'abc'`、`1.23`、および `'2024-05-19'` はリテラルです。 + +### テキスト + +テキストリテラルは、`'abc'` や `'abc def'` など、一重引用符 `'` で囲まれた文字のシーケンスです。 + +### 数値 + +数値リテラルには、正確な値 (INTEGER および BIGINT) と近似値 (FLOAT および DOUBLE) のリテラルが含まれます。 + +正確な値リテラルは、`123` や `-5` などの数字のシーケンスです。 + +近似値リテラルは、`4.754` や `-1.2` などの小数点付きの数字のシーケンスです。 + +### 日付と時刻 + +日付と時刻リテラルは、DATE、TIME、TIMESTAMP、および TIMESTAMPTZ 値を表す特定の形式に従うテキストリテラルです。 + +| ScalarDB データ型 | 形式 | 注記 | 例 | +|-----------------|---------------------------------------|-----------------------------------------|----------------------------------------------------------------------------------| +| DATE | **'YYYY-MM-DD'** | | `'2024-05-19'` | +| TIME | **'HH:MM:[SS[.FFFFFF]]'** | 秒と小数秒 (最大1マイクロ秒) はオプションです。 | `'12:34'`、`'12:34:56'`、`'12:34:56.789123'` | +| TIMESTAMP | **'YYYY-MM-DD HH:MM:[SS[.FFF]]'** | 秒と小数秒 (最大1ミリ秒) はオプションです。 | `'2024-05-19 12:34'`、`'2024-05-19 12:34:56'`、`'2024-05-19 12:34:56.789'` | +| TIMESTAMPTZ | **'YYYY-MM-DD HH:MM:[SS[.FFF]] Z'** | 秒と小数秒 (最大1ミリ秒) はオプションです。 | `'2024-05-19 12:34 Z'`、`'2024-05-19 12:34:56 Z'`、`'2024-05-19 12:34:56.789 Z'` | diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/images/spring_data_ingegration_overall_arch.png b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/images/spring_data_ingegration_overall_arch.png new file mode 100644 index 00000000..67b52a44 Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/images/spring_data_ingegration_overall_arch.png differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/index.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/index.mdx new file mode 100644 index 00000000..8f103dca --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/index.mdx @@ -0,0 +1,41 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB SQL 概要 + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB SQL は、クライアントアプリケーションが SQL を使用して ScalarDB Cluster と通信できるようにするインターフェースレイヤーです。 + +:::note + +ScalarDB SQL は標準 SQL と完全に互換性があるわけではありませんが、SQL 言語の大部分をサポートしています。 + +::: + +## SQL インターフェースの種類 + +ScalarDB SQL には3種類の SQL インターフェースがあります。 + +### JDBC + +JDBC インターフェースを使用すると、標準 JDBC API を使用して ScalarDB Cluster に接続できます。これは既に JDBC を使用しているアプリケーションに便利です。 + +JDBC インターフェースの設定と使用方法の詳細については、[ScalarDB JDBC ガイド](./jdbc-guide.mdx)を参照してください。 + +### SQL API + +SQL API を使用すると、独自のモダンな Java SQL API を介して ScalarDB Cluster に接続できます。これは、JDBC インターフェースに依存する必要のないアプリケーションに便利です。 + +SQL API の設定と使用方法の詳細については、[ScalarDB SQL API ガイド](./sql-api-guide.mdx)を参照してください。 + +### Spring Data JDBC + +Spring Data JDBC インターフェースを使用すると、Spring Data JDBC リポジトリとエンティティを介して ScalarDB Cluster と対話できます。これは、既に Spring Data を使用しているアプリケーションや、ScalarDB Cluster を Spring アプリケーションに統合したい場合に便利です。 + +Spring Data JDBC インターフェースの設定と使用方法の詳細については、[Spring Data JDBC for ScalarDB ガイド](./spring-data-guide.mdx)を参照してください。 diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/jdbc-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/jdbc-guide.mdx new file mode 100644 index 00000000..b3a03773 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/jdbc-guide.mdx @@ -0,0 +1,222 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB JDBC ガイド + +ScalarDB JDBC の使用方法は、基本的に [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) に従います。 +このガイドでは、ScalarDB JDBC に固有の重要なトピックをいくつか説明します。 + +## プロジェクトに ScalarDB JDBC ドライバーを追加する + +Gradle を使用して ScalarDB JDBC ドライバーの依存関係を追加するには、次を使用します。`` は、使用している ScalarDB JDBC ドライバーと関連ライブラリのバージョンに置き換えます。 + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql-jdbc:' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:' +} +``` + +Maven を使用して依存関係を追加するには、次のコマンドを使用します。`...` は、使用している ScalarDB JDBC ドライバーのバージョンに置き換えます。 + +```xml + + + com.scalar-labs + scalardb-sql-jdbc + ... + + + com.scalar-labs + scalardb-cluster-java-client-sdk + ... + + +``` + +## JDBC 接続 URL + +ScalarDB JDBC の JDBC 接続 URL 形式は次のとおりです。 + +```console +jdbc:scalardb:?=&=&... +``` + +例: + +設定ファイルのパスのみを指定します: + +```console +jdbc:scalardb:/path/to/database.properties +``` + +プロパティのみを指定します: + +```console +jdbc:scalardb:?scalar.db.contact_points=localhost&scalar.db.username=cassandra&scalar.db.password=cassandra&scalar.db.storage=cassandra +``` + +設定ファイルのパスとプロパティを指定します。 + +```console +jdbc:scalardb:/path/to/database.properties?scalar.db.metadata.cache_expiration_time_secs=0 +``` + +## ScalarDB JDBC の設定 + +設定の詳細については、[ScalarDB Cluster SQL クライアント設定](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +さらに、ScalarDB JDBC 固有の設定は次のとおりです。 + +| 名前 | 説明 | デフォルト | +|---------------------------------------------------------------------|----------------------------------------------------|-----------| +| scalar.db.sql.jdbc.default_auto_commit | デフォルトの接続の自動コミットモード。 | true | +| scalar.db.sql.jdbc.sql_session_factory_cache.expiration_time_millis | SQL セッションファクトリのキャッシュの有効期限 (ミリ秒)。 | 10000 | + +## ScalarDB と JDBC 間のデータ型マッピング + +ScalarDB は JDBC で定義されているすべてのデータ型をサポートしているわけではないため、以下では ScalarDB と JDBC 間のデータ型マッピングについて説明します。 + +ScalarDB と JDBC 間のデータ型マッピングは次のとおりです。 + +| ScalarDB タイプ | JDBC (Java) タイプ | +|--------------|-------------------------| +| BOOLEAN | boolean または Boolean | +| INT | int または Integer | +| BIGINT | long または Long | +| FLOAT | float または Float | +| DOUBLE | double または Double | +| TEXT | String | +| BLOB | byte[] | +| DATE | java.time.LocalDate | +| TIME | java.time.LocalTime | +| TIMESTAMP | java.time.LocalDateTime | +| TIMESTAMPTZ | java.time.Instant | + +各データ型の `java.sql.ResultSet` オブジェクトからデータを取得する方法は次のとおりです。 + +```java +try (ResultSet resultSet = ...) { + resultSet.next(); + + // Get a BOOLEAN value of a column + boolean booleanValue = resultSet.getBoolean(""); + + // Get an INT value of a column + int intValue = resultSet.getInt(""); + + // Get a BIGINT value of a column + long bigIntValue = resultSet.getLong(""); + + // Get a FLOAT value of a column + float floatValue = resultSet.getFloat(""); + + // Get a DOUBLE value of a column + double doubleValue = resultSet.getDouble(""); + + // Get a TEXT value of a column + String textValue = resultSet.getString(""); + + // Get a BLOB value of a column + byte[] blobValue = resultSet.getBytes(""); + + // Get a DATE value of a column + LocalDate dateValue = resultSet.getObject("", LocalDate.class); + + // Get a TIME value of a column + LocalTime timeValue = resultSet.getObject("", LocalTime.class); + + // Get a TIMESTAMP value of a column + LocalDateTime timestampValue = resultSet.getObject("", LocalDateTime.class); + + // Get a TIMESTAMPTZ value of a column + Instant timestampTZValue = resultSet.getObject("", Instant.class); +} +``` + +`java.sql.PreparedStatement` オブジェクトの各データ型のパラメータとしてデータを設定する方法は次のとおりです。 + +```java +try (PreparedStatement preparedStatement = ...) { + // Set a BOOLEAN value as parameter + preparedStatement.setBoolean(1, ); + + // Set an INT value as parameter + preparedStatement.setInt(2, ); + + // Set a BIGINT value as parameter + preparedStatement.setLong(3, ); + + // Set a FLOAT value as parameter + preparedStatement.setFloat(4, ); + + // Set a DOUBLE value as parameter + preparedStatement.setDouble(5, ); + + // Set a TEXT value as parameter + preparedStatement.setString(7, ""); + + // Set a BLOB value as parameter + preparedStatement.setBytes(8, ); + //Set a DATE value as parameter + preparedStatement.setObject(9, ); + + //Set a TIME value as parameter + preparedStatement.setObject(10, ); + + //Set a TIMESTAMP value as parameter + preparedStatement.setObject(11, ); + + //Set a TIMESTAMPTZ value as parameter + preparedStatement.setObject(12, ); + + preparedStatement.execute(); +} +``` + +## SQLException の処理 + +例外処理は基本的に ScalarDB SQL API と同じです。 + +```java +// If you execute multiple statements in a transaction, you need to set auto-commit to false. +connection.setAutoCommit(false); + +try { + // Execute statements (SELECT/INSERT/UPDATE/DELETE) in the transaction + ... + + // Commit the transaction + connection.commit(); +} catch (SQLException e) { + if (e.getErrorCode() == 301) { + // The error code 301 indicates that you catch `UnknownTransactionStatusException`. + // If you catch `UnknownTransactionStatusException`, it indicates that the status of the + // transaction, whether it has succeeded or not, is unknown. In such a case, you need to check + // if the transaction is committed successfully or not and retry it if it failed. How to + // identify a transaction status is delegated to users + } else { + // For other cases, you can try retrying the transaction + + // Rollback the transaction + connection.rollback(); + + // The cause of the exception can be `TransactionRetryableException` or the other + // exceptions. For `TransactionRetryableException`, you can basically retry the transaction. + // However, for the other exceptions, the transaction may still fail if the cause of the + // exception is nontransient. For such a case, you need to limit the number of retries and + // give up retrying + } +} +``` + +例外処理の詳細については、[ScalarDB SQL API ガイド](sql-api-guide.mdx)も参照してください。 + +## 参考文献 + +- [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) +- [ScalarDB SQL API ガイド](sql-api-guide.mdx) +- [Javadoc for ScalarDB JDBC](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-jdbc/3.15.4/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/migration-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/migration-guide.mdx new file mode 100644 index 00000000..b20f5b4b --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/migration-guide.mdx @@ -0,0 +1,115 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# アプリケーションとデータベースを ScalarDB ベースの環境に移行する方法 + +このガイドでは、既存のアプリケーションとリレーショナルデータベースをそれぞれ ScalarDB ベースのアプリケーションと ScalarDB 管理データベースに移行する方法について説明します。 + +## 対象読者 + +このガイドの対象読者は、アプリケーション開発者とデータベース管理者です。このガイドの目的は、既存のアプリケーションとデータベースを移行する方法と、移行する条件を理解することです。 + +## 学習内容 + +- 移行の要件 +- アプリケーションを移行する手順 +- 移行のためにアプリケーションに加える変更 + +## アプリケーションを移行する手順 + +```mermaid +flowchart LR +subgraph AM[移行後] + direction TB + C[アプリケーション - 更新済み] -->|ScalarDB SQL| D[ScalarDB] --> E[リレーショナル/JDBC データベース - スキーマ更新済み] +end +subgraph BM[移行前] + direction TB + A[アプリケーション] ---->|SQL| B[リレーショナル/JDBC データベース] +end +BM===>AM +``` + +1. チェックリストの項目を確認します。 + - [移行チェックリスト](#移行チェックリスト)を参照して、データベースが移行可能であることを確認します。 +2. アプリケーションを移行します (必要な場合)。 + - ScalarDB は、専用の SQL 文法を使用して選択、投影、結合操作を提供します。そのため、アプリケーション内の一部の SQL ステートメントは、文法レベルや集計処理などのロジックレベルなど、ScalarDB SQL 用に変更する必要がある場合があります。 + - 詳細については、[アプリケーションの移行方法](#アプリケーションの移行方法)を参照してください。 +3. データベースをバックアップします。 + - データベースのインポートに使用する ScalarDB Schema Loader は、ScalarDB にインポートするときにデータベースのメタデータのみを変更しますが、予期しない事故を避けるためにバックアップする必要があります。 + - データベースの管理ガイドに従ってください。 +4. ScalarDB 環境を設定します。 + - ScalarDB がターゲットデータベースにアクセスできるように設定ファイルを準備します。 + - ScalarDB 設定の詳細については、[ScalarDB 設定](../configurations.mdx)を参照してください。 +5. データベースを ScalarDB にインポートします。 + - ターゲットスキーマとテーブルを定義するインポートスキーマファイルを準備します。スキーマとテーブルは、それぞれ ScalarDB 名前空間とテーブルにマップされます。一部のデータベースシステムでは、「スキーマ」は「データベース」の同義語であることに注意してください。 + - インポートオプション、作成した ScalarDB 設定ファイル、および準備したスキーマファイルを使用して、ScalarDB Schema Loader を実行します。 + - Schema Loader の使用方法の詳細については、[既存のテーブルをインポートするための Schema Loader の実行](../schema-loader-import.mdx#既存のテーブルをインポートするための-schema-loader-の実行)を参照してください。 +6. アプリケーションを切り替えて動作を確認します。 + - これで、アプリケーションを ScalarDB ベースのアプリケーションに切り替えることができます。 + +## 移行チェックリスト + +移行を開始する前に、次の質問を確認してください。これらの質問の答えが1つでも「いいえ」の場合は、移行を進める前にそれらの質問に対処する必要があります。 + +- ターゲットデータベースとバージョンは、[サポートされているリレーショナルデータベース (ScalarDB では JDBC データベースと呼ばれます) とバージョン](../requirements.mdx#リレーショナルデータベース)の1つですか? +- ターゲットデータベースを管理できる完全な権限を持つアカウントがありますか? 詳細については、[一般的な要件](../database-configurations.mdx#一般的な要件)を参照してください。 +- すべてのターゲットテーブルに主キーがありますか? +- 各列のデータ型は ScalarDB でサポートされていますか?サポートされているデータ型と、それらが ScalarDB データ型にマッピングされる方法については、[JDBC データベースから ScalarDB へのデータ型マッピング](../schema-loader-import.mdx#jdbc-データベースからscalardbへのデータ型マッピング)を参照してください。 +- アプリケーション内のクエリの機能と文法は、[ScalarDB SQL 文法](./grammar.mdx)に準拠していますか? または、準拠していないクエリについては、ScalarDB 用に書き直すことができますか? 書き直しの例については、[アプリケーションの移行方法](#アプリケーションの移行方法)を参照してください。 +- アプリケーションとデータベースをそれぞれ ScalarDB アプリケーションと ScalarDB 管理データベースに移行した後、データベースに直接アクセスすることはやめられますか? つまり、常に ScalarDB を介してデータベースにアクセスしても問題ありませんか? + +## アプリケーションの移行方法 + +アプリケーション環境によっては、次の3つの側面でアプリケーションを移行する必要がある場合があります。 + +- 接続設定を変更します。 +- ScalarDB SQL 文法に基づいて SQL ステートメントを変更します。 +- SQL 変更の回避策がない場合は、アプリケーションロジックを変更します。 + +### 接続設定を変更します + +アプリケーションが Java ベースである場合は、移行時に ScalarDB JDBC ドライバーを使用できます。ScalarDB JDBC ドライバーの依存関係を追加して接続 URL を書き換える方法の詳細については、[ScalarDB JDBC ガイド](./jdbc-guide.mdx)を参照してください。 + +アプリケーションが Java ベースでない場合は、ScalarDB に接続して gRPC 経由で SQL を発行できます。詳細については、[ScalarDB Cluster SQL gRPC API ガイド](../scalardb-cluster/scalardb-cluster-sql-grpc-api-guide.mdx)を参照してください。 + +### SQL 文の変更 + +SQL 文法の違いにより、アプリケーション内の SQL 文を変更する必要がある場合があります。一般的な例は次のとおりです。詳細については、[ScalarDB SQL 文法](./grammar.mdx)を参照してください。 + +- `JOIN` クエリ + - ScalarDB は、結合するテーブルと `FROM` 句の条件を記述するスタイルの `JOIN` クエリのみをサポートします。 + - `JOIN` 条件とフィルタリングにもいくつかの制限があります。 + - 上記に基づいてクエリを書き直す必要がある場合があります。SQL クエリが ScalarDB 仕様に準拠していない場合は、アプリケーションレベルの変更を選択できます。 +- `WHERE` 句 + - ScalarDB では、述語は `AND` 述語リストの OR 形式 (論理和標準形または DNF と呼ばれる) または `OR` 述語リストの AND 形式 (論理積標準形または CNF と呼ばれる) である必要があります。したがって、`WHERE` 句を変更する必要があるかもしれませんが、述語の任意の形式を DNF または CNF のいずれかに変更できることに注意してください。 + - 同様に、`IN` 句を使用する場合は、それらを DNF または CNF のいずれかに変更する必要があります。サブクエリを含む `IN` 句については、[アプリケーションロジックの変更](#アプリケーションロジックの変更)を参照してください。 + - ScalarDB は、`LIKE` 演算子と PostgreSQL および MySQL のエスケープシーケンスに類似した仕様を採用しています。データベースが PostgreSQL でも MySQL でもない場合は、`LIKE` 演算子を使用して述語を変更する必要がある場合があります。 + +### アプリケーションロジックの変更 + +ScalarDB SQL には、集計クエリやサブクエリなどの一部の機能が用意されていませんが、これらのクエリはアプリケーションレベルの実装に変更できます。一般的な変更手法は次のとおりです。 + +- 集計クエリ + - `GROUP BY` 句のない `count()` や `sum()` などの単純な集計クエリの場合は、対象レコードに対して `SELECT` を使用し、その結果を使用してレコード数をカウントしたり合計を計算したりすることができます。 + - `GROUP BY` 集計クエリの場合は、まず `GROUP BY` 句を外し、すべての対象レコードに対して `SELECT` を使用します。次に、結果レコードをマルチマップデータ構造に配置し、`GROUP BY` 句で指定された列に基づいて分類します。この列はマルチマップのキーとして使用する必要があります。最後に、マルチマップ内の各キーのレコードを集計します。マルチマップには、[Guava](https://github.com/google/guava) などのライブラリを使用できます。 +- サブクエリ + - `IN` 句のサブクエリの場合、まずサブクエリで指定されたレコードに対して `SELECT` を使用し、次に結果値を `WHERE` 句の `OR` 述語として追加します。 + - その他のサブクエリの場合、基本的に、各クエリのレコードに対して `SELECT` を使用し、次にアプリケーションで結果レコードを結合またはフィルター処理する必要があります。 +- 単一の更新クエリを使用した読み取り、変更、書き込み + - `UPDATE` クエリには、多くの場合、増分または減分などの式が含まれます (例: `UPDATE table SET a = a + 1 WHERE ...`)。ScalarDB では、ターゲットレコードに対して `SELECT` を使用し、次に `UPDATE table SET a = 5 WHERE ...` のように、増分値を単一のトランザクションで定数として設定する必要があります。 + +## 制限事項 + +データ型の違いにより、ScalarDB では、ScalarDB データ型で許容されるサイズであっても、基になるデータベースの列の最大サイズを超えるデータを書き込むとエラーが発生します。逆に、いくつかの型では、基になるデータベースのデータが ScalarDB の最大サイズを超える場合があります。詳細については、[JDBC データベースから ScalarDB へのデータ型マッピング](../schema-loader-import.mdx#jdbc-データベースからscalardbへのデータ型マッピング)を参照してください。 + +## 参考文献 + +- [サポートされているデータベース](../requirements.mdx#データベース) +- [ScalarDB SQL API ガイド](./sql-api-guide.mdx) +- [ScalarDB JDBC ガイド](./jdbc-guide.mdx) +- [ScalarDB SQL 文法](./grammar.mdx) +- [ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](../schema-loader-import.mdx) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/scalardb-sql-status-codes.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/scalardb-sql-status-codes.mdx new file mode 100644 index 00000000..66dd4696 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/scalardb-sql-status-codes.mdx @@ -0,0 +1,647 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB SQL エラーコード + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +このページでは、ScalarDB SQL のエラーコードの一覧を示します。 + +## エラーコードのクラスと説明 + +| クラス | 説明 | +|:---------------|:--------------------------| +| `DB-SQL-1xxxx` | ユーザーエラーカテゴリのエラー | + +## `DB-SQL-1xxxx` ステータスコード + +以下は、ユーザーエラーカテゴリのステータスコードとメッセージです。 + +### `DB-SQL-10000` + +**メッセージ** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-SQL-10001` + +**メッセージ** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-SQL-10002` + +**メッセージ** + +```markdown +The column %s does not exist +``` + +### `DB-SQL-10003` + +**メッセージ** + +```markdown +The column does not exist. Table: %s; Column: %s +``` + +### `DB-SQL-10004` + +**メッセージ** + +```markdown +The column index is out of bounds. Index: %d; Size: %d +``` + +### `DB-SQL-10005` + +**メッセージ** + +```markdown +A positional bind marker is not allowed when binding named values +``` + +### `DB-SQL-10006` + +**メッセージ** + +```markdown +A named bind marker is not allowed when binding positional values +``` + +### `DB-SQL-10007` + +**メッセージ** + +```markdown +Cannot convert BLOB values to SQL. Please use a bind marker for a BLOB value and bind it separately +``` + +### `DB-SQL-10008` + +**メッセージ** + +```markdown +No namespace name has been specified. Set a default namespace name, or explicitly specify a namespace name +``` + +### `DB-SQL-10009` + +**メッセージ** + +```markdown +Zero bytes may not occur in string parameters +``` + +### `DB-SQL-10010` + +**メッセージ** + +```markdown +Mixing positional values and named values is not allowed +``` + +### `DB-SQL-10011` + +**メッセージ** + +```markdown +Preparing a transaction is supported only in two-phase commit transaction mode +``` + +### `DB-SQL-10012` + +**メッセージ** + +```markdown +Validating a transaction is supported only in two-phase commit transaction mode +``` + +### `DB-SQL-10013` + +**メッセージ** + +```markdown +The previous transaction is still in progress. Commit, roll back, or suspend the previous transaction first +``` + +### `DB-SQL-10014` + +**メッセージ** + +```markdown +This SQL session has already been closed +``` + +### `DB-SQL-10015` + +**メッセージ** + +```markdown +A transaction has not begun +``` + +### `DB-SQL-10016` + +**メッセージ** + +```markdown +The type %s is not supported +``` + +### `DB-SQL-10017` + +**メッセージ** + +```markdown +No connection mode implementations are found. Please add a connection mode implementation to the classpath +``` + +### `DB-SQL-10018` + +**メッセージ** + +```markdown +The connection mode is not specified, but multiple connection mode implementations are found. Specify one of the following connection modes: %s +``` + +### `DB-SQL-10019` + +**メッセージ** + +```markdown +The connection mode '%s' is not found. Specify one of the following connection modes: %s +``` + +### `DB-SQL-10020` + +**メッセージ** + +```markdown +Access denied: You need the %s privilege on the namespace %s to execute this operation +``` + +### `DB-SQL-10021` + +**メッセージ** + +```markdown +Access denied: You need the %s privilege on the table %s to execute this operation +``` + +### `DB-SQL-10022` + +**メッセージ** + +```markdown +Access denied: You can't grant the %s privilege because you don't have the same privilege on the table %s +``` + +### `DB-SQL-10023` + +**メッセージ** + +```markdown +Access denied: You can't grant the %s privilege because you don't have the same privilege on the namespace %s +``` + +### `DB-SQL-10024` + +**メッセージ** + +```markdown +Access denied: You can't revoke the %s privilege because you don't have the same privilege on the table %s +``` + +### `DB-SQL-10025` + +**メッセージ** + +```markdown +Access denied: You can't revoke the %s privilege because you don't have the same privilege on the namespace %s +``` + +### `DB-SQL-10026` + +**メッセージ** + +```markdown +Syntax error. Line %d:%d %s +``` + +### `DB-SQL-10027` + +**メッセージ** + +```markdown +Syntax error. Multiple PRIMARY KEYs specified (exactly one required) +``` + +### `DB-SQL-10028` + +**メッセージ** + +```markdown +Cannot grant the INSERT privilege if the user doesn't have the UPDATE privilege +``` + +### `DB-SQL-10029` + +**メッセージ** + +```markdown +Cannot grant the UPDATE privilege if the user doesn't have the INSERT privilege +``` + +### `DB-SQL-10030` + +**メッセージ** + +```markdown +Cannot grant the UPDATE privilege if the user doesn't have the SELECT privilege +``` + +### `DB-SQL-10031` + +**メッセージ** + +```markdown +Cannot grant the DELETE privilege if the user doesn't have the SELECT privilege +``` + +### `DB-SQL-10032` + +**メッセージ** + +```markdown +Cannot revoke the SELECT privilege if the user has the UPDATE privilege +``` + +### `DB-SQL-10033` + +**メッセージ** + +```markdown +Cannot revoke the SELECT privilege if the user has the DELETE privilege +``` + +### `DB-SQL-10034` + +**メッセージ** + +```markdown +Cannot revoke the INSERT privilege if the user has the UPDATE privilege +``` + +### `DB-SQL-10035` + +**メッセージ** + +```markdown +Cannot revoke the UPDATE privilege if the user has the INSERT privilege +``` + +### `DB-SQL-10036` + +**メッセージ** + +```markdown +A non-clustering-key column is specified in the CLUSTERING ORDER directive. Column: %s +``` + +### `DB-SQL-10037` + +**メッセージ** + +```markdown +The order of the columns in the CLUSTERING ORDER directive must match the order for the clustering key (%s must appear before %s) +``` + +### `DB-SQL-10038` + +**メッセージ** + +```markdown +The CLUSTERING ORDER is missing for the column %s +``` + +### `DB-SQL-10039` + +**メッセージ** + +```markdown +Empty SQL is specified +``` + +### `DB-SQL-10040` + +**メッセージ** + +```markdown +Multiple SQLs are not allowed +``` + +### `DB-SQL-10041` + +**メッセージ** + +```markdown +The column %s is ambiguous +``` + +### `DB-SQL-10042` + +**メッセージ** + +```markdown +The column %s cannot be specified in the %s clause. Only the columns in the table %s can be specified in the %s clause +``` + +### `DB-SQL-10043` + +**メッセージ** + +```markdown +An unbound bind marker is still in the escape character of the LIKE predicate for the column %s +``` + +### `DB-SQL-10044` + +**メッセージ** + +```markdown +The escape character must be a TEXT value for the LIKE predicate for the column %s +``` + +### `DB-SQL-10045` + +**メッセージ** + +```markdown +The value of the predicate must not be null unless the operator is 'IS NULL' or 'IS NOT NULL'. Predicate: %s +``` + +### `DB-SQL-10046` + +**メッセージ** + +```markdown +An unbound bind marker is still in the LIMIT clause +``` + +### `DB-SQL-10047` + +**メッセージ** + +```markdown +The LIMIT must be an INT value +``` + +### `DB-SQL-10048` + +**メッセージ** + +```markdown +Unmatched column names or values +``` + +### `DB-SQL-10049` + +**メッセージ** + +```markdown +The column %s is specified twice +``` + +### `DB-SQL-10050` + +**メッセージ** + +```markdown +All primary key columns must be specified in the INSERT or UPSERT statement +``` + +### `DB-SQL-10051` + +**メッセージ** + +```markdown +An unbound bind marker is still in the value of the column %s +``` + +### `DB-SQL-10052` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a boolean value (BOOLEAN) is specified +``` + +### `DB-SQL-10053` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a decimal number (INT or BIGINT) is specified +``` + +### `DB-SQL-10054` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a floating point number (FLOAT or DOUBLE) is specified +``` + +### `DB-SQL-10055` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a string (TEXT, DATE, TIME, TIMESTAMP, or TIMESTAMPTZ) is specified +``` + +### `DB-SQL-10056` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a BOOLEAN value is specified +``` + +### `DB-SQL-10057` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but an INT value is specified +``` + +### `DB-SQL-10058` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a BIGINT value is specified +``` + +### `DB-SQL-10059` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a FLOAT value is specified +``` + +### `DB-SQL-10060` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a DOUBLE value is specified +``` + +### `DB-SQL-10061` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a TEXT value is specified +``` + +### `DB-SQL-10062` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a BLOB value is specified +``` + +### `DB-SQL-10063` + +**メッセージ** + +```markdown +RIGHT OUTER JOIN can only be specified as the first join +``` + +### `DB-SQL-10064` + +**メッセージ** + +```markdown +The JOIN predicate is not specified properly. Predicate: %s +``` + +### `DB-SQL-10065` + +**メッセージ** + +```markdown +The data types of the columns in the JOIN predicate do not match. Predicate: %s +``` + +### `DB-SQL-10066` + +**メッセージ** + +```markdown +The column %s is specified twice in the JOIN predicates. Predicates: %s +``` + +### `DB-SQL-10067` + +**メッセージ** + +```markdown +Either all primary key columns or an indexed column for the table %s must be specified in the JOIN predicates. Predicates: %s +``` + +### `DB-SQL-10068` + +**メッセージ** + +```markdown +Cannot issue mutation DML SQLs such as INSERT, UPDATE or DELETE with executeQuery() +``` + +### `DB-SQL-10069` + +**メッセージ** + +```markdown +Cannot issue SELECT SQLs with executeUpdate() +``` + +### `DB-SQL-10070` + +**メッセージ** + +```markdown +The TWO_PHASE_COMMIT_TRANSACTION mode is not supported in the current transaction manager +``` + +### `DB-SQL-10071` + +**メッセージ** + +```markdown +The encrypted column %s is not allowed in the %s clause +``` + +### `DB-SQL-10072` + +**メッセージ** + +```markdown +The user %s does not exist +``` + +### `DB-SQL-10073` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a DATE value is specified +``` + +### `DB-SQL-10074` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a TIME value is specified +``` + +### `DB-SQL-10075` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a TIMESTAMP value is specified +``` + +### `DB-SQL-10076` + +**メッセージ** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a TIMESTAMPTZ value is specified +``` + +### `DB-SQL-10077` + +**メッセージ** + +```markdown +The policy %s does not exist +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/spring-data-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/spring-data-guide.mdx new file mode 100644 index 00000000..d212ee81 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/spring-data-guide.mdx @@ -0,0 +1,827 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# Spring Data JDBC for ScalarDB ガイド + +ScalarDB API を直接使用するのは、大量のコードを記述し、トランザクションの API (例: `rollback()` および `commit()`) をいつどのように呼び出すかを考慮する必要があるため、難しい場合があります。ほとんどの ScalarDB ユーザーは Java でアプリケーションを開発すると想定されるため、Java で開発するための最も人気のあるアプリケーションフレームワークの1つである Spring Framework を利用できます。Spring Data JDBC for ScalarDB を使用すると、使い慣れたフレームワークを使用して開発を効率化できます。 + +![Spring Data JDBC for ScalarDB の全体的なアーキテクチャの概要](images/spring_data_ingegration_overall_arch.png) + +Spring Data JDBC for ScalarDB の使用方法は、基本的に [Spring Data JDBC - リファレンスドキュメント](https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/)に従います。 + +このガイドでは、Spring Data JDBC for ScalarDB を使用するためのいくつかの重要なトピックとその制限について説明します。 + +:::warning + +Spring Data JDBC for ScalarDB は Spring Data JDBC を拡張していますが、完全に代替するものではありません。このドキュメントに記載されている機能のみが公式にテストされサポートされています。 + +::: + +## Spring Data JDBC for ScalarDB をプロジェクトに追加します + +Gradle を使用して Spring Data JDBC for ScalarDB への依存関係を追加するには、以下を使用します。`` は、使用している Spring Data JDBC for ScalarDB と関連ライブラリのバージョンにそれぞれ置き換えます。 + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql-spring-data:' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:' +} +``` + +Maven を使用して依存関係を追加するには、以下を使用します。`...` を、使用している Spring Data JDBC for ScalarDB のバージョンに置き換えます。 + +```xml + + + com.scalar-labs + scalardb-sql-spring-data + ... + + + com.scalar-labs + scalardb-cluster-java-client-sdk + ... + + +``` + +## 設定 + +Spring Data JDBC for ScalarDB は、Spring アプリケーションの一部として使用されることになっています。少なくとも次のプロパティが必要です。 + +### spring.datasource.driver-class-name + +これは、固定値 `com.scalar.db.sql.jdbc.SqlJdbcDriver` に設定する必要があります。 + +```console +spring.datasource.driver-class-name=com.scalar.db.sql.jdbc.SqlJdbcDriver +``` + +### spring.datasource.url + +この値は、ScalarDB JDBC 接続 URL 設定に従います。詳細については、[ScalarDB JDBC ガイド](jdbc-guide.mdx)および [ScalarDB Cluster SQL クライアント設定](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +```console +spring.datasource.url=jdbc:scalardb:\ +?scalar.db.sql.connection_mode=direct\ +&scalar.db.contact_points=jdbc:mysql://localhost:3306/my_app_ns\ +&scalar.db.username=root\ +&scalar.db.password=mysql\ +&scalar.db.storage=jdbc\ +&scalar.db.consensus_commit.isolation_level=SERIALIZABLE +``` + +## アノテーション + +Spring Data JDBC for ScalarDB を使用するには、次のように JVM アプリケーションに `@EnableScalarDbRepositories` アノテーションが必要です。 + +```java +@SpringBootApplication +@EnableScalarDbRepositories +public class MyApplication { + // These repositories are described in the next section in details + @Autowired private GroupRepository groupRepository; + @Autowired private UserRepository userRepository; +``` + +## 永続エンティティモデル + +Spring Data JDBC for ScalarDB のユーザーは、ScalarDB テーブルへのオブジェクトマッピング用のクラスを作成する必要があります。これらのクラスの作成方法は [永続エンティティ](https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/#jdbc.entity-persistence)に記載されています。このセクションでは、統合に関するいくつかの制限について説明します。 + +これらはモデルクラスの例です。 + +### domain/model/User + +```java +// This model class corresponds to the following table schema: +// +// create table my_app_ns.user (id bigint, group_id bigint, name text, primary key (id)); +// +// -- UserRepository can use `name` column as a condition in SELECT statement +// -- as the column is a ScalarDB secondary index. +// create index on my_app_ns.user (name); + +// Set `schema` parameter in @Table annotation if you don't use `scalar.db.sql.default_namespace_name` property. +// +// Spring Data automatically decides the target table name based on a model class name. +// You can also specify a table name by setting `value` parameter. +// +// @Table(schema = "my_app_ns", value = "user") +@Table +public class User { + @Id + public final Long id; + + public final Long groupId; + + // Spring Data automatically decides the target column name based on an instance variable name. + // You can also specify a column name by setting `value` parameter in @Column annotation. + // @Column("name") + public final String name; + + public User(Long id, Long groupId, String name) { + this.id = id; + this.groupId = groupId; + this.name = name; + } +} +``` + +### domain/model/Group + +```java +// This model class corresponds to the following table schema: +// +// create table my_app_ns.group (account_id int, group_type int, balance int, primary key (account_id, group_type)); + +@Table +public class Group { + // This column `account_id` is a part of PRIMARY KEY in ScalarDB SQL + // + // Spring Data JDBC always requires a single @Id annotation while it doesn't allow multiple @Id annotations. + // The corresponding ScalarDB SQL table `group` has a primary key consisting of multiple columns. + // So, Spring Data @Id annotation can't be used in this case, but @Id annotation must be put on any instance variable + // (@Id annotation can be put on `balance` as well.) + @Id + public final Integer accountId; + + // This column `group_type` is also a part of PRIMARY KEY in ScalarDB SQL + public final Integer groupType; + + public final Integer balance; + + public Group(Integer accountId, Integer groupType, Integer balance) { + this.accountId = accountId; + this.groupType = groupType; + this.balance = balance; + } +} +``` + +[このサンプル実装](https://github.com/scalar-labs/scalardb-samples/tree/main/spring-data-sample/src/main/java/sample/domain/model)もリファレンスとして使用できます。 + +### domain/repository/UserRepository + +```java +@Transactional +@Repository +public interface UserRepository extends ScalarDbRepository { + + // `insert()` and `update()` are automatically enabled with `ScalarDbRepository` (or `ScalarDbTwoPcRepository`). + + // Many APIs of `CrudRepository` and `PagingAndSortingRepository` are automatically enabled. + // https://docs.spring.io/spring-data/commons/docs/3.0.x/api/org/springframework/data/repository/CrudRepository.html + // https://docs.spring.io/spring-data/commons/docs/3.0.x/api/org/springframework/data/repository/PagingAndSortingRepository.html + + // Also, you can prepare complicated APIs with the combination of the method naming conventions. + // https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/#repositories.definition-tuning + + // These APIs use the ScalarDB secondary index + List findByName(String name); + List findTop2ByName(String name); + // Current ScalarDB SQL doesn't support range scan or order using secondary indexes + // List findByNameBetween(String name); + // List findByGroupIdOrderByName(long groupId); + + default void reverseName(long id) { + Optional model = findById(id); + if (model.isPresent()) { + User existing = model.get(); + User updated = + new User( + existing.id, + existing.groupId, + existing.name.reverse()); + update(updated); + } + } + + default void deleteAfterSelect(long id) { + Optional existing = findById(id); + existing.ifPresent(this::delete); + } +} +``` + +### domain/repository/GroupRepository + +```java +@Transactional +@Repository +public interface GroupRepository extends ScalarDbRepository { + + // @Id annotation is put only on Group.accountId, but ScalarDB SQL expects the combination of + // `account_id` and `group_type` columns as the table uses them as a primary key. So `findById()` can't be used. + Optional findFirstByAccountIdAndGroupType(int accountId, int groupType); + + List findByAccountIdAndGroupTypeBetweenOrderByGroupTypeDesc( + int accountId, int groupTypeFrom, int groupTypeTo); + + List findTop2ByAccountIdAndGroupTypeBetween( + int accountId, int groupTypeFrom, int groupTypeTo); + + // `update()` method also depends on @Id annotation as well as `findById()`, + // so users need to write ScalarDB SQL in @Query annotation. + @Modifying + @Query( + "UPDATE \"my_app_ns\".\"group\" SET \"balance\" = :balance \n" + + " WHERE \"my_app_ns\".\"group\".\"account_id\" = :accountId \n" + + " AND \"my_app_ns\".\"group\".\"group_type\" = :groupType \n") + int updateWithAttributes( + @Param("accountId") int accountId, + @Param("groupType") int groupType, + @Param("balance") int balance); + + default void incrementBalance(int accountId, int groupType, int value) { + Optional model = findFirstByAccountIdAndGroupType(accountId, groupType); + model.ifPresent( + found -> + updateWithAttributes( + found.accountId, found.groupType, found.balance + value)); + } + + default void transfer( + int accountIdFrom, int groupTypeFrom, int accountIdTo, int groupTypeTo, int value) { + incrementBalance(accountIdFrom, groupTypeFrom, -value); + incrementBalance(accountIdTo, groupTypeTo, value); + } + + // This method name and signature results in issuing an unexpected SELECT statement and + // results in query failure. It looks a bug of Spring Data... + // + // void deleteByAccountIdAndGroupType(int accountId, int groupType); + + @Modifying + @Query( + "DELETE FROM \"my_app_ns\".\"group\" \n" + + " WHERE \"my_app_ns\".\"group\".\"account_id\" = :accountId \n" + + " AND \"my_app_ns\".\"group\".\"group_type\" = :groupType \n") + int deleteByAccountIdAndGroupType( + @Param("accountId") int accountId, @Param("groupType") int groupType); + + default void deleteByAccountIdAndGroupTypeAfterSelect(int accountId, int groupType) { + Optional entity = findFirstByAccountIdAndGroupType(accountId, groupType); + entity.ifPresent(found -> deleteByAccountIdAndGroupType(accountId, groupType)); + } +} +``` + +[このサンプル実装](https://github.com/scalar-labs/scalardb-samples/tree/main/spring-data-sample/src/main/java/sample/domain/repository)もリファレンスとして使用できます。 + +## エラー処理 + +Spring Data JDBC for ScalarDB では、次の例外がスローされる可能性があります。 + +- com.scalar.db.sql.springdata.exception.ScalarDbTransientException + - これは、一時的なエラーが原因でトランザクションが失敗したときにスローされます。 + - トランザクションを再試行する必要があります。 + - これは `org.springframework.dao.TransientDataAccessException` のサブクラスであり、Spring Data からスローされる他の種類の一時的なエラーを処理するには、スーパークラスをキャッチする方が安全です。 +- com.scalar.db.sql.springdata.exception.ScalarDbNonTransientException + - これは、非一時的エラーが原因でトランザクションが失敗した場合にスローされます。 + - トランザクションは再試行しないでください。 + - これは `org.springframework.dao.NonTransientDataAccessException` のサブクラスであり、Spring Data からスローされる他のタイプの非一時的エラーを処理するには、スーパークラスをキャッチする方が安全です。 +- com.scalar.db.sql.springdata.exception.ScalarDbUnknownTransactionStateException + - これは `ScalarDbNonTransientException` のサブクラスであり、トランザクションも再試行しないでください。 + - これは、トランザクションのコミットが失敗し、最終状態が不明な場合にスローされます。 + - トランザクションが実際にコミットされるかどうかは、アプリケーション側で決定する必要があります (例: ターゲットレコードが期待どおりに更新されているかどうかを確認します)。 + +これらの例外にはトランザクション ID が含まれており、トラブルシューティングに役立ちます。 + +## 制限事項 + +### 複数列の PRIMARY KEY + +上記の例からわかるように、Spring Data JDBC の `@Id` アノテーションは複数の列をサポートしていません。そのため、テーブルに複数の列で構成される主キーがある場合、ユーザーは次の API を使用できず、`@Query` アノテーションで Scalar SQL DB クエリを記述する必要がある場合があります。 + +- `findById()` +- `existsById()` +- `update(T entity)` +- `delete(T entity)` +- `deleteById(ID id)` +- `deleteAllById(Iterable ids)` + +### 2つのエンティティ間の1対多の関係 + +Spring Data JDBC は1対多の関係をサポートしています。ただし、親の属性のみが変更された場合でも、関連付けられているすべての子レコードが暗黙的に削除され、再作成されます。この動作により、パフォーマンスが低下します。さらに、Spring Data JDBC for ScalarDB の1対多の関係の特定のユースケースは、ScalarDB SQL のいくつかの制限との組み合わせにより失敗します。これらの懸念と制限を考慮すると、Spring Data JDBC for ScalarDB の機能を使用することは推奨されません。 + +たとえば、Bank レコードに多数の Account レコードが含まれていると仮定すると、次の実装は `BankRepository#update()` を呼び出すと失敗します。 + +```java +@Autowired BankRepository bankRepository; + +... + +bankRepository.insert(new Bank(42, "My bank", ImmutableSet.of( + new Account(1, "Alice"), + new Account(2, "Bob"), + new Account(3, "Carol") +))); + +Bank bank = bankRepository.findById(42).get(); +System.out.printf("Bank: " + bank); + +// Fails here as `DELETE FROM "account" WHERE "account"."bank_id" = ?` is implicitly issued by Spring Data JDBC +// while ScalarDB SQL doesn't support DELETE with a secondary index +// (Spring Data JDBC's custom query might avoid these limitations) +bankRepository.update(new Bank(bank.bankId, bank.name + " 2", bank.accounts)); +``` + +## 高度な機能 + +### マルチストレージトランザクション + +ScalarDB は [マルチストレージトランザクション](../multi-storage-transactions.mdx)をサポートしており、ユーザーは Spring Data JDBC for ScalarDB を介してこの機能を使用できます。この機能を使用するには、次の設定が必要です。 + +#### spring.datasource.url + +以下は、それぞれ MySQL と PostgreSQL でデータを管理する2つの名前空間「north」と「south」があると仮定したサンプルのデータソース URL です。 + +``` +spring.datasource.url=jdbc:scalardb:\ +?scalar.db.sql.connection_mode=direct\ +&scalar.db.storage=multi-storage\ +&scalar.db.multi_storage.storages=mysql,postgresql\ +&scalar.db.multi_storage.namespace_mapping=north:mysql,south:postgresql\ +&scalar.db.multi_storage.default_storage=postgresql\ +&scalar.db.multi_storage.storages.mysql.storage=jdbc\ +&... +``` + +#### モデルクラスの @Table アノテーション + +- `schema` パラメータ: マルチストレージマッピングキー名 (`scalar.db.multi_storage.namespace_mapping`) +- `value` パラメータ: 実際のテーブル名 + +```java + @Table(schema = "north", value = "account") + public class NorthAccount { +``` + +### 再試行 + +#### Spring Retry を使用した再試行 + +Spring Data JDBC for ScalarDB は、同時トランザクションが競合すると例外をスローする可能性があります。ユーザーは、操作を再試行してこれらの例外に対処する必要があります。[Spring Retry](https://github.com/spring-projects/spring-retry) は再試行のための機能を提供します。また、Spring Data JDBC for ScalarDB でも、Spring Retry を使用すると再試行処理がシンプルかつ簡単になります。このセクションでは、Spring Retry の使用方法を紹介します。 + +##### 依存関係 + +次の依存関係をプロジェクトに追加する必要があります。 + +```gradle +dependencies { + implementation "org.springframework.boot:spring-boot-starter:${springBootVersion}" + implementation "org.springframework.boot:spring-boot-starter-aop:${springBootVersion}" + implementation "org.springframework.retry:spring-retry:${springRetryVersion}" +} +``` + +##### 注釈 + +JVM アプリケーションに `@EnableRetry` 注釈を追加する必要があります。 + +```java +@SpringBootApplication +@EnableScalarDbRepositories +@EnableRetry +public class MyApp { +``` + +`@Retryable` アノテーションにより、Spring Data リポジトリクラスまたはメソッドは失敗した操作を自動的に再試行します。Spring Data JDBC for ScalarDB は一時的なエラー例外をスローする可能性があるため、アノテーションでターゲットクラスとして `org.springframework.dao.TransientDataAccessException` を指定することを強くお勧めします。また、バックオフと最大試行回数は、次のようにアノテーションで設定できます。 + +```java + @Transactional + @Retryable( + include = TransientDataAccessException.class, + maxAttempts = 4, + backoff = @Backoff(delay = 500, maxDelay = 2000, multiplier = 2)) + default void insertWithRetry(Player player) { + insert(player); + } +``` + +`@Recover` アノテーションを使用すると、再試行回数を超えた失敗は指定されたメソッドによって自動的に回復されます。 + +```java + @Transactional + @Retryable(include = TransientDataAccessException.class, + recover = "recoverInsert") + default void insertWithRetryAndRecover(Player player) { + insert(player); + } + + @Transactional + @Recover + default void recoverInsert(Throwable throwable, Player player) throws Throwable { + Optional existing = findById(player.id); + if (!existing.isPresent()) { + throw throwable; + } + logger.info( + "Found an existing record {}. Updating it with a new record {}", existing.get(), player); + + update(player); + } +``` + +#### 他の再試行ライブラリを使用して再試行 + +トランザクションを再試行するための他のオプションとして、Spring Retry の RetryTemplate や Resilience4j などがあります。お好みの再試行ライブラリを自由に選択して使用してください。 + +### 2フェーズコミットトランザクション + +ScalarDB は[2フェーズコミットトランザクション](../two-phase-commit-transactions.mdx)をサポートしており、ユーザーは Spring Data JDBC for ScalarDB を介してこの機能を使用できます。次の設定が必要です。 + +#### spring.datasource.url + +- `scalar.db.sql.default_transaction_mode` プロパティ: `two_phase_commit_transaction` + +```console +spring.datasource.url=jdbc:scalardb:\ +?scalar.db.sql.connection_mode=direct\ +&scalar.db.contact_points=jdbc:mysql://localhost:3306/my_app_ns\ +&...\ +&scalar.db.sql.default_transaction_mode=two_phase_commit_transaction +``` + +#### Spring Data トランザクションマネージャーの設定 + +Spring Data JDBC for ScalarDB は、2PC トランザクションを実現するためのカスタム Spring Data トランザクションマネージャーを提供します。カスタムトランザクションマネージャーを有効にするには、次のいずれかのアノテーションを設定する必要があります。 + +- すべての `@Transactional` の `transactionManager` パラメーターを `scalarDbSuspendableTransactionManager` に設定します +- `@EnableScalarDbRepositories` の `transactionManagerRef` パラメーターを `scalarDbSuspendableTransactionManager` に設定します + +#### リポジトリクラス + +##### API + +Spring Data JDBC for ScalarDB は、2PC トランザクション用の2種類の API をサポートしています。1つはプリミティブ API で、もう1つは高レベル API です。 + +##### プリミティブ 2PC API + +`ScalarDbTwoPcRepository` は `ScalarDbRepository` の拡張であり、ScalarDB の同じ名前のメソッドに対応する次の API があり、ユーザーはこれらを使用して 2PC トランザクション用のカスタムリポジトリメソッドを構築できます。 + +- begin() +- 自動生成されたトランザクション ID を返します +- prepare() +- validate() +- suspend() +- commit() +- join(`transactionId`) +- resume(`transactionId`) + +Spring Data リポジトリメソッドから例外がスローされると、実行中のすべての操作がロールバックされます。 + +詳細については、[2フェーズコミットトランザクションの実行方法](../two-phase-commit-transactions.mdx#2フェーズコミットトランザクションの実行方法)を参照してください。 + +```java +@Transactional(transactionManager = "scalarDbSuspendableTransactionManager") +@Repository +public interface TwoPcPlayerRepository extends ScalarDbTwoPcRepository { + + Logger logger = LoggerFactory.getLogger(TwoPcPlayerRepository.class); + + // Either of twoPcJoinAndInsert() or twoPcBeginAndInsert() can be used to start a transaction + default void twoPcJoinAndInsert(String txId, Player player) throws SQLException { + join(txId); + insert(player); + suspend(); + } + + default String twoPcBeginAndInsert(String id, Player player) throws SQLException { + String txId = begin(); + insert(player); + suspend(); + return txId; + } + + default void twoPcPrepare(String txId) throws SQLException { + resume(txId); + prepare(); + suspend(); + } + + default void twoPcValidate(String txId) throws SQLException { + resume(txId); + validate(); + suspend(); + } + + default void twoPcCommit(String txId) throws SQLException { + resume(txId); + commit(); + } +``` + +###### 高レベル 2PC API + +上記のプリミティブ API は強力で、柔軟かつきめ細かな方法で 2PC トランザクション操作を明示的に制御できます。一方、ユーザーは API を使用する際に、どの API を適切な順序で呼び出すかを考慮する必要があります。特に、ローカル状態やリモートサービス呼び出しのコーディネーター側の操作は複雑になりやすいです。 + +`ScalarDbTwoPcRepository` は、一般的なユースケースをカバーするために、高レベル API と呼ばれるユーザーフレンドリな API もいくつか提供しています。これらの API を使用すると、マイクロサービスアプリケーションをより簡単かつ安全に開発できます。 + +マイクロサービスでのコーディネーターサービスの開発のために、`ScalarDbTwoPcRepository` は、2PC 関連の操作を次の順序で暗黙的に実行する `executeTwoPcTransaction` API を提供しています。この API を使用すると、トランザクション操作をどのように、いつ実行するかを考える必要がありません。 + +- グローバルトランザクション ID を使用してローカルトランザクションを開始します +- 実行フェーズ: ローカルおよびリモートの CRUD 操作 (*) +- 準備フェーズ: ローカルおよびリモートの準備操作 (**) を並列で実行します +- 検証フェーズ: ローカルおよびリモートの検証操作 (**) を並列で実行します +- これは、`scalar.db.consensus_commit.isolation_level` が `SERIALIZABLE` で、`scalar.db.consensus_commit.serializable_strategy` が `EXTRA_READ` である場合にのみ必要です +- コミットフェーズ: ローカルコミット操作が最初に実行されます。ローカルコミット操作が成功した後、リモートコミット操作が並列で実行されます (**) +- (リモートコミット操作以外の操作が失敗した場合) ロールバックフェーズ: ローカルおよびリモートのロールバック操作が並列で実行されます (**) + +(* このローカルおよびリモート操作コールバックの実装は、ユーザーによって挿入されます)\ +(** このリモート操作コールバックの実装は、ユーザーによって挿入されます) + +ローカルおよびリモート参加者のロールバック操作は、いずれかの操作から例外がスローされたときに実行されます。 + +`executeTwoPcTransaction()` のエラー処理については、 + +- API から次の例外がスローされる可能性があります +- `ScalarDbTransientException` +- この例外がスローされた場合、ユーザーは 2PC トランザクション操作を最初から再試行する必要があります +- `ScalarDbNonTransientException` +- `ScalarDbUnknownTransactionStateException` +- 2PC トランザクションが実際にコミットされるかどうかは、アプリケーション側で決定する必要があります +- 例外には 2PC グローバルトランザクション ID が含まれます。トラブルシューティングに役立つはずです + +実行フェーズ操作 (ローカルおよびリモート参加者) の実装と、ユーザーによって渡される準備/検証/コミット/ロールバックフェーズのリモート操作については、失敗したときにこれらのコールバックでいずれかの例外をスローする必要があります: + +- ネットワーク切断やデータベーストランザクションの競合などの一時的な問題が発生した場合は `ScalarDbTransientException` +- 認証エラーや権限エラーなどの非一時的な問題が発生した場合は `ScalarDbNonTransientException` +- 原因として `UnknownTransactionStatusException` を含む例外が発生した場合は `ScalarDbUnknownTransactionStateException` +- コールバックからスローされるその他の例外は `ScalarDbTransientException` として扱われます + +マイクロサービスでの参加者サービスの開発のために、`ScalarDbTwoPcRepository` は次の API を提供します。この API を使用すると、トランザクションに参加、再開、一時停止する方法とタイミングを詳細に考える必要がありません。 + +- `joinTransactionOnParticipant` + - トランザクションに参加し、CRUD 操作を実行し、参加者サービスでトランザクションを一時停止します。この API を最初に呼び出し、次に `prepareTransactionOnParticipant` とそれに続く API を呼び出す必要があります。 +- `resumeTransactionOnParticipant` + - トランザクションを再開し、CRUD 操作を実行して、参加者サービスでトランザクションを一時停止します。この API は、必要に応じて、`joinTransactionOnParticipant` の後、`prepareTransactionOnParticipant` の前に呼び出すことができます。 +- `prepareTransactionOnParticipant` + - トランザクションを準備し、参加者サービスでトランザクションを一時停止します。この API は `joinTransactionOnParticipant` の後に呼び出され、その後 `validateTransactionOnParticipant` とそれに続く API が呼び出されるはずです。 +- `validateTransactionOnParticipant` + - トランザクションを検証し、参加者サービスでトランザクションを一時停止します。この API は `prepareTransactionOnParticipant` の後に呼び出され、その後 `commitTransactionOnParticipant` または `rollbackTransactionOnParticipant` が呼び出される必要があります。 + - これは、`scalar.db.consensus_commit.isolation_level` が `SERIALIZABLE` で、`scalar.db.consensus_commit.serializable_strategy` が `EXTRA_READ` の場合にのみ必要です。 +- `commitTransactionOnParticipant` + - 参加者サービスでトランザクションをコミットします。この API は、トランザクションマネージャーの設定に応じて、`prepareTransactionOnParticipant` または `validateTransactionOnParticipant` の後に呼び出す必要があります。 +- `rollbackTransactionOnParticipant` + - 参加者サービスでトランザクションをロールバックします。この API は、トランザクションマネージャーの設定に応じて、`prepareTransactionOnParticipant` または `validateTransactionOnParticipant` の後に呼び出す必要があります。 + +Spring Data JDBC for ScalarDB の高レベル 2PC API を使用すると、次のように複雑なトランザクション操作を API 内に隠すことで、ビジネスロジックに集中できます。 + +**コーディネーターサービス** + +```java + @Autowired private AccountRepository accountRepository; + private final StockService stockService = ...; + private final NotificationService notificationService = ...; + private final List remotePrepareCommitOpsList = + Arrays.asList( + RemotePrepareCommitPhaseOperations.createSerializable( + stockService::prepareTransaction, + stockService::validateTransaction, + stockService::commitTransaction, + stockService::rollbackTransaction), + RemotePrepareCommitPhaseOperations.createSerializable( + notificationService::prepareTxn, + notificationService::validateTxn, + notificationService::commitTxn, + notificationService::rollbackTxn)); +``` + +```java + private Result> executeTwoPcTransactionUsingHighLevelApi( + Account account, String itemName, int itemPrice, String notificationEventName) { + return accountRepository.executeTwoPcTransaction( + // CRUD operations for local and remote participants in execution phase. + txId -> { + // [local] Read the account's balance + Optional stored = accountRepository.findById(account.id); + if (!stored.isPresent()) { + // Cancel the transaction if the account doesn't exist. + // No need to retry. + throw new ScalarDbNonTransientException( + "The local state doesn't meet the condition. Aborting this transaction"); + } + // [remote] Start a transaction with the transaction ID, + // read the item information and decrement the count + Optional price = stockService.purchaseItem(txId, account.id, itemName); + // [remote] Start a transaction with the transaction ID, + // read the notification and remove it + Optional notification = + notificationService.getNotification(txId, account.id, notificationEventName); + if (price.isPresent() && notification.isPresent()) { + int currentBalance = stored.get().balance - price.get(); + if (currentBalance < 0) { + // Cancel the transaction if the global state doesn't meet the condition. + // No need to retry. + throw new ScalarDbNonTransientException( + "The state of local and remote participants doesn't meet the condition. Aborting this transaction"); + } + // [local] Decrease the account's balance for the item + accountRepository.update(new Account(account.id, currentBalance)); + return Pair.of(currentBalance, notification.get()); + } + // Cancel the transaction if the global state doesn't meet the condition. + // No need to retry. + throw new ScalarDbNonTransientException( + "The remote state doesn't meet the condition. Aborting this transaction"); + }, + // Remote operations for Prepare/Validate/Commit/Rollback + remotePrepareCommitOpsList); + } +``` + +```java + RetryTemplate retryTemplate = + new RetryTemplateBuilder() + .retryOn(TransientDataAccessException.class) + .exponentialBackoff(500, 2.0, 8000) + .maxAttempts(8) + .withListener( + new RetryListenerSupport() { + @Override + public void onError(RetryContext context, RetryCallback callback, Throwable throwable) { + if (throwable instanceof ScalarDbUnknownTransactionStateException) { + // Report an exception occurred that requires special treatments + reportToDevelopers( + String.format("Failed to process a 2PC transaction (%s). The final transaction status is unknown. Please check current application status", + ((ScalarDbUnknownTransactionStateException) throwable).getTransactionId()), throwable); + } + }}) + .build(); + + Result> result = + retryTemplate.execute(context -> + executeTwoPcTransactionUsingHighLevelApi(account, itemName, itemPrice, notificationEventName)); +``` + +[このサンプル実装](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java)もリファレンスとして使用できます。 + +**参加者サービス** + +```java +@RestController +public class StockController { + @Autowired private StockRepository stockRepository; + + @PostMapping("/purchaseItem") + public Optional purchaseItem( + @RequestParam("transactionId") String transactionId, + @RequestParam("accountId") int accountId, + @RequestParam("itemName") String itemName) { + return stockRepository.joinTransactionOnParticipant(txId, () -> { + Optional item = stockRepository.findById(itemName); + + ... + + return Optional.of(item.price); + }); + } + + @PostMapping("/prepareTransaction") + public void prepareTransaction(@RequestParam("transactionId") String transactionId) { + return stockRepository.prepareTransactionOnParticipant(txId); + } + + @PostMapping("/validateTransaction") + public void validateTransaction(@RequestParam("transactionId") String transactionId) { + return stockRepository.validateTransactionOnParticipant(txId); + } + + @PostMapping("/commitTransaction") + public void commitTransaction(@RequestParam("transactionId") String transactionId) { + return stockRepository.commitTransactionOnParticipant(txId); + } + + @PostMapping("/rollbackTransaction") + public void rollbackTransaction(@RequestParam("transactionId") String transactionId) { + return stockRepository.rollbackTransactionOnParticipant(txId); + } +} +``` + +[このサンプル実装](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java)は REST API ではなく gRPC を使用していますが、リファレンスとしても使用できます。 + +#### JVM アプリケーションで 2PC と通常のトランザクションモードの両方を使用する方法 + +ほとんどの場合、アプリケーションでは 2PC と通常のトランザクションモードのいずれか1つだけを使用することになっています。ただし、両方のトランザクションモードを使用するユースケースもあります。たとえば、2PC の参加者として使用されるサービスに、2PC プロトコルを使用せずに他のサービスまたはクライアントから直接呼び出される API がいくつかあるとします。この場合、開発者は 2PC で使用されない API に対して通常のトランザクションモードを使用するだけで済みます。 + +このユースケースを実現するには、2PC と通常のトランザクションモードの異なる `scalar.db.sql.default_transaction_mode` パラメータを、`spring.datasource.url` プロパティを介して Spring Data JDBC フレームワークに渡す必要があります。ただし、Spring Data JDBC では、複数のデータソース設定を使用する簡単な方法は提供されていません。ただし、いくつかのカスタム設定クラスを使用すると、ユーザーは複数のデータソース設定を使用する JVM アプリケーションで 2PC と通常のトランザクションモードの両方を使用できます。 + +#### 制限事項 + +##### `@Transactional` メソッドは `commit()` を暗黙的に呼び出しません + +ScalarDB を使用したマイクロサービスアプリケーションでは、コミットはコーディネーターサービスによって明示的に呼び出される必要があり、`@Transactional` メソッドを終了するときに Spring Data トランザクションフレームワークによってローカルにトリガーされることはありません。`@Transactional(transactionManager = "scalarDbSuspendableTransactionManager")` アノテーションは、このようなローカルコミットを防止します。 + +この拡張された動作は、`@Transactional` メソッドがトランザクションを暗黙的にコミットすることを期待している開発者を混乱させる可能性があります。 + +たとえば、サービスクラスのメソッドで `@Transactional` アノテーションを使用すると仮定すると、次のコードは **通常の** トランザクションモードで機能します。 + +```java +@Service +public class SampleService { + + ... + + // For the normal transaction mode + @Transactional + // For the 2PC transaction mode + // @Transactional(transactionManager = "scalarDbSuspendableTransactionManager") + public void repayment(int customerId, int amount) { + Customer customer = customerRepository.getById(customerId); + + int updatedCreditTotal = customer.creditTotal - amount; + + // Check if over repayment or not + if (updatedCreditTotal < 0) { + throw new RuntimeException( + String.format( + "Over repayment. creditTotal:%d, payment:%d", customer.creditTotal, amount)); + } + + // Reduce credit_total for the customer + customerRepository.update(customer.withCreditTotal(updatedCreditTotal)); + } +} +``` + +ただし、このコードは、`transactionManager = "scalarDbSuspendableTransactionManager"` であっても 2PC トランザクションモードでは機能しません。代わりに、次のように `ScalarDbTwoPcRepository.executeOneshotOperations()` を使用します。 + +```java +@Service +public class SampleService { + + ... + + public void repayment(int customerId, int amount) { + customerRepository.executeOneshotOperations(() -> { + Customer customer = customerRepository.getById(customerId); + + int updatedCreditTotal = customer.creditTotal - amount; + + // Check if over repayment or not + if (updatedCreditTotal < 0) { + throw new RuntimeException( + String.format( + "Over repayment. creditTotal:%d, payment:%d", customer.creditTotal, amount)); + } + + // Reduce credit_total for the customer + customerRepository.update(customer.withCreditTotal(updatedCreditTotal)); + + return null; + }); + } +} +``` + +## トラブルシューティング + +このセクションでは、Spring Data JDBC の使用時に発生する可能性のあるエラーのトラブルシューティング方法について説明します。 + +### `A constructor parameter name must not be null to be used with Spring Data JDBC` ランタイムエラー + +Spring Boot 3の使用時に、`A constructor parameter name must not be null to be used with Spring Data JDBC` というランタイムエラーが発生する場合があります。この問題を回避するには、次のように `javac` に `-parameters` オプションを渡します。 + +```gradle + compileJava { + options.compilerArgs << '-parameters' + } +``` + +## サンプルアプリケーション + +Spring Data JDBC for ScalarDB を使用する次のサンプルアプリケーションを確認できます。これは参照用であり、必ずしも本番環境のコード標準を満たしているわけではありません。 + +- [Spring Data JDBC for ScalarDB を使用した ScalarDB Cluster SQL をはじめよう](../scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [マルチストレージトランザクションを使用した Spring Data JDBC for ScalarDB のサンプルアプリケーション](../scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx) +- [マイクロサービストランザクションを使用した Spring Data JDBC for ScalarDB のサンプルアプリケーション](../scalardb-samples/spring-data-microservice-transaction-sample/README.mdx) + +## 仕組み + +Spring Data JDBC for ScalarDB を使用するために、統合では次の機能が実装されています。 + +- JDBC 接続 URL の `jdbc:scalardb` プロトコルを ScalarDB SQL の Spring Data JDBC 方言クラスにマップします。 + - この機能は ScalarDbDialect と ScalarDbDialectProvider によって処理されます。 +- ScalarDB SQL でサポートされていない Spring Data Repository クラス (CrudRepository および PagingAndSortingRepository) の一部 API をユーザーが使用できないようにします。 + - この機能は、リポジトリクラスで使用される少し下位層の Spring Data JDBC コンポーネントであるScalarDbJdbcAggregateTemplateによって処理されます。 +- Spring Data Repository クラスが暗黙的にカスタム JdbcAggregateTemplate (ScalarDbJdbcAggregateTemplate) を使用するようにします。 + - この機能は ScalarDbJdbcRepositoryFactory と ScalarDbJdbcRepositoryFactoryBean によって処理されます。 +- ScalarDB SQL ではサポートされていない、基盤となるデータベースの自動増分 ID 機能に依存するバンドルされた `save()` の代わりに、明示的な `insert()` および `update()` API を Spring Data Repository クラスに追加します。 + - この機能は ScalarDbRepository (または ScalarDbTwoPcRepository) と ScalarDbRepositoryImpl によって処理されます。 +- 上記のすべての機能を Spring フレームワークの方法で有効にします。 + - この設定は以下によって処理されます: + - `com.scalar.db.sql.springdata` 内のいくつかの Java クラス + - `@EnableScalarDbRepositories` アノテーション + - `resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` + - `resources/META-INF/spring.factories` + +## 参考文献 + +- [Spring Data JDBC - Reference Documentation](https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/) +- [ScalarDB JDBC ガイド](jdbc-guide.mdx) +- [Javadoc for Spring Data JDBC for ScalarDB](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-spring-data/3.15.4/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/sql-api-guide.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/sql-api-guide.mdx new file mode 100644 index 00000000..b8493ecf --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/scalardb-sql/sql-api-guide.mdx @@ -0,0 +1,383 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB SQL API ガイド + +import JavadocLink from '/src/theme/JavadocLink.js'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + +このガイドでは、ScalarDB SQL API の使用方法について説明します。 + +## プロジェクトに ScalarDB SQL API を追加する + +Gradle を使用して ScalarDB SQL API への依存関係を追加するには、次のコードを使用します。`` は、使用している ScalarDB SQL API と関連ライブラリのバージョンに置き換えてください。 + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql:' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:' +} +``` + +Maven を使用して依存関係を追加するには、以下を使用します (`...` を使用している ScalarDB SQL API のバージョンに置き換えます)。 + +```xml + + + com.scalar-labs + scalardb-sql + ... + + + com.scalar-labs + scalardb-cluster-java-client-sdk + ... + + +``` + +## SqlSessionFactory + +ScalarDB SQL API では、`SqlSessionFactory` でインスタンス化された `SqlSession` インスタンスを通じてすべての操作を実行します。このセクションでは、それらの使用方法を説明します。 + +`SqlSessionFactory` を説明する前に、接続モードとトランザクションモードについて説明します。 + +### トランザクションモード + +また、ScalarDB SQL には、*トランザクション* モードと*2フェーズコミットトランザクション*モードの2つのトランザクションモードがあります。 + +トランザクションモードでは、ユーザーには `commit` インターフェイスのみが公開され、バックグラウンドで2フェーズコミットが実行されます。一方、2フェーズコミットトランザクションモードでは、ユーザーに2フェーズコミットスタイルのインターフェイス (`prepare` と `commit`) が公開されます。 + +デフォルトのトランザクションモードは、設定ファイルで指定するか、`SqlSessionFactory` をビルドするときに指定できます。 + +また、`SqlSession` の `setTransactionMode()` メソッドを使用して変更することもできます。 + +### SqlSessionFactory をビルドする + +次のように、プロパティファイルを使用して `SqlSessionFactory` をビルドできます。 + +```java +SqlSessionFactory sqlSessionFactory = SqlSessionFactory.builder() + .withPropertiesFile("") + // If you need to set custom properties, you can specify them with withProperty() or withProperties() + .withProperty("", "") + .build(); +``` + +設定の詳細については、[ScalarDB Cluster SQL クライアント設定](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-クライアント設定)を参照してください。 + +### SqlSession インスタンスを取得する + +次のように、`SqlSessionFactory` を使用して `SqlSession` インスタンスを取得できます。 + +```java +SqlSession sqlSession = sqlSessionFactory.createSqlSession(); +``` + +`SqlSession` はスレッドセーフではないことに注意してください。 + +複数のスレッドから同時に使用しないでください。 + +#### SqlSession インスタンスを閉じる + +`SqlSession` インスタンスですべての操作が完了したら、SqlSession インスタンスを閉じる必要があります。 + +```java +sqlSession.close(); +``` + +### SqlSessionFactory インスタンスを閉じる + +`sqlSessionFactory` も、不要になったら閉じる必要があります。 + +```java +sqlSessionFactory.close(); +``` + +## SQL を実行する + +次のように `SqlSession` を使用して SQL を実行できます。 + +```java +ResultSet resultSet = sqlSession.execute(""); +``` + +次のように `SqlSession` を使用して `Statement` オブジェクトを実行することもできます。 + +```java +// Build a statement +Statement statement = StatementBuilder....; + +// Execute the statement +ResultSet resultSet = sqlSession.execute(statement); +``` + +`Statement` オブジェクトは、対応する SQL のファクトリメソッドを持つ `StatementBuilder` によって構築できます。詳細については、Javadoc の ページおよび [ScalarDB SQL 文法](grammar.mdx)を参照してください。 + +### ResultSet オブジェクトの処理 + +SQL 実行の結果として、`SqlSession` は `ResultSet` オブジェクトを返します。 + +ここでは、`ResultSet` オブジェクトの処理方法について説明します。 + +`ResultSet` オブジェクトから結果を1つずつ取得する場合は、次のように `one()` メソッドを使用できます。 +```java +Optional record = resultSet.one(); +``` + +または、すべての結果を `List` として一度に取得したい場合は、次のように `all()` メソッドを使用できます。 +```java +List records = resultSet.all(); +``` + +また、`ResultSet` は `Iterable` を実装しているので、次のように for-each ループで使用できます。 + +```java +for (Record record : resultSet) { + ... +} +``` + +`ResultSet` オブジェクトのメタデータを取得する場合は、次のように `getColumnDefinitions()` メソッドを使用できます。 + +```java +ColumnDefinitions columnDefinitions = resultSet.getColumnDefinitions(); +``` + +詳細については、Javadoc の ページを参照してください。 + +### Record オブジェクトの処理 + +前述のように、`ResultSet` オブジェクトは、データベースのレコードを表す `Record` オブジェクトを返します。 + +次のように、`getXXX("")` メソッドまたは `getXXX()` メソッド (XXX は型名) を使用して結果の列値を取得できます。 + +```java +// Get a BOOLEAN value of a column +boolean booleanValueGottenByName = record.getBoolean(""); +boolean booleanValueGottenByIndex = record.getBoolean(); + +// Get an INT value of a column +int intValueGottenByName = record.getInt(""); +int intValueGottenByIndex = record.getInt(); + +// Get a BIGINT value of a column +long bigIntValueGottenByName = record.getBigInt(""); +long bigIntValueGottenByIndex = record.getBigInt(); + +// Get a FLOAT value of a column +float floatValueGottenByName = record.getFloat(""); +float floatValueGottenByIndex = record.getFloat(); + +// Get a DOUBLE value of a column +double doubleValueGottenByName = record.getDouble(""); +double doubleValueGottenByIndex = record.getDouble(); + +// Get a TEXT value of a column +String textValueGottenByName = record.getText(""); +String textValueGottenByIndex = record.getText(); + +// Get a BLOB value of a column (as a ByteBuffer) +ByteBuffer blobValueGottenByName = record.getBlob(""); +ByteBuffer blobValueGottenByIndex = record.getBlob(); + +// Get a BLOB value of a column as a byte array +byte[] blobValueAsBytesGottenByName = record.getBlobAsBytes(""); +byte[] blobValueAsBytesGottenByIndex = record.getBlobAsBytes(); + +// Get a DATE value of a column as a LocalDate +LocalDate dateValueGottenByName = record.getDate(""); +LocalDate dateValueGottenByName = record.getDate(); + +// Get a TIME value of a column as a LocalTime +LocalTime timeValueGottenByName = record.getTime(""); +LocalTime timeValueGottenByName = record.getTime(); + +// Get a TIMESTAMP value of a column as a LocalDateTime +LocalDateTime timestampValueGottenByName = record.getTimestamp(""); +LocalDateTime timestampValueGottenByName = record.getTimestamp(); + +// Get a TIMESTAMPTZ value of a column as an Instant +Instant timestampTZValueGottenByName = record.getTimestampTZ(""); +Instant timestampTZValueGottenByName = record.getTimestampTZ(); +``` + +列の値が null かどうかを確認する必要がある場合は、`isNull("<列名>")` または `isNull(<列インデックス>)` メソッドを使用できます。 + +``` java +// Check if a value of a column is null +boolean isNullGottenByName = record.isNull(""); +boolean isNullGottenByIndex = record.isNull(); +``` + +詳細については、Javadoc の ページを参照してください。 + +### 準備済みステートメント + +アプリケーションで複数回実行されるクエリには、`PreparedStatement` を使用できます。 + +```java +PreparedStatement preparedStatement = sqlSession.prepareStatement(""); +ResultSet result = preparedStatement.execute(); +``` + +同じクエリを2回目以降に実行すると、キャッシュされた事前解析済みステートメントオブジェクトが使用されます。 +したがって、クエリを複数回実行すると、`PreparedStatement` を使用するとパフォーマンス上の利点が得られます。 +クエリを1回だけ実行する場合、準備済みステートメントは余分な処理が必要になるため非効率的です。 +その場合は、代わりに `sqlSession.execute()` メソッドの使用を検討してください。 + +また、バインドパラメータで `PreparedStatement` を使用することもできます。 +パラメータは、位置指定または名前付きのいずれかになります。 + +```java +// Positional parameters +PreparedStatement preparedStatement1 = + sqlSession.prepareStatement("INSERT INTO tbl (c1, c2) VALUES (?, ?)"); + +// Named parameters +PreparedStatement preparedStatement2 = + sqlSession.prepareStatement("INSERT INTO tbl (c1, c2) VALUES (:a, :b)"); +``` + +最初にパラメータを設定して実行することができます: + +```java +// Positional setters +preparedStatement1 + .setInt(0, 10) + .setText(1, "value") + .execute(); + +// Named setters +preparedStatement2 + .setInt("a", 10) + .setText("b", "value") + .execute(); +``` + +詳細については、Javadoc の ページを参照してください。 + +## トランザクションの実行 + +ScalarDB SQL では、DML ステートメント (SELECT/INSERT/UPDATE/DELETE) はトランザクション内でのみ実行できます。 + +したがって、DML ステートメントを実行する前に、トランザクションを開始する必要があります。 + +DML ステートメント以外のステートメントはトランザクションで実行できないことに注意してください。 + +したがって、トランザクションを開始した後に非 DML ステートメントを実行しても、そのステートメントはすぐに実行され、開始したトランザクションには影響しません。 + +このセクションでは、トランザクションモードと2フェーズコミットトランザクションモードの各トランザクションモードについて、トランザクションを実行する方法について説明します。 + +### トランザクションモード + +トランザクションモードのサンプルコードは次のとおりです。 + +```java +try { + // Begin a transaction + sqlSession.begin(); + + // Execute statements (SELECT/INSERT/UPDATE/DELETE) in the transaction + ... + + // Commit the transaction + sqlSession.commit(); +} catch (UnknownTransactionStatusException e) { + // If you catch `UnknownTransactionStatusException`, it indicates that the status of the + // transaction, whether it has succeeded or not, is unknown. In such a case, you need to check if + // the transaction is committed successfully or not and retry it if it failed. How to identify a + // transaction status is delegated to users +} catch (SqlException e) { + // For other exceptions, you can try retrying the transaction + + // Rollback the transaction + sqlSession.rollback(); + + // For `TransactionRetryableException`, you can basically retry the transaction. However, for + // the other exceptions, the transaction may still fail if the cause of the exception is + // nontransient. For such a case, you need to limit the number of retries and give up retrying +} +``` + +`UnknownTransactionStatusException` をキャッチした場合、トランザクションのステータス (成功したかどうか) が不明であることを示します。 +このような場合、トランザクションが正常にコミットされたかどうかを確認し、失敗した場合は再試行する必要があります。 +トランザクションステータスを識別する方法はユーザーに委任されています。 +トランザクションステータステーブルを作成し、他のアプリケーションデータを使用してトランザクション的に更新して、ステータステーブルからトランザクションのステータスを取得できるようにすることをお勧めします。 + +別の例外をキャッチした場合は、トランザクションを再試行することができます。 +`TransactionRetryableException` の場合、基本的にトランザクションを再試行することができます。 +ただし、他の例外の場合、例外の原因が一時的でない場合は、トランザクションが失敗する可能性があります。 +このような場合は、再試行回数を制限し、再試行をあきらめる必要があります。 + +### 2フェーズコミットトランザクションモード + +これを読む前に、[このドキュメント](../two-phase-commit-transactions.mdx) を読んで、2フェーズコミットトランザクションの概念を学んでください。 + +コーディネータのトランザクションを開始するには、次のようにします。 + +```java +String transactionId = sqlSession.begin(); +``` + +参加者のトランザクションに参加するには、次のようにします。 + +```java +sqlSession.join(transactionId); +``` + +2フェーズコミットトランザクションモードのコード例は次のとおりです。 + +```java +try { + // Begin a transaction + sqlSession.begin(); + + // Execute statements (SELECT/INSERT/UPDATE/DELETE) in the transaction + ... + + // Prepare the transaction + sqlSession.prepare(); + + // Validate the transaction + sqlSession.validate(); + + // Commit the transaction + sqlSession.commit(); +} catch (UnknownTransactionStatusException e) { + // If you catch `UnknownTransactionStatusException` when committing the transaction, it + // indicates that the status of the transaction, whether it has succeeded or not, is unknown. + // In such a case, you need to check if the transaction is committed successfully or not and + // retry it if it failed. How to identify a transaction status is delegated to users +} catch (SqlException e) { + // For other exceptions, you can try retrying the transaction + + // Rollback the transaction + sqlSession.rollback(); + + // For `TransactionRetryableException`, you can basically retry the transaction. However, for + // the other exceptions, the transaction may still fail if the cause of the exception is + // nontransient. For that case, you need to limit the number of retries and give up retrying +} +``` + +例外処理はトランザクションモードと同じです。 + +## メタデータの取得 + +次のように `SqlSession.getMetadata()` メソッドを使用してメタデータを取得できます。 + +```java +Metadata metadata = sqlSession.getMetadata(); +``` + +詳細については、Javadoc の ページを参照してください。 + +## 参考文献 + +- [ScalarDB SQL 文法](grammar.mdx) +- [2フェーズコミットトランザクション](../two-phase-commit-transactions.mdx) +- [Javadoc for ScalarDB SQL](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.15.4/index.html) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/schema-loader-import.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/schema-loader-import.mdx new file mode 100644 index 00000000..26d433c7 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/schema-loader-import.mdx @@ -0,0 +1,293 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +既存のデータベースで ScalarDB を使用したい場合があります (データベースにまたがるトランザクションなど)。その場合、ScalarDB Schema Loader を使用して、それらのデータベースを ScalarDB の制御下にインポートできます。ScalarDB Schema Loader は、既存の各テーブルとメタデータテーブルに ScalarDB 内部メタデータ列を自動的に追加し、複数のデータベースにわたるトランザクション管理などのさまざまな ScalarDB 機能を有効にします。 + +## 始める前に + +:::warning + +運用環境で ScalarDB にテーブルをインポートする場合は、データベーステーブルと ScalarDB メタデータテーブルにトランザクションメタデータ列が追加されるため、慎重に計画する必要があります。この場合、データベースと ScalarDB の間にはいくつかの違いがあり、いくつかの制限もあります。 + +::: + +### データベースに追加されるもの + +- **ScalarDB メタデータテーブル:** ScalarDB は、'scalardb' という名前空間 (基盤となるデータベースのスキーマまたはデータベース) で名前空間名とテーブルメタデータを管理します。 +- **トランザクションメタデータ列:** Consensus Commit トランザクションマネージャーでは、トランザクションを適切に処理するために、実際のレコードとともに保存されたメタデータ (トランザクション ID、レコードバージョン、トランザクションステータスなど) が必要です。したがって、Consensus Commit トランザクションマネージャーを使用する場合、このツールはメタデータ列を追加します。 + +:::note + +このツールはデータベースのメタデータのみを変更します。そのため、処理時間はデータベースのサイズに比例して増加することはなく、通常は数秒しかかかりません。 + +::: + +### 要件 + +- SQLite を除く [JDBC データベース](./requirements.mdx#リレーショナルデータベース)をインポートできます。 +- 各テーブルにはプライマリーキー列が必要です。(複合プライマリーキーを使用できます。) +- ターゲットテーブルには、サポートされているデータ型の列のみが必要です。詳細については、[JDBC データベースから ScalarDB へのデータ型マッピング](#jdbc-データベースから-scalardb-へのデータ型マッピング))を参照してください。 + +### Schema Loader の設定 + +既存のテーブルをインポートするために Schema Loader を設定するには、[Schema Loader を設定する](./schema-loader.mdx#schema-loader-を設定する)を参照してください。 + +## 既存のテーブルをインポートするために Schema Loader を実行する + +`--import` オプションとインポート固有のスキーマファイルを使用して、JDBC データベース内の既存のテーブルを ScalarDB にインポートできます。テーブルをインポートするには、次のコマンドを実行し、山括弧内の内容を説明に従って置き換えます。 + +```console +java -jar scalardb-schema-loader-.jar --config -f --import +``` + +- ``: 設定した ScalarDB Schema Loader のバージョン。 +- ``: ScalarDB のプロパティファイルへのパス。サンプルのプロパティファイルについては、[`database.properties`](https://github.com/scalar-labs/scalardb/blob/master/conf/database.properties) を参照してください。 +- ``: インポートスキーマファイルへのパス。サンプルについては、[サンプルインポートスキーマファイル](#サンプルインポートスキーマファイル)を参照してください。 + +既存のテーブルをインポートした後に Consensus Commit トランザクションマネージャーを使用する場合は、次のコマンドを個別に実行し、説明に従って山括弧内の内容を置き換えます。 + +```console +java -jar scalardb-schema-loader-.jar --config --coordinator +``` + +## サンプルインポートスキーマファイル + +以下は、テーブルをインポートするためのサンプルスキーマです。サンプルスキーマファイルについては、[`import_schema_sample.json`](https://github.com/scalar-labs/scalardb/blob/master/schema-loader/sample/import_schema_sample.json) を参照してください。 + +```json +{ + "sample_namespace1.sample_table1": { + "transaction": true, + "override-columns-type": { + "c3": "TIME", + "c5": "TIMESTAMP" + } + }, + "sample_namespace1.sample_table2": { + "transaction": true + }, + "sample_namespace2.sample_table3": { + "transaction": false + } +} +``` + +インポートテーブルスキーマは、名前空間名、テーブル名、`transaction` フィールド、及び `override-columns-type` 任意フィルドで設定されます: +- `transaction` フィールドは、テーブルがトランザクション用にインポートされるかどうかを示します。`transaction` フィールドを `true` に設定するか、`transaction` フィールドを指定しない場合、このツールは必要に応じてトランザクションメタデータを含むテーブルを作成します。`transaction` フィールドを `false` に設定すると、このツールはトランザクションメタデータを追加せずにテーブルをインポートします (つまり、[Storage API](run-non-transactional-storage-operations-through-primitive-crud-interface.mdx) を使用するテーブルの場合)。 +- `override-columns-type` フィールドは、デフォルトのデータ型マッピングをオーバーライドする列を示します。このフィールドは任意であり、型のオーバーライドが必要な列でのみ設定する必要があります。 + +## JDBC データベースから ScalarDB へのデータ型マッピング + +次の表は、各 JDBC データベースでサポートされているデータ型と、それらの ScalarDB データ型へのマッピングを示しています。データベースを選択し、既存のテーブルをインポートできるかどうかを確認してください。 + + + + | MySQL | ScalarDB | 注記 | + |--------------|-------------------------------------|---------------------------------------------------------------------------------------------------------------------| + | bigint | BIGINT | 下記の警告 [1](#1) を参照してください。 | + | binary | BLOB | | + | bit | BOOLEAN | | + | blob | BLOB | 下記の警告 [2](#2) を参照してください。 | + | char | TEXT | 下記の警告 [2](#2) を参照してください。 | + | date | DATE | | + | datetime | TIMESTAMP (デフォルト)、TIMESTAMPTZ | TIMESTAMPTZ としてインポートする場合、ScalarDB はデータが UTC タイムゾーンにあると想定します。下記の警告 [6](#6) を参照してください。 | + | double | DOUBLE | | + | float | FLOAT | | + | int | INT | | + | int unsigned | BIGINT | 下記の警告 [2](#2) を参照してください。 | + | integer | INT | | + | longblob | BLOB | | + | longtext | TEXT | | + | mediumblob | BLOB | 下記の警告 [2](#2) を参照してください。 | + | mediumint | INT | 下記の警告 [2](#2) を参照してください。 | + | mediumtext | TEXT | 下記の警告 [2](#2) を参照してください。 | + | smallint | INT | 下記の警告 [2](#2) を参照してください。 | + | text | TEXT | 下記の警告 [2](#2) を参照してください。 | + | time | TIME | | + | timestamp | TIMESTAMPTZ | | + | tinyblob | BLOB | 下記の警告 [2](#2) を参照してください。 | + | tinyint | INT | 下記の警告 [2](#2) を参照してください。 | + | tinyint(1) | BOOLEAN | | + | tinytext | TEXT | 下記の警告 [2](#2) を参照してください。 | + | varbinary | BLOB | 下記の警告 [2](#2) を参照してください。 | + | varchar | TEXT | 下記の警告 [2](#2) を参照してください。 | + + 上記に記載されていないデータ型はサポートされていません。サポートされていない一般的なデータ型は次のとおりです。 + + - bigint unsigned + - bit(n) (n > 1) + - decimal + - enum + - geometry + - json + - numeric + - set + - year + + + | PostgreSQL/YugabyteDB | ScalarDB | 注記 | + |--------------------------|-------------|-----------------------------------| + | bigint | BIGINT | 下記の警告 [1](#1) を参照してください。| + | boolean | BOOLEAN | | + | bytea | BLOB | | + | character | TEXT | 下記の警告 [2](#2) を参照してください。| + | character varying | TEXT | 下記の警告 [2](#2) を参照してください。| + | date | DATE | | + | double precision | DOUBLE | | + | integer | INT | | + | real | FLOAT | | + | smallint | INT | 下記の警告 [2](#2) を参照してください。| + | text | TEXT | | + | time | TIME | | + | timestamp | TIMESTAMP | | + | timestamp with time zone | TIMESTAMPTZ | | + + 上記に記載されていないデータ型はサポートされていません。サポートされていない一般的なデータ型は次のとおりです。 + + - bigserial + - bit + - box + - cidr + - circle + - inet + - interval + - json + - jsonb + - line + - lseg + - macaddr + - macaddr8 + - money + - numeric + - path + - pg_lsn + - pg_snapshot + - point + - polygon + - smallserial + - serial + - time with time zone + - tsquery + - tsvector + - txid_snapshot + - uuid + - xml + + + +| Oracle | ScalarDB | 注記 | +|--------------------------------|-----------------------------------|-------------------------------------| +| binary_double | DOUBLE | | +| binary_float | FLOAT | | +| blob | BLOB | 下記の警告 [3](#3) を参照してください。 | +| char | TEXT | 下記の警告 [2](#2) を参照してください。 | +| clob | TEXT | | +| date | DATE(デフォルト)、TIME、TIMESTAMP | 下記の警告 [6](#6) を参照してください。 | +| float | DOUBLE | 下記の警告 [4](#4) を参照してください。 | +| long | TEXT | | +| long raw | BLOB | | +| nchar | TEXT | 下記の警告 [2](#2) を参照してください。 | +| nclob | TEXT | | +| number | BIGINT / DOUBLE | 下記の警告 [5](#5) を参照してください。 | +| nvarchar2 | TEXT | 下記の警告 [2](#2) を参照してください。 | +| raw | BLOB | 下記の警告 [2](#2) を参照してください。 | +| timestamp | TIMESTAMP (デフォルト)、TIME | 下記の警告 [6](#6) を参照してください。 | +| timestamp with time zone | TIMESTAMPTZ | | +| timestamp with local time zone | TIMESTAMPTZ | | +| varchar2 | TEXT | 下記の警告 [2](#2) を参照してください。 | + + 上記に記載されていないデータ型はサポートされていません。サポートされていない一般的なデータ型は次のとおりです。 + + - interval + - rowid + - urowid + - bfile + - json + + + | SQL Server | ScalarDB | 注記 | + |----------------|-------------|------------------------------------| + | bigint | BIGINT | 下記の警告 [1](#1) を参照してください。 | + | binary | BLOB | 下記の警告 [2](#2) を参照してください。 | + | bit | BOOLEAN | | + | char | TEXT | 下記の警告 [2](#2) を参照してください。 | + | date | DATE | | + | datetime | TIMESTAMP | | + | datetime2 | TIMESTAMP | | + | float | DOUBLE | | + | image | BLOB | | + | int | INT | | + | nchar | TEXT | 下記の警告 [2](#2) を参照してください。 | + | ntext | TEXT | | + | nvarchar | TEXT | 下記の警告 [2](#2) を参照してください。 | + | offsetdatetime | TIMESTAMPTZ | | + | real | FLOAT | | + | smalldatetime | TIMESTAMP | | + | smallint | INT | 下記の警告 [2](#2) を参照してください。 | + | text | TEXT | | + | time | TIME | | + | tinyint | INT | 下記の警告 [2](#2) を参照してください。 | + | varbinary | BLOB | 下記の警告 [2](#2) を参照してください。 | + | varchar | TEXT | 下記の警告 [2](#2) を参照してください。 | + + 上記に記載されていないデータ型はサポートされていません。サポートされていない一般的なデータ型は次のとおりです。 + + - cursor + - decimal + - geography + - geometry + - hierarchyid + - money + - numeric + - rowversion + - smallmoney + - sql_variant + - uniqueidentifier + - xml + + + +:::warning + +
    +
  1. + ScalarDB の `BIGINT` の値の範囲は、基礎となるデータベースの `bigint` のサイズに関係なく、-2^53から2^53です。したがって、インポートされたテーブルにこの範囲外のデータが存在する場合、ScalarDB はそれを読み取ることができません。 +
  2. +
  3. + 上記の特定のデータ型の場合、ScalarDB は基になるデータベースのデータ型よりも大きいデータ型をマップする場合があります。その場合、基になるデータベースで指定されたサイズよりも大きいサイズの値を入力するとエラーが表示されます。 +
  4. +
  5. + ScalarDB の `BLOB` の最大サイズは約 2GB (正確には2^31-1バイト) です。対照的に、Oracle の `blob` は (4GB-1)*(ブロック数) を持つことができます。したがって、インポートされたテーブルに 2GB を超えるデータが存在する場合、ScalarDB はそれを読み取ることができません。 +
  6. +
  7. + ScalarDB は、ScalarDB の `DOUBLE` よりも精度の高い Oracle `float` 列をサポートしていません。 +
  8. +
  9. + ScalarDB では、ScalarDB のデータ型の最大サイズにより、`p` が15より大きい場合、Oracle の `numeric(p, s)` 列 (`p` は精度、`s` はスケール) をサポートしません。`s` が0の場合、ScalarDB は列を `BIGINT` にマッピングします。それ以外の場合は、ScalarDB は列を `DOUBLE` にマッピングします。後者の場合、浮動小数点値が固定小数点値にキャストされるため、基になるデータベースで切り上げまたは切り捨てが発生する可能性があることに注意してください。 +
  10. +
  11. + 基盤となるデータベースデータ型は、いくつかの ScalarDB データ型にマップできます。デフォルトのマッピングをオーバーライドするには、インポートスキーマファイルの `override-columns-type` フィールドを使用します。例については、[サンプルインポートスキーマファイル](#サンプルインポートスキーマファイル)を参照してください。 +
  12. +
+ +::: + +## アプリケーションでインポート機能を使用する + +次のインターフェースを使用して、アプリケーションでインポート機能を使用できます。 + +- [ScalarDB Admin API](./api-guide.mdx#テーブルをインポートする) +- [ScalarDB Schema Loader API](./schema-loader.mdx#アプリケーションで-schema-loader-を使用する) diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/schema-loader.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/schema-loader.mdx new file mode 100644 index 00000000..181bcba2 --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/schema-loader.mdx @@ -0,0 +1,729 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# ScalarDB Schema Loader + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB には、実装固有のデータモデルとスキーマにマップされる独自のデータモデルとスキーマがあります。 さらに、ScalarDB は、Consensus Commit トランザクションマネージャーを使用するときにトランザクションログとステータスを管理するために、トランザクション ID、レコードバージョン、トランザクションステータスなどの内部メタデータを保存します。 + +トランザクションのスキーママッピングとメタデータの管理は難しい場合があるため、スキーママッピングやメタデータに関する詳細な知識を必要としないスキーマ作成ツールである ScalarDB Schema Loader を使用できます。 + +Schema Loader で一般的な CLI オプションを指定するには、次の2つのオプションがあります。 + +- ScalarDB プロパティファイルとデータベース固有またはストレージ固有のオプションを渡します。 +- ScalarDB プロパティファイルなしでデータベース固有またはストレージ固有のオプションを渡します。(非推奨) + +:::note + +このツールは、テーブルの作成、削除、修復、または変更を行うための基本的なオプションのみをサポートしています。データベースの高度な機能を使用する場合は、このツールでテーブルを作成した後、データベース固有のツールを使用してテーブルを変更する必要があります。 + +::: + +## Schema Loader を設定する + +希望する方法を選択して Schema Loader を設定し、指示に従います。 + + + + Schema Loader のリリースバージョンは、[ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) ページからダウンロードできます。 + + + 次のコマンドを実行し、山括弧内の内容を説明に従って置き換えることで、[Scalar コンテナーレジストリ](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-schema-loader) から Docker イメージをプルできます。 + + ```console + docker run --rm -v : [-v :] ghcr.io/scalar-labs/scalardb-schema-loader: + ``` + +:::note + +fat JAR やコンテナを使用する場合でも、同じコマンド引数を指定できます。[利用可能なコマンド](#利用可能なコマンド)セクションでは JAR が使用されていますが、`java -jar scalardb-schema-loader-.jar` を `docker run --rm -v : [-v :] ghcr.io/scalar-labs/scalardb-schema-loader:` に置き換えることで、コンテナを使用して同様にコマンドを実行できます。 + +::: + + + +## Schema Loader を実行する + +このセクションでは、Schema Loader を実行する方法について説明します。 + +### 利用可能なコマンド + +データベースの Schema Loader を設定する方法を選択します。他のデータベース固有の方法は非推奨であるため、プロパティファイルを使用することをお勧めします。 + +プロパティファイルを使用する場合、次のコマンドを使用できます。 + +```console +Usage: java -jar scalardb-schema-loader-.jar [-D] [--coordinator] + [--no-backup] [--no-scaling] -c= + [--compaction-strategy=] [-f=] + [--replication-factor=] + [--replication-strategy=] [--ru=] +Create/Delete schemas in the storage defined in the config file + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -c, --config= + Path to the config file of ScalarDB + --compaction-strategy= + The compaction strategy, must be LCS, STCS or TWCS + (supported in Cassandra) + --coordinator Create/delete/repair Coordinator tables + -D, --delete-all Delete tables + -f, --schema-file= + -I, --import Import tables : it will import existing non-ScalarDB + tables to ScalarDB. + Path to the schema json file + --no-backup Disable continuous backup (supported in DynamoDB) + --no-scaling Disable auto-scaling (supported in DynamoDB, Cosmos DB) + --repair-all Repair namespaces and tables that are in an unknown + state: it re-creates namespaces, tables, secondary + indexes, and their metadata if necessary. + --replication-factor= + The replication factor (supported in Cassandra) + --replication-strategy= + The replication strategy, must be SimpleStrategy or + NetworkTopologyStrategy (supported in Cassandra) + --ru= Base resource unit (supported in DynamoDB, Cosmos DB) + --upgrade Upgrades the ScalarDB environment to support the latest + version of the ScalarDB API. Typically, as indicated in + the release notes, you will need to run this command + after updating the ScalarDB version that your + application environment uses. + +``` + +サンプルのプロパティファイルについては、[`database.properties`](https://github.com/scalar-labs/scalardb/blob/master/conf/database.properties) を参照してください。 + +:::note + +次のデータベース固有のメソッドは非推奨になりました。代わりに、[プロパティファイルを設定するためのコマンド](#利用可能なコマンド)を使用してください。 + + + + ```console + Usage: java -jar scalardb-schema-loader-.jar --jdbc [-D] + -f= -j= -p= -u= + Create/Delete JDBC schemas + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -D, --delete-all Delete tables + -f, --schema-file= + Path to the schema json file + -j, --jdbc-url= JDBC URL + -p, --password= + JDBC password + --repair-all Repair tables : it repairs the table metadata of + existing tables + -u, --user= JDBC user + ``` + + + ```console + Usage: java -jar scalardb-schema-loader-.jar --dynamo [-D] + [--no-backup] [--no-scaling] [--endpoint-override=] + -f= -p= [-r=] --region= + -u= + Create/Delete DynamoDB schemas + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -D, --delete-all Delete tables + --endpoint-override= + Endpoint with which the DynamoDB SDK should + communicate + -f, --schema-file= + Path to the schema json file + --no-backup Disable continuous backup for DynamoDB + --no-scaling Disable auto-scaling for DynamoDB + -p, --password= AWS access secret key + -r, --ru= Base resource unit + --region= AWS region + --repair-all Repair tables : it repairs the table metadata of + existing tables + -u, --user= AWS access key ID + ``` + + + ```console + Usage: java -jar scalardb-schema-loader-.jar --cosmos [-D] + [--no-scaling] -f= -h= -p= [-r=] + Create/Delete Cosmos DB schemas + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -D, --delete-all Delete tables + -f, --schema-file= + Path to the schema json file + -h, --host= Cosmos DB account URI + --no-scaling Disable auto-scaling for Cosmos DB + -p, --password= Cosmos DB key + -r, --ru= Base resource unit + --repair-all Repair tables : it repairs the table metadata of + existing tables and repairs stored procedure + attached to each table + ``` + + + ```console + Usage: java -jar scalardb-schema-loader-.jar --cassandra [-D] + [-c=] -f= -h= + [-n=] [-p=] [-P=] + [-R=] [-u=] + Create/Delete Cassandra schemas + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -c, --compaction-strategy= + Cassandra compaction strategy, must be LCS, STCS or TWCS + -D, --delete-all Delete tables + -f, --schema-file= + Path to the schema json file + -h, --host= Cassandra host IP + -n, --network-strategy= + Cassandra network strategy, must be SimpleStrategy or + NetworkTopologyStrategy + -p, --password= + Cassandra password + -P, --port= Cassandra Port + -R, --replication-factor= + Cassandra replication factor + --repair-all Repair tables : it repairs the table metadata of + existing tables + -u, --user= Cassandra user + ``` + + + +::: + +### 名前空間とテーブルを作成する + +プロパティファイルを使用して名前空間とテーブルを作成するには、山括弧内の内容を説明に従って置き換えて、次のコマンドを実行します。 + +```console +java -jar scalardb-schema-loader-.jar --config -f [--coordinator] +``` + +`--coordinator` が指定されている場合は、[Coordinator テーブル](api-guide.mdx#coordinator-テーブルの操作を指定する)が作成されます。 + +:::note + +次のデータベース固有の CLI 引数は非推奨になりました。代わりに、プロパティファイルを設定するための CLI 引数を使用してください。 + + + + ```console + java -jar scalardb-schema-loader-.jar --jdbc -j -u -p -f + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --dynamo -u -p --region -f [-r BASE_RESOURCE_UNIT] + ``` + + - `` は、`ap-northeast-1` のような AWS リージョンを指定する文字列である必要があります。 + - `-r` オプションは、Cosmos DB for NoSQL オプションとほぼ同じです。ただし、単位は DynamoDB の容量単位を意味します。読み取りおよび書き込み容量単位は同じ値に設定されます。 + + + ```console + java -jar scalardb-schema-loader-.jar --cosmos -h -p -f [-r BASE_RESOURCE_UNIT] + ``` + + - `` では、主キーまたはセカンダリキーを使用できます。 + - `-r BASE_RESOURCE_UNIT` はオプションです。各データベースの RU を指定できます。データベース内のテーブルの最大 RU が設定されます。テーブルの RU を指定しない場合は、このオプションでデータベース RU が設定されます。デフォルトでは400です。 + + + ```console + java -jar scalardb-schema-loader-.jar --cassandra -h [-P ] [-u ] [-p ] -f [-n ] [-R ] + ``` + + - `-P ` が指定されていない場合、デフォルトで `9042` になります。 + - `-u ` が指定されていない場合、デフォルトで `cassandra` になります。 + - `-p ` が指定されていない場合、デフォルトで `cassandra` になります。 + - `` は `SimpleStrategy` または `NetworkTopologyStrategy` にする必要があります。 + + + +::: + +### テーブルの変更 + +コマンドを使用して、既存のテーブルに新しい列を追加したり、セカンダリインデックスを作成または削除したりできます。このコマンドは、指定されたテーブルスキーマを既存のスキーマと比較し、追加する必要がある列と作成または削除する必要があるインデックスを決定します。 + +既存のテーブルに新しい列を追加したり、セカンダリインデックスを作成または削除したりするには、次のコマンドを実行し、山括弧内の内容を説明に従って置き換えます。 + +```console +java -jar scalardb-schema-loader-.jar --config -f --alter +``` + +:::note + +次のデータベース固有の CLI 引数は非推奨になりました。代わりに、プロパティファイルを設定するための CLI 引数を使用してください。 + + + + ```console + java -jar scalardb-schema-loader-.jar --jdbc -j -u -p -f --alter + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --dynamo -u -p --region -f --alter + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cosmos -h -p -f --alter + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cassandra -h [-P ] [-u ] [-p ] -f --alter + ``` + + + +::: + +### テーブルの削除 + +プロパティファイルを使用してテーブルを削除できます。テーブルを削除するには、次のコマンドを実行し、山括弧内の内容を説明に従って置き換えます。 + +```console +java -jar scalardb-schema-loader-.jar --config -f [--coordinator] -D +``` + +`--coordinator` が指定されている場合は、Coordinator テーブルも削除されます。 + +:::note + +次のデータベース固有の CLI 引数は非推奨になりました。代わりに、プロパティファイルを設定するための CLI 引数を使用してください。 + + + + ```console + java -jar scalardb-schema-loader-.jar --jdbc -j -u -p -f -D + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --dynamo -u -p --region -f -D + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cosmos -h -p -f -D + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cassandra -h [-P ] [-u ] [-p ] -f -D + ``` + + + +::: + +### 名前空間とテーブルを修復する + +プロパティファイルを使用して、名前空間とテーブルを修復できます。名前空間とテーブルを修復する理由は、名前空間またはテーブルが基盤となるストレージに存在するが、その ScalarDB メタデータが存在しない、またはその逆など、それらが不明な状態になる可能性があるためです。名前空間、テーブル、セカンダリインデックス、およびそれらのメタデータを修復するには、必要に応じてそれらを再作成する必要があります。それらを修復するには、次のコマンドを実行し、説明されているように山括弧内の内容を置き換えます。 + +```console +java -jar scalardb-schema-loader-.jar --config -f [--coordinator] --repair-all +``` + +:::warning + +このコマンドを実行する前に、スキーマ設定が最後に適用されたものと同じであることを確認する必要があります。 + +::: + +`--coordinator` が指定されている場合は、Coordinator テーブルも修復されます。また、Cosmos DB for NoSQL を使用している場合は、このコマンドを実行すると、各テーブルにアタッチされているストアドプロシージャも修復されます。 + +:::note + +次のデータベース固有の CLI 引数は非推奨になりました。代わりに、プロパティファイルを設定するための CLI 引数を使用してください。 + + + + ```console + java -jar scalardb-schema-loader-.jar --jdbc -j -u -p -f --repair-all + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --dynamo -u -p --region [--no-backup] -f --repair-all + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cosmos -h -p -f --repair-all + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cassandra -h [-P ] [-u ] [-p ] -f --repair-all + ``` + + + +::: + +### テーブルのインポート + +`--import` オプションとインポート固有のスキーマファイルを使用して、JDBC データベース内の既存のテーブルを ScalarDB にインポートできます。詳細については、[ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](./schema-loader-import.mdx)を参照してください。 + +### 環境をアップグレードして最新の ScalarDB API をサポートする + +ScalarDB 環境をアップグレードして、最新バージョンの ScalarDB API をサポートすることができます。通常、リリースノートに記載されているように、アプリケーション環境で使用する ScalarDB バージョンを更新した後、このコマンドを実行する必要があります。次のコマンドを実行するときは、説明されているように山括弧内の内容を必ず置き換えてください。 + +```console +java -jar scalardb-schema-loader-.jar --config --upgrade +``` + +### サンプルスキーマファイル + +以下はサンプルスキーマです。サンプルスキーマファイルについては、[`schema_sample.json`](https://github.com/scalar-labs/scalardb/blob/master/schema-loader/sample/schema_sample.json) を参照してください。 + +```json +{ + "sample_db.sample_table": { + "transaction": false, + "partition-key": [ + "c1" + ], + "clustering-key": [ + "c4 ASC", + "c6 DESC" + ], + "columns": { + "c1": "INT", + "c2": "TEXT", + "c3": "BLOB", + "c4": "INT", + "c5": "BOOLEAN", + "c6": "INT" + }, + "secondary-index": [ + "c2", + "c4" + ] + }, + + "sample_db.sample_table1": { + "transaction": true, + "partition-key": [ + "c1" + ], + "clustering-key": [ + "c4" + ], + "columns": { + "c1": "INT", + "c2": "TEXT", + "c3": "INT", + "c4": "INT", + "c5": "BOOLEAN" + } + }, + + "sample_db.sample_table2": { + "transaction": false, + "partition-key": [ + "c1" + ], + "clustering-key": [ + "c4", + "c3" + ], + "columns": { + "c1": "INT", + "c2": "TEXT", + "c3": "INT", + "c4": "INT", + "c5": "BOOLEAN" + } + } +} +``` + +スキーマには、`columns`、`partition-key`、`clustering-key`、`secondary-index`、および `transaction` フィールドを含むテーブル定義があります。 + +- `columns` フィールドは、テーブルの列とそのデータ型を定義します。 +- `partition-key` フィールドは、パーティションキーがどの列で設定されているかを定義します。 +- `clustering-key` フィールドは、クラスタリングキーがどの列で設定されているかを定義します。 +- `secondary-index` フィールドは、インデックスが付けられる列を定義します。 +- `transaction` フィールドは、テーブルがトランザクション用かどうかを示します。 + - `transaction` フィールドを `true` に設定するか、`transaction` フィールドを指定しない場合、このツールは必要に応じてトランザクションメタデータを含むテーブルを作成します。 + - `transaction` フィールドを `false` に設定すると、このツールはトランザクションメタデータのないテーブルを作成します (つまり、[Storage API](run-non-transactional-storage-operations-through-primitive-crud-interface.mdx) を含むテーブルの場合)。 + +次のように、テーブル定義でデータベースまたはストレージ固有のオプションを指定することもできます。 + +```json +{ + "sample_db.sample_table3": { + "partition-key": [ + "c1" + ], + "columns": { + "c1": "INT", + "c2": "TEXT", + "c3": "BLOB" + }, + "compaction-strategy": "LCS", + "ru": 5000 + } +} +``` + +指定できるデータベースまたはストレージ固有のオプションは次のとおりです。 + + + + JDBC データベースには使用できるオプションはありません。 + + + `ru` オプションはリクエストユニットを表します。詳細については、[RUs](#rus) を参照してください。 + + + `ru` オプションはリクエストユニットを表します。詳細については、[RUs](#rus) を参照してください。 + + + `compaction-strategy` オプションは、使用される圧縮戦略です。このオプションは、`STCS` (SizeTieredCompaction)、`LCS` (LeveledCompactionStrategy)、または `TWCS` (TimeWindowCompactionStrategy) である必要があります。 + + + +## Cosmos DB for NoSQL または DynamoDB を使用する場合のパフォーマンスのスケーリング + +Cosmos DB for NoSQL または DynamoDB を使用する場合、リクエストユニット (RU) または自動スケーリングを使用してスケーリングできます。 + +### RU + +`--ru` オプションを指定すると、Cosmos DB for NoSQL および DynamoDB のスループットをスケーリングできます。このオプションを指定すると、スケーリングはすべてのテーブルまたは各テーブルの `ru` パラメータに適用されます。 + +`--ru` オプションが設定されていない場合、デフォルト値は Cosmos DB for NoSQL の場合は `400`、DynamoDB の場合は `10` になります。 + +:::note + +- Schema Loader は、Cosmos DB for NoSQL の[要求ユニット](https://learn.microsoft.com/ja-jp/azure/cosmos-db/request-units)と DynamoDB の[容量ユニット](https://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/capacity-mode.html#HowItWorks.ProvisionedThroughput.Manual)を `RU` で抽象化します。そのため、データベースの実装に応じて適切な値を設定してください。 +- Schema Loader は、DynamoDB の読み取り容量ユニットと書き込み容量ユニットの両方に同じ値を設定することに注意してください。 + +::: + +### 自動スケーリング + +デフォルトでは、Schema Loader はすべてのテーブルに対して RU の自動スケーリングを有効にします。RU は、ワークロードに応じて、指定された RU の 10% から 100% の間でスケーリングされます。たとえば、`-r 10000` を指定すると、各テーブルの RU は `1000` から `10000` の間で自動スケーリングされます。 + +:::note + +Cosmos DB for NoSQL の自動スケーリングは、このオプションが `4000` 以上に設定されている場合にのみ有効になります。 + +::: + +## ScalarDB と他のデータベース間のデータ型マッピング + +次の表は、ScalarDB でサポートされているデータ型と、他のデータベースのデータ型へのマッピングを示しています。 + +| ScalarDB | Cassandra | Cosmos DB for NoSQL | DynamoDB | MySQL/MariaDB | PostgreSQL/YugabyteDB | Oracle | SQL Server | SQLite | +|-------------|------------------------------|---------------------|----------|---------------|--------------------------|--------------------------|-----------------|---------| +| BOOLEAN | boolean | boolean (JSON) | BOOL | boolean | boolean | number(1) | bit | boolean | +| INT | int | number (JSON) | N | int | int | number(10) | int | int | +| BIGINT | bigint | number (JSON) | N | bigint | bigint | number(16) | bigint | bigint | +| FLOAT | float | number (JSON) | N | real | real | binary_float | float(24) | float | +| DOUBLE | double | number (JSON) | N | double | double precision | binary_double | float | double | +| TEXT | text | string (JSON) | S | longtext | text | varchar2(4000) | varchar(8000) | text | +| BLOB | blob | string (JSON) | B | longblob | bytea | RAW(2000) | varbinary(8000) | blob | +| DATE | date | number (JSON) | N | date | date | date | date | int | +| TIME | time | number (JSON) | N | time | time | timestamp | time | bigint | +| TIMESTAMP | サポートされていません | number (JSON) | N | datetime | timestamp | timestamp | datetime2 | bigint | +| TIMESTAMPTZ | timestamp | number (JSON) | N | datetime | timestamp with time zone | timestamp with time zone | datetimeoffset | bigint | + +:::note + +TIMESTAMP はタイムゾーン情報のない日付と時刻を表しますが、TIMESTAMPTZ は UTC タイムゾーンの日付と時刻を表します。 + +::: + +ただし、JDBC データベースの次のデータ型は、主キーまたはセカンダリインデックスキーとして使用される場合、異なる方法で変換されます。これは、RDB データ型の制限によるものです。MySQL および Oracle の場合、キー列の合計サイズの制限を満たす限り、列サイズ (最小 64 バイト) を変更できます。詳細については、[基盤となるストレージまたはデータベースの設定](configurations.mdx#基盤となるストレージまたはデータベースの設定) を参照してください。 + +| ScalarDB | MySQL/MariaDB | PostgreSQL/YugabyteDB | Oracle | +|----------|----------------|-----------------------|---------------| +| TEXT | VARCHAR(128) | VARCHAR(10485760) | VARCHAR2(128) | +| BLOB | VARBINARY(128) | | RAW(128) | + +次のデータ型には、基盤になるデータベースに関係なく、値の範囲と精度があります。 + +| データ型 | 最小限 | 最大限 | 精度 | +|--------------|---------------------------|---------------------------|---------------| +| BIGINT | -2^53 | 2^53 | - | +| DATE | 1000-01-01 | 9999-12-31 | 1 日 | +| TIME | 00:00:00.000000 | 23:59:59.999999 | 1 マイクロ秒 | +| TIMESTAMP | 1000-01-01 00:00:00.000 | 9999-12-31 23:59:59.999 | 1 ミリ秒 | +| TIMESTAMPTZ | 1000-01-01 00:00:00.000 Z | 9999-12-31 23:59:59.999 Z | 1 ミリ秒 | + +:::note + +YugabyteDB には、浮動小数点型 (FLOAT および DOUBLE) が主キー、クラスタリングキー、またはセカンダリインデックスキーとして正しく機能しないという制限があります。 + +::: + +このデータ型マッピングがアプリケーションと一致しない場合は、このツールを使用してテーブルを作成した後、テーブルを変更してデータ型を変更してください。 + +## Consensus Commit の内部メタデータ + +Consensus Commit トランザクションマネージャーは、トランザクションを適切に処理するために、実際のレコードとともに保存されるメタデータ (トランザクション ID、レコードバージョン、トランザクションステータスなど) を管理します。 + +したがって、アプリケーションに必要な列とともに、メタデータ用の追加列をスキーマに定義する必要があります。さらに、Consensus Commit トランザクションマネージャーを使用する場合、このツールはメタデータを含むテーブルを作成します。 + +## アプリケーションで Schema Loader を使用する + +[Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-schema-loader) から Schema Loader のバージョンを確認できます。たとえば、Gradle では、`build.gradle` ファイルに次の依存関係を追加し、`` を使用する Schema Loader のバージョンに置き換えます。 + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-schema-loader:' +} +``` + +### 使用例 + +`SchemaLoader` クラスを使用すると、CLI と同じコマンドを実行できます。 + +- スキーマで定義されているテーブルを作成、変更、削除、または修復するには、必要に応じて ScalarDB プロパティファイル、スキーマ、および追加のオプションを渡すことができます。 +- 環境をアップグレードするには、必要に応じて ScalarDB プロパティと追加のオプションを渡すことができます。 + +```java +public class SchemaLoaderSample { + public static int main(String... args) throws SchemaLoaderException { + Path configFilePath = Paths.get("database.properties"); + // "sample_schema.json" and "altered_sample_schema.json" can be found in the "/sample" directory. + Path schemaFilePath = Paths.get("sample_schema.json"); + Path alteredSchemaFilePath = Paths.get("altered_sample_schema.json"); + boolean createCoordinatorTables = true; // whether to create the Coordinator table or not + boolean deleteCoordinatorTables = true; // whether to delete the Coordinator table or not + boolean repairCoordinatorTables = true; // whether to repair the Coordinator table or not + + Map tableCreationOptions = new HashMap<>(); + + tableCreationOptions.put( + CassandraAdmin.REPLICATION_STRATEGY, ReplicationStrategy.SIMPLE_STRATEGY.toString()); + tableCreationOptions.put(CassandraAdmin.COMPACTION_STRATEGY, CompactionStrategy.LCS.toString()); + tableCreationOptions.put(CassandraAdmin.REPLICATION_FACTOR, "1"); + + tableCreationOptions.put(DynamoAdmin.REQUEST_UNIT, "1"); + tableCreationOptions.put(DynamoAdmin.NO_SCALING, "true"); + tableCreationOptions.put(DynamoAdmin.NO_BACKUP, "true"); + + Map indexCreationOptions = new HashMap<>(); + indexCreationOptions.put(DynamoAdmin.NO_SCALING, "true"); + + Map reparationOptions = new HashMap<>(); + reparationOptions.put(DynamoAdmin.NO_BACKUP, "true"); + + Map upgradeOptions = new HashMap<>(tableCreationOptions); + + // Create tables. + SchemaLoader.load(configFilePath, schemaFilePath, tableCreationOptions, createCoordinatorTables); + + // Alter tables. + SchemaLoader.alterTables(configFilePath, alteredSchemaFilePath, indexCreationOptions); + + // Repair namespaces and tables. + SchemaLoader.repairAll(configFilePath, schemaFilePath, reparationOptions, repairCoordinatorTables); + + // Delete tables. + SchemaLoader.unload(configFilePath, schemaFilePath, deleteCoordinatorTables); + + // Upgrade the environment + SchemaLoader.upgrade(configFilePath, upgradeOptions); + + return 0; + } +} +``` + +次に示すように、シリアル化されたスキーマ JSON 文字列 (スキーマファイルの生のテキスト) を渡すことによって、スキーマを作成、削除、または修復することもできます。 + +```java +// Create tables. +SchemaLoader.load(configFilePath, serializedSchemaJson, tableCreationOptions, createCoordinatorTables); + +// Alter tables. +SchemaLoader.alterTables(configFilePath, serializedAlteredSchemaFilePath, indexCreationOptions); + +// Repair namespaces and tables. +SchemaLoader.repairAll(configFilePath, serializedSchemaJson, reparationOptions, repairCoordinatorTables); + +// Delete tables. +SchemaLoader.unload(configFilePath, serializedSchemaJson, deleteCoordinatorTables); +``` + +ScalarDB を設定するときに、次に示すように `Properties` オブジェクトも使用できます。 + +```java +// Create tables. +SchemaLoader.load(properties, serializedSchemaJson, tableCreationOptions, createCoordinatorTables); + +// Alter tables. +SchemaLoader.alterTables(properties, serializedAlteredSchemaFilePath, indexCreationOptions); + +// Repair namespaces and tables. +SchemaLoader.repairAll(properties, serializedSchemaJson, reparationOptions, repairCoordinatorTables); + +// Delete tables. +SchemaLoader.unload(properties, serializedSchemaJson, deleteCoordinatorTables); + +// Upgrade the environment +SchemaLoader.upgrade(properties, upgradeOptions); +``` + +### Import tables + +[サンプルスキーマファイル](#サンプルスキーマファイル)に示されているのと同様の方法で、`--import` オプションとインポート固有のスキーマファイルを使用して、既存の JDBC データベーステーブルを ScalarDB にインポートできます。詳細については、[ScalarDB Schema Loader を使用して既存のテーブルを ScalarDB にインポートする](./schema-loader-import.mdx)を参照してください。 + +:::warning + +運用環境で ScalarDB にテーブルをインポートする場合は、データベーステーブルと ScalarDB メタデータテーブルにトランザクションメタデータ列が追加されるため、慎重に計画する必要があります。この場合、データベースと ScalarDB の間にはいくつかの違いがあり、いくつかの制限もあります。 + +::: + +以下はインポートのサンプルです。 + +```java +public class SchemaLoaderImportSample { + public static int main(String... args) throws SchemaLoaderException { + Path configFilePath = Paths.get("database.properties"); + // "import_sample_schema.json" can be found in the "/sample" directory. + Path schemaFilePath = Paths.get("import_sample_schema.json"); + Map tableImportOptions = new HashMap<>(); + + // Import tables. + // You can also use a Properties object instead of configFilePath and a serialized-schema JSON + // string instead of schemaFilePath. + SchemaLoader.importTables(configFilePath, schemaFilePath, tableImportOptions); + + return 0; + } +} +``` diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/slides/TransactionManagementOnCassandra.pdf b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/slides/TransactionManagementOnCassandra.pdf new file mode 100644 index 00000000..40e855bd Binary files /dev/null and b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/slides/TransactionManagementOnCassandra.pdf differ diff --git a/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/two-phase-commit-transactions.mdx b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/two-phase-commit-transactions.mdx new file mode 100644 index 00000000..3429c6aa --- /dev/null +++ b/i18n/versioned_docs/ja-jp/docusaurus-plugin-content-docs/version-3.15/two-phase-commit-transactions.mdx @@ -0,0 +1,763 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsJapanese +--- + +# 2フェーズコミットインターフェースを使用したトランザクション + +import TranslationBanner from '/src/components/_translation-ja-jp.mdx'; + + + +ScalarDB は、2フェーズコミットインターフェースを使用したトランザクションの実行をサポートしています。2フェーズコミットインターフェースを使用すると、マイクロサービスアーキテクチャのように、複数のプロセスまたはアプリケーションにまたがるトランザクションを実行できます。 + +このページでは、2フェーズコミットインターフェースを使用したトランザクションが ScalarDB でどのように機能するか、および ScalarDB でそれらを設定して実行する方法について説明します。 + +## ScalarDB での2フェーズコミットインターフェースを使用したトランザクションの動作 + +ScalarDB は通常、1フェーズコミットインターフェースを使用して単一のトランザクションマネージャーインスタンスでトランザクションを実行します。1フェーズコミットインターフェースを使用したトランザクションでは、トランザクションを開始し、CRUD 操作を実行し、同じトランザクションマネージャーインスタンスでトランザクションをコミットします。 + +ScalarDB では、複数のトランザクションマネージャーインスタンスにまたがる2フェーズコミットインターフェースを使用してトランザクションを実行できます。トランザクションマネージャーインスタンスは、同じプロセスまたはアプリケーションに存在しても、異なるプロセスまたはアプリケーションに存在してもかまいません。たとえば、複数のマイクロサービスにトランザクションマネージャーインスタンスがある場合は、複数のマイクロサービスにまたがるトランザクションを実行できます。 + +2フェーズコミットインターフェースを使用したトランザクションでは、Coordinator と参加者という2つのロールが1つのトランザクションを共同で実行します。 + +Coordinator プロセスと参加者プロセスはすべて、異なるトランザクションマネージャーインスタンスを持っています。Coordinator プロセスが最初にトランザクションを開始または開始し、参加者プロセスがトランザクションに参加します。 CRUD 操作を実行した後、Coordinator プロセスと参加プロセスは2フェーズインターフェイスを使用してトランザクションをコミットします。 + +## 2フェーズコミットインターフェースを使用してトランザクションを実行する方法 + +2フェーズコミットインターフェイスを使用してトランザクションを実行するには、トランザクションマネージャーインスタンスを取得する必要があります。その後、Coordinator プロセスはトランザクションを開始または起動でき、参加者はトランザクションを処理できます。 + +### `TwoPhaseCommitTransactionManager` インスタンスを取得する + +2フェーズコミットインターフェースを使用してトランザクションを実行するには、まず `TwoPhaseCommitTransactionManager` インスタンスを取得する必要があります。 + +`TwoPhaseCommitTransactionManager` インスタンスを取得するには、次のように `TransactionFactory` を使用できます。 + +```java +TransactionFactory factory = TransactionFactory.create(""); +TwoPhaseCommitTransactionManager transactionManager = factory.getTwoPhaseCommitTransactionManager(); +``` + +### トランザクションを開始する (Coordinator 用) + +トランザクションを開始するプロセスまたはアプリケーションが Coordinator として機能するには、次の `begin` メソッドを使用する必要があります。 + +```java +// Begin a transaction. +TwoPhaseCommitTransaction tx = transactionManager.begin(); +``` + +または、トランザクションを開始するプロセスまたはアプリケーションが Coordinator として機能するようにするには、次の `start` メソッドを使用する必要があります。 + +```java +// Start a transaction. +TwoPhaseCommitTransaction tx = transactionManager.start(); +``` + +あるいは、次のようにトランザクション ID を指定して、トランザクションに `begin` メソッドを使用することもできます。 + +```java +// Begin a transaction by specifying a transaction ID. +TwoPhaseCommitTransaction tx = transactionManager.begin(""); +``` + +または、次のようにトランザクション ID を指定して、トランザクションに `start` メソッドを使用することもできます。 + +```java +// Start a transaction by specifying a transaction ID. +TwoPhaseCommitTransaction tx = transactionManager.start(""); +``` + +### トランザクションに参加する (参加者向け) + +参加者は、次のように、Coordinator が開始または開始したトランザクションに関連付けられたトランザクション ID を指定して、トランザクションに参加できます。 + +```java +TwoPhaseCommitTransaction tx = transactionManager.join(""); +``` + +:::note + +`getId()` を使用してトランザクション ID を取得するには、次のように指定します。 + +```java +tx.getId(); +``` + +::: + +### トランザクションの CRUD 操作 + +`TwoPhaseCommitTransacton` の CRUD 操作は、`DistributedTransaction` の操作と同じです。詳細については、[CRUD 操作](api-guide.mdx#crud-operations) を参照してください。 + +以下は、2フェーズコミットインターフェイスを使用したトランザクションの CRUD 操作のサンプルコードです。 + +```java +TwoPhaseCommitTransaction tx = ... + +// Retrieve the current balances by ID. +Get fromGet = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLE) + .partitionKey(new Key(ID, fromId)) + .build(); + +Get toGet = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLE) + .partitionKey(new Key(ID, toId)) + .build(); + +Optional fromResult = tx.get(fromGet); +Optional toResult = tx.get(toGet); + +// Calculate the balances (assuming that both accounts exist). +int newFromBalance = fromResult.get().getInt(BALANCE) - amount; +int newToBalance = toResult.get().getInt(BALANCE) + amount; + +// Update the balances. +Put fromPut = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLE) + .partitionKey(new Key(ID, fromId)) + .intValue(BALANCE, newFromBalance) + .build(); + +Put toPut = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLE) + .partitionKey(new Key(ID, toId)) + .intValue(BALANCE, newToBalance) + .build(); + +tx.put(fromPut); +tx.put(toPut); +``` + +### トランザクションを準備、コミット、またはロールバックする + +CRUD 操作が完了したら、トランザクションをコミットする必要があります。標準の2フェーズコミットプロトコルと同様に、準備とコミットの2つのフェーズがあります。 + +すべての Coordinator プロセスと参加者プロセスでは、次のようにトランザクションを準備してからコミットする必要があります。 + +```java +TwoPhaseCommitTransaction tx = ... + +try { + // Execute CRUD operations in the Coordinator and participant processes. + ... + + // Prepare phase: Prepare the transaction in all the Coordinator and participant processes. + tx.prepare(); + ... + + // Commit phase: Commit the transaction in all the Coordinator and participant processes. + tx.commit(); + ... +} catch (TransactionException e) { + // If an error happens, you will need to roll back the transaction in all the Coordinator and participant processes. + tx.rollback(); + ... +} +``` + +`prepare()` の場合、Coordinator または参加者プロセスのいずれかがトランザクションの準備に失敗した場合、すべての Coordinator および参加者プロセスで `rollback()` (または `abort()`) を呼び出す必要があります。 + +`commit()` の場合、Coordinator または参加者プロセスのいずれかがトランザクションを正常にコミットした場合、トランザクションはコミットされたと見なすことができます。トランザクションがコミットされたら、他の Coordinator および参加者プロセスで発生したエラーは無視できます。すべての Coordinator および参加者プロセスがトランザクションのコミットに失敗した場合、すべての Coordinator および参加者プロセスで `rollback()` (または `abort()`) を呼び出す必要があります。 + +パフォーマンスを向上させるには、Coordinator および参加者プロセスでそれぞれ `prepare()`、`commit()`、および `rollback()` を並行して呼び出すことができます。 + +#### トランザクションを検証する + +並行性制御プロトコルに応じて、以下に示すように、`prepare()` の後、`commit()` の前に、すべての Coordinator および参加者プロセスで `validate()` を呼び出す必要があります。 + +```java +// Prepare phase 1: Prepare the transaction in all the Coordinator and participant processes. +tx.prepare(); +... + +// Prepare phase 2: Validate the transaction in all the Coordinator and participant processes. +tx.validate(); +... + +// Commit phase: Commit the transaction in all the Coordinator and participant processes. +tx.commit(); +... +``` + +`prepare()` と同様に、Coordinator または参加者プロセスのいずれかがトランザクションの検証に失敗した場合は、すべての Coordinator および参加者プロセスで `rollback()` (または `abort()`) を呼び出す必要があります。さらに、パフォーマンスを向上させるために、Coordinator および参加者プロセスで `validate()` を並行して呼び出すこともできます。 + +:::note + +`scalar.db.consensus_commit.serializable_strategy` の値として `EXTRA_READ` を設定し、`scalar.db.consensus_commit.isolation_level` の値として `SERIALIZABLE` を設定して [Consensus Commit](configurations.mdx#consensus-commit-を使用してトランザクションを実行する) トランザクションマネージャーを使用する場合は、`validate()` を呼び出す必要があります。ただし、Consensus Commit を使用していない場合は、`validate()` を指定しても効果はありません。 + +::: + +### 複数のトランザクションマネージャーインスタンスを使用してトランザクションを実行する + +上記の API を使用すると、複数のトランザクションマネージャーインスタンスを使用してトランザクションを実行できます。以下はその動作例です。 + +:::warning + +以下のサンプルコードは、2フェーズコミットインターフェースの使用方法を説明するための簡略版であり、実際のユースケースを表すものではありません。実際のアプリケーションでは、プロセスまたはサービスごとにトランザクションマネージャーインスタンスが作成されることを想定しています。 + +実際の例については、[マイクロサービストランザクションのサンプルチュートリアル](scalardb-samples/microservice-transaction-sample/README.mdx)を参照してください。 + +::: + +```java +TransactionFactory factory1 = + TransactionFactory.create(""); +TwoPhaseCommitTransactionManager transactionManager1 = + factory1.getTwoPhaseCommitTransactionManager(); + +TransactionFactory factory2 = + TransactionFactory.create(""); +TwoPhaseCommitTransactionManager transactionManager2 = + factory2.getTwoPhaseCommitTransactionManager(); + +TwoPhaseCommitTransaction transaction1 = null; +TwoPhaseCommitTransaction transaction2 = null; +try { + // Begin a transaction. + transaction1 = transactionManager1.begin(); + + // Join the transaction begun by `transactionManager1` by getting the transaction ID. + transaction2 = transactionManager2.join(transaction1.getId()); + + // Execute CRUD operations in the transaction. + Optional result = transaction1.get(...); + List results = transaction2.scan(...); + transaction1.put(...); + transaction2.delete(...); + + // Prepare the transaction. + transaction1.prepare(); + transaction2.prepare(); + + // Validate the transaction. + transaction1.validate(); + transaction2.validate(); + + // Commit the transaction. If any of the transactions successfully commit, + // you can regard the transaction as committed. + AtomicReference exception = new AtomicReference<>(); + boolean anyMatch = + Stream.of(transaction1, transaction2) + .anyMatch( + t -> { + try { + t.commit(); + return true; + } catch (TransactionException e) { + exception.set(e); + return false; + } + }); + + // If all the transactions fail to commit, throw the exception and roll back the transaction. + if (!anyMatch) { + throw exception.get(); + } +} catch (TransactionException e) { + // Roll back the transaction. + if (transaction1 != null) { + try { + transaction1.rollback(); + } catch (RollbackException e1) { + // Handle the exception. + } + } + if (transaction2 != null) { + try { + transaction2.rollback(); + } catch (RollbackException e1) { + // Handle the exception. + } + } +} +``` + +簡潔にするために、上記のサンプルコードでは、API がスローする可能性のある例外は処理していません。例外の処理の詳細については、[例外の処理方法](#how-to-handle-exceptions) を参照してください。 + +前述のように、`commit()` の場合、Coordinator または参加者プロセスのいずれかがトランザクションのコミットに成功した場合、トランザクションはコミットされたと見なすことができます。また、パフォーマンスを向上させるために、`prepare()`、`validate()`、および `commit()` をそれぞれ並列で実行することもできます。 + +### トランザクションを再開または再結合する + +2フェーズコミットインターフェースでトランザクションを使用するプロセスまたはアプリケーションでは、通常、複数の要求と応答の交換が行われるため、さまざまなエンドポイントまたは API 間でトランザクションを実行する必要がある場合があります。このようなシナリオでは、`resume()` または `join()` を使用して、以前に参加したトランザクションのトランザクションオブジェクト (`TwoPhaseCommitTransaction` のインスタンス) を取得できます。 + +以下は、`resume()` と `join()` がどのように動作するかを示しています。 + +```java +// Join (or begin) the transaction. +TwoPhaseCommitTransaction tx = transactionManager.join(""); + +... + +// Resume the transaction by using the transaction ID. +TwoPhaseCommitTransaction tx1 = transactionManager.resume(""); + +// Or you can re-join the transaction by using the transaction ID. +TwoPhaseCommitTransaction tx2 = transactionManager.join(""); +``` + +:::note + +`getId()` を使用してトランザクション ID を取得するには、次のように指定します。 + +```java +tx.getId(); +``` + +また、`join()` を使用してトランザクションに再参加する場合、以前にトランザクションに参加したことがない場合は、新しいトランザクションオブジェクトが返されます。一方、`resume()` を使用してトランザクションを再開する場合、以前にトランザクションに参加したことがない場合は、`TransactionNotFoundException` がスローされます。 + +::: + +以下は、複数のエンドポイントを持つ2つのサービスの例です。 + +```java +interface ServiceA { + void facadeEndpoint() throws Exception; +} + +interface ServiceB { + void endpoint1(String txId) throws Exception; + + void endpoint2(String txId) throws Exception; + + void prepare(String txId) throws Exception; + + void commit(String txId) throws Exception; + + void rollback(String txId) throws Exception; +} +``` + +以下は、2つのサービス (`ServiceA` と `ServiceB`) にまたがるトランザクションを開始する `ServiceA.facadeEndpoint()` を呼び出すクライアントの例です。 + +```java +public class ServiceAImpl implements ServiceA { + + private TwoPhaseCommitTransactionManager transactionManager = ...; + private ServiceB serviceB = ...; + + ... + + @Override + public void facadeEndpoint() throws Exception { + TwoPhaseCommitTransaction tx = transactionManager.begin(); + + try { + ... + + // Call `ServiceB` `endpoint1`. + serviceB.endpoint1(tx.getId()); + + ... + + // Call `ServiceB` `endpoint2`. + serviceB.endpoint2(tx.getId()); + + ... + + // Prepare. + tx.prepare(); + serviceB.prepare(tx.getId()); + + // Commit. + tx.commit(); + serviceB.commit(tx.getId()); + } catch (Exception e) { + // Roll back. + tx.rollback(); + serviceB.rollback(tx.getId()); + } + } +} +``` + +上記のように、`ServiceA` のファサードエンドポイントは、`ServiceB` の複数のエンドポイント (`endpoint1()`、`endpoint2()`、`prepare()`、`commit()`、および `rollback()`) を呼び出します。また、2フェーズコミットインターフェースを持つトランザクションでは、エンドポイント間で同じトランザクションオブジェクトを使用する必要があります。 + +この状況では、トランザクションを再開できます。`ServiceB` の実装は次のとおりです。 + +```java +public class ServiceBImpl implements ServiceB { + + private TwoPhaseCommitTransactionManager transactionManager = ...; + + ... + + @Override + public void endpoint1(String txId) throws Exception { + // Join the transaction. + TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + } + + @Override + public void endpoint2(String txId) throws Exception { + // Resume the transaction that you joined in `endpoint1()`. + TwoPhaseCommitTransaction tx = transactionManager.resume(txId); + + // Or re-join the transaction that you joined in `endpoint1()`. + // TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + } + + @Override + public void prepare(String txId) throws Exception { + // Resume the transaction. + TwoPhaseCommitTransaction tx = transactionManager.resume(txId); + + // Or re-join the transaction. + // TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + + // Prepare. + tx.prepare(); + } + + @Override + public void commit(String txId) throws Exception { + // Resume the transaction. + TwoPhaseCommitTransaction tx = transactionManager.resume(txId); + + // Or re-join the transaction. + // TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + + // Commit. + tx.commit(); + } + + @Override + public void rollback(String txId) throws Exception { + // Resume the transaction. + TwoPhaseCommitTransaction tx = transactionManager.resume(txId); + + // Or re-join the transaction. + // TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + + // Roll back. + tx.rollback(); + } +} +``` + +上記のように、トランザクションを再開または再結合することで、`ServiceB` 内の複数のエンドポイント間で同じトランザクションオブジェクトを共有できます。 + +## 例外の処理方法 + +複数のトランザクションマネージャーインスタンスを使用してトランザクションを実行する場合は、例外を適切に処理する必要もあります。 + +:::warning + +例外を適切に処理しないと、異常やデータの不整合が発生する可能性があります。 + +::: + +たとえば、[複数のトランザクションマネージャーインスタンスを使用してトランザクションを実行する](#複数のトランザクションマネージャーインスタンスを使用してトランザクションを実行する)のサンプルコードでは、説明を簡単にするために、1つのプロセスで複数のトランザクションマネージャー (`transactionManager1` と `transactionManager2`) が使用されています。ただし、このサンプルコードには例外を処理する方法が含まれていません。 + +次のサンプルコードは、2フェーズコミットインターフェイスを使用してトランザクションで例外を処理する方法を示しています。 + +```java +public class Sample { + public static void main(String[] args) throws Exception { + TransactionFactory factory1 = + TransactionFactory.create(""); + TwoPhaseCommitTransactionManager transactionManager1 = + factory1.getTwoPhaseCommitTransactionManager(); + + TransactionFactory factory2 = + TransactionFactory.create(""); + TwoPhaseCommitTransactionManager transactionManager2 = + factory2.getTwoPhaseCommitTransactionManager(); + + int retryCount = 0; + TransactionException lastException = null; + + while (true) { + if (retryCount++ > 0) { + // Retry the transaction three times maximum in this sample code. + if (retryCount >= 3) { + // Throw the last exception if the number of retries exceeds the maximum. + throw lastException; + } + + // Sleep 100 milliseconds before retrying the transaction in this sample code. + TimeUnit.MILLISECONDS.sleep(100); + } + + TwoPhaseCommitTransaction transaction1 = null; + TwoPhaseCommitTransaction transaction2 = null; + try { + // Begin a transaction. + transaction1 = transactionManager1.begin(); + + // Join the transaction that `transactionManager1` begun by using the transaction ID. + transaction2 = transactionManager2.join(transaction1.getId()); + + // Execute CRUD operations in the transaction. + Optional result = transaction1.get(...); + List results = transaction2.scan(...); + transaction1.put(...); + transaction2.delete(...); + + // Prepare the transaction. + prepare(transaction1, transaction2); + + // Validate the transaction. + validate(transaction1, transaction2); + + // Commit the transaction. + commit(transaction1, transaction2); + } catch (UnsatisfiedConditionException e) { + // You need to handle `UnsatisfiedConditionException` only if a mutation operation specifies + // a condition. This exception indicates the condition for the mutation operation is not met. + + rollback(transaction1, transaction2); + + // You can handle the exception here, according to your application requirements. + + return; + } catch (UnknownTransactionStatusException e) { + // If you catch `UnknownTransactionStatusException` when committing the transaction, + // it indicates that the status of the transaction, whether it was successful or not, is unknown. + // In such a case, you need to check if the transaction is committed successfully or not and + // retry the transaction if it failed. How to identify a transaction status is delegated to users. + return; + } catch (TransactionException e) { + // For other exceptions, you can try retrying the transaction. + + // For `CrudConflictException`, `PreparationConflictException`, `ValidationConflictException`, + // `CommitConflictException`, and `TransactionNotFoundException`, you can basically retry the + // transaction. However, for the other exceptions, the transaction will still fail if the cause of + // the exception is non-transient. In such a case, you will exhaust the number of retries and + // throw the last exception. + + rollback(transaction1, transaction2); + + lastException = e; + } + } + } + + private static void prepare(TwoPhaseCommitTransaction... transactions) + throws TransactionException { + // You can execute `prepare()` in parallel. + List exceptions = + Stream.of(transactions) + .parallel() + .map( + t -> { + try { + t.prepare(); + return null; + } catch (TransactionException e) { + return e; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + // If any of the transactions failed to prepare, throw the exception. + if (!exceptions.isEmpty()) { + throw exceptions.get(0); + } + } + + private static void validate(TwoPhaseCommitTransaction... transactions) + throws TransactionException { + // You can execute `validate()` in parallel. + List exceptions = + Stream.of(transactions) + .parallel() + .map( + t -> { + try { + t.validate(); + return null; + } catch (TransactionException e) { + return e; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + // If any of the transactions failed to validate, throw the exception. + if (!exceptions.isEmpty()) { + throw exceptions.get(0); + } + } + + private static void commit(TwoPhaseCommitTransaction... transactions) + throws TransactionException { + // You can execute `commit()` in parallel. + List exceptions = + Stream.of(transactions) + .parallel() + .map( + t -> { + try { + t.commit(); + return null; + } catch (TransactionException e) { + return e; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + // If any of the transactions successfully committed, you can regard the transaction as committed. + if (exceptions.size() < transactions.length) { + if (!exceptions.isEmpty()) { + // You can log the exceptions here if you want. + } + + return; // Commit was successful. + } + + // + // If all the transactions failed to commit: + // + + // If any of the transactions failed to commit due to `UnknownTransactionStatusException`, throw + // it because you should not retry the transaction in such a case. + Optional unknownTransactionStatusException = + exceptions.stream().filter(e -> e instanceof UnknownTransactionStatusException).findFirst(); + if (unknownTransactionStatusException.isPresent()) { + throw unknownTransactionStatusException.get(); + } + + // Otherwise, throw the first exception. + throw exceptions.get(0); + } + + private static void rollback(TwoPhaseCommitTransaction... transactions) { + Stream.of(transactions) + .parallel() + .filter(Objects::nonNull) + .forEach( + t -> { + try { + t.rollback(); + } catch (RollbackException e) { + // Rolling back the transaction failed. The transaction should eventually recover, + // so you don't need to do anything further. You can simply log the occurrence here. + } + }); + } +} +``` + +### `TransactionException` および `TransactionNotFoundException` + +`begin()` API は `TransactionException` または `TransactionNotFoundException` をスローする可能性があります: + +- `TransactionException` をキャッチした場合、この例外は、一時的または非一時的障害が原因でトランザクションを開始できなかったことを示します。トランザクションを再試行することはできますが、非一時的障害が原因でトランザクションを開始できない可能性があります。 +- `TransactionNotFoundException` をキャッチした場合、この例外は、一時的障害が原因でトランザクションを開始できなかったことを示します。この場合、トランザクションを再試行できます。 + +`join()` API も `TransactionNotFoundException` をスローする可能性があります。この例外は、`begin()` API の例外を処理するのと同じ方法で処理できます。 + +### `CrudException` および `CrudConflictException` + +CRUD 操作の API (`get()`、`scan()`、`put()`、`delete()`、および `mutate()`) は、`CrudException` または `CrudConflictException` をスローする可能性があります: + +- `CrudException` をキャッチした場合、この例外は、トランザクション CRUD 操作が一時的または非一時的障害のために失敗したことを示します。トランザクションを最初から再試行することはできますが、原因が非一時的である場合はトランザクションは失敗します。 +- `CrudConflictException` をキャッチした場合、この例外は、トランザクション CRUD 操作が一時的な障害 (競合エラーなど) のために失敗したことを示します。この場合、トランザクションを最初から再試行できます。 + +### `UnsatisfiedConditionException` + +ミューテーション操作の API (`put()`、`delete()`、および `mutate()`) も `UnsatisfiedConditionException` をスローする可能性があります。 + +`UnsatisfiedConditionException` をキャッチした場合、この例外はミューテーション操作の条件が満たされていないことを示します。この例外は、アプリケーションの要件に応じて処理できます。 + +### `PreparationException` および `PreparationConflictException` + +`prepare()` API は、`PreparationException` または `PreparationConflictException` をスローする可能性があります: + +- `PreparationException` をキャッチした場合、この例外は、一時的または非一時的障害が原因でトランザクションの準備が失敗したことを示します。トランザクションを最初から再試行することはできますが、原因が非一時的である場合はトランザクションは失敗します。 +- `PreparationConflictException` をキャッチした場合、この例外は、一時的な障害 (競合エラーなど) が原因でトランザクションの準備が失敗したことを示します。この場合、トランザクションを最初から再試行できます。 + +### `ValidationException` および `ValidationConflictException` + +`validate()` API は `ValidationException` または `ValidationConflictException` をスローする可能性があります: + +- `ValidationException` をキャッチした場合、この例外は、一時的または非一時的障害が原因でトランザクションの検証が失敗したことを示します。トランザクションを最初から再試行することはできますが、原因が非一時的である場合はトランザクションは失敗します。 +- `ValidationConflictException` をキャッチした場合、この例外は、一時的な障害 (競合エラーなど) が原因でトランザクションの検証が失敗したことを示します。この場合、トランザクションを最初から再試行できます。 + +### `CommitException`、`CommitConflictException`、および `UnknownTransactionStatusException` + +`commit()` API は、`CommitException`、`CommitConflictException`、または `UnknownTransactionStatusException` をスローする可能性があります: + +- `CommitException` をキャッチした場合、この例外は、一時的または非一時的障害が原因でトランザクションのコミットが失敗したことを示します。トランザクションを最初から再試行することはできますが、原因が非一時的である場合はトランザクションは失敗します。 +- `CommitConflictException` をキャッチした場合、この例外は、一時的な障害 (競合エラーなど) が原因でトランザクションのコミットが失敗したことを示します。この場合、トランザクションを最初から再試行できます。 +- `UnknownTransactionStatusException` をキャッチした場合、この例外は、トランザクションのステータス (成功したかどうか) が不明であることを示します。この場合、トランザクションが正常にコミットされたかどうかを確認し、失敗した場合はトランザクションを再試行する必要があります。 + +トランザクションステータスを識別する方法は、ユーザーに委任されています。トランザクションステータステーブルを作成し、他のアプリケーションデータを使用してトランザクション的に更新して、ステータステーブルからトランザクションのステータスを取得できるようにすることができます。 + +### 一部の例外に関する注意 + +サンプルコードには示されていませんが、`resume()` API は `TransactionNotFoundException` をスローする可能性もあります。この例外は、指定された ID に関連付けられたトランザクションが見つからなかったか、トランザクションの有効期限が切れた可能性があることを示します。いずれの場合も、この例外の原因は基本的に一時的なものであるため、トランザクションを最初から再試行できます。 + +サンプルコードでは、`UnknownTransactionStatusException` の場合、トランザクションは再試行されません。これは、アプリケーションがトランザクションが成功したかどうかをチェックして、重複操作の可能性を回避する必要があるためです。また、`UnsatisfiedConditionException` の場合、この例外の処理方法はアプリケーションの要件によって異なるため、トランザクションは再試行されません。その他の例外の場合、例外の原因が一時的または非一時的であるため、トランザクションは再試行されます。例外の原因が一時的である場合、再試行するとトランザクションが成功する可能性があります。ただし、例外の原因が非一時的である場合、再試行してもトランザクションは失敗します。このような場合、再試行回数が上限に達します。 + +:::note + +トランザクション ID を指定してトランザクションを開始する場合、トランザクションを再試行するときには別の ID を使用する必要があります。 + +また、サンプルコードでは、トランザクションは最大3回再試行され、再試行前に100ミリ秒間スリープします。ただし、アプリケーション要件に応じて、指数バックオフなどの再試行ポリシーを選択できます。 + +::: + +## 2フェーズコミットインターフェースを使用したトランザクションでのリクエストルーティング + +2フェーズコミットインターフェースを使用したトランザクションを使用するサービスは通常、次の図に示すように、複数のリクエストと応答を交換することによってトランザクションを実行します。 + +![2フェーズコミットインターフェースを使用したトランザクションのシーケンス図](images/two_phase_commit_sequence_diagram.png) + +さらに、各サービスには通常、スケーラビリティと可用性のために複数のサーバー (またはホスト) があり、サーバー側 (プロキシ) またはクライアント側の負荷分散を使用してサーバーに要求を分散します。このような場合、2フェーズコミットインターフェイスを使用したトランザクションのトランザクション処理はステートフルであるため、次の図に示すように、トランザクション内の要求は同じサーバーにルーティングする必要があり、負荷を分散するために異なるトランザクションを分散する必要があります。 + +![2フェーズコミットインターフェースによるトランザクションの負荷分散](images/two_phase_commit_load_balancing.png) + +サービス間のプロトコルに応じて、2フェーズコミットインターフェースを使用してトランザクションの負荷分散を実現する方法はいくつかあります。この方法には、gRPC、HTTP/1.1、および [ScalarDB Cluster](scalardb-cluster/index.mdx) の使用が含まれます。これは、ScalarDB Enterprise エディションでのみ使用可能なコンポーネントです。 + +### gRPC + +クライアント側のロードバランサーを使用すると、同じ gRPC 接続を使用してトランザクションでリクエストを送信できるため、リクエストが同じサーバーに送信されることが保証されます。 + +サーバー側 (プロキシ) ロードバランサーを使用する場合、L3/L4 (トランスポートレベル) ロードバランサーと L7 (アプリケーションレベル) ロードバランサーではソリューションが異なります。 + +- L3/L4ロードバランサーを使用する場合、クライアント側ロードバランサーを使用する場合と同様に、同じ gRPC 接続を使用してトランザクションでリクエストを送信できます。この場合、同じ gRPC 接続のリクエストは常に同じサーバーに送信されます。 +- L7ロードバランサーを使用する場合、同じ gRPC 接続のリクエストが必ずしも同じサーバーに送信されるわけではないため、Cookie または同様の方法を使用してリクエストを正しいサーバーにルーティングする必要があります。 + - たとえば、[Envoy](https://www.envoyproxy.io/) を使用する場合、gRPC のセッションアフィニティ (スティッキーセッション) を使用できます。あるいは、L7ロードバランサが同じストリーム内のリクエストを同じサーバーに分散するため、[bidirectional streaming RPC in gRPC](https://grpc.io/docs/what-is-grpc/core-concepts/#bidirectional-streaming-rpc) を使用することもできます。 + +gRPC でのロードバランシングの詳細については、[gRPC Load Balancing](https://grpc.io/blog/grpc-load-balancing/) を参照してください。 + +### HTTP/1.1 + +通常、HTTP/1.1ではサーバー側 (プロキシ) ロードバランサを使用します。 + +- L3/L4ロードバランサを使用する場合、同じ HTTP 接続を使用してトランザクションでリクエストを送信できるため、リクエストが同じサーバーに送信されることが保証されます。 +- L7ロードバランサを使用する場合、同じ HTTP 接続内のリクエストが必ずしも同じサーバーに送信されるわけではないため、Cookie または同様の方法を使用してリクエストを正しいサーバーにルーティングする必要があります。その場合は、セッションアフィニティ (スティッキーセッション) を使用できます。 + +### ScalarDB Cluster + +ScalarDB Cluster は、リクエストをクラスター内の適切なクラスターノードに転送できるルーティングメカニズムを提供することで、リクエストルーティングに対応します。ScalarDB Cluster の詳細については、[ScalarDB Cluster](scalardb-cluster/index.mdx) を参照してください。 + +## ハンズオンチュートリアル + +2フェーズコミットインターフェースを使用したトランザクションのユースケースの1つに、マイクロサービストランザクションがあります。ハンズオンチュートリアルについては、[マイクロサービストランザクションをサポートするサンプルアプリケーションを作成する](scalardb-samples/microservice-transaction-sample/README.mdx)を参照してください。 diff --git a/sidebars.js b/sidebars.js index f7d13aca..b4b5669c 100644 --- a/sidebars.js +++ b/sidebars.js @@ -904,6 +904,16 @@ const sidebars = { id: 'scalardb-sql/scalardb-sql-status-codes', label: 'ScalarDB SQL', }, + { + type: 'doc', + id: 'scalardb-schema-loader-status-codes', + label: 'ScalarDB Schema Loader', + }, + { + type: 'doc', + id: 'scalardb-data-loader-status-codes', + label: 'ScalarDB Data Loader', + }, { type: 'doc', id: 'scalardb-cluster/scalardb-auth-status-codes', @@ -1830,6 +1840,16 @@ const sidebars = { id: 'scalardb-sql/scalardb-sql-status-codes', label: 'ScalarDB SQL', }, + { + type: 'doc', + id: 'scalardb-schema-loader-status-codes', + label: 'ScalarDB Schema Loader', + }, + { + type: 'doc', + id: 'scalardb-data-loader-status-codes', + label: 'ScalarDB Data Loader', + }, { type: 'doc', id: 'scalardb-cluster/scalardb-auth-status-codes', diff --git a/src/components/Cards/3.16.tsx b/src/components/Cards/3.16.tsx new file mode 100644 index 00000000..6758e514 --- /dev/null +++ b/src/components/Cards/3.16.tsx @@ -0,0 +1,254 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable global-require */ + +import React from 'react'; +import clsx from 'clsx'; +import Translate from '@docusaurus/Translate'; +import Link from '@docusaurus/Link'; +import LiteYouTubeEmbed from 'react-lite-youtube-embed'; +import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faBook } from '@fortawesome/free-solid-svg-icons'; + +const new_content = [ + { + name: 'New content', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['api-guide#begin-or-start-a-transaction-in-read-only-mode'], + labels: ['Begin or start a transaction in read-only mode'] + }, + { + cell: 1, // Second cell + links: ['consensus-commit#one-phase-commit'], + labels: ['One-phase commit optimization'] + }, + { + cell: 2, // Third cell + links: ['configurations#scan-fetch-size'], + labels: ['Scan fetch size'] + } + ] + } +]; + +const categories = [ + { + name: 'About ScalarDB', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['overview'], + labels: ['ScalarDB Overview'] + }, + { + cell: 1, // Second cell + links: ['design'], + labels: ['Design'] + }, + { + cell: 2, // Third cell + links: ['requirements'], + labels: ['Requirements'] + } + ] + }, + { + name: 'Quickstart', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['quickstart-overview'], + labels: ['Quickstart Overview'] + }, + { + cell: 1, // Second cell + links: ['getting-started-with-scalardb'], + labels: ['Getting Started with ScalarDB'] + }, + { + cell: 2, // Third cell + links: ['scalardb-cluster/getting-started-with-scalardb-cluster'], + labels: ['Getting Started with ScalarDB Cluster'] + } + ] + }, + { + name: 'Develop', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['develop-overview'], + labels: ['Develop Overview'] + }, + { + cell: 1, // Second cell + links: ['develop-run-transactions-overview'], + labels: ['Run Transactions'] + }, + { + cell: 2, // Third cell + links: ['develop-run-non-transactional-operations-overview'], + labels: ['Run Non-Transactional Storage Operations'] + } + ] + }, + { + name: 'Deploy', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['deploy-overview'], + labels: ['Deploy Overview'] + }, + { + cell: 1, // Second cell + links: ['scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart'], + labels: ['Deploy ScalarDB Cluster Locally'] + }, + { + cell: 2, // Third cell + links: ['scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS'], + labels: ['Deploy ScalarDB Cluster on Amazon EKS'] + } + ] + }, + { + name: 'Migrate', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['migrate-overview'], + labels: ['Migrate Overview'] + }, + { + cell: 1, // Second cell + links: ['scalardb-sql/migration-guide'], + labels: ['Import Tables by Using Schema Loader'] + }, + { + cell: 2, // Third cell + links: ['scalardb-sql/migration-guide'], + labels: ['Migrate Applications and Databases'] + } + ] + }, + { + name: 'Manage', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['manage-overview'], + labels: ['Manage Overview'] + }, + { + cell: 1, // Second cell + links: ['scalar-kubernetes/HowToScaleScalarDB'], + labels: ['Scale ScalarDB'] + }, + { + cell: 2, // Third cell + links: ['scalar-kubernetes/HowToUpgradeScalarDB'], + labels: ['Upgrade ScalarDB'] + } + ] + } +]; + +const CategoryGrid = () => { + return ( +
+ {/* Hero section */} +
+
+

ScalarDB

+

ScalarDB is a universal hybrid transaction/analytical processing (HTAP) engine for diverse databases. It runs as middleware on databases and virtually unifies diverse databases by achieving ACID transactions and real-time analytics across them to simplify the complexity of managing multiple databases or multiple instances of a single database.

+ {/* +

As a versatile solution, ScalarDB supports a range of databases, including:

+ +
    +
  • Relational databases that support JDBC, such as MariaDB, Microsoft SQL Server, MySQL, Oracle Database, PostgreSQL, SQLite, and their compatible databases, like Amazon Aurora and YugabyteDB.
  • +
  • NoSQL databases like Amazon DynamoDB, Apache Cassandra, and Azure Cosmos DB.
  • +
+
*/} +
+
+ +
+
+ + {/* New content table */} +
+ {new_content.map((doc, i) => ( + +
+ {/* +  {doc.name}*/} + {doc.name} +
+ {doc.categoryLinks.map((categoryLinkCell, j) => ( +
+ {categoryLinkCell.links.map((cellLink, k) => ( + cellLink ? ( + + {categoryLinkCell.labels[k]} + + ) : ( + + {categoryLinkCell.labels[k]} + + ) + ))} +
+ ))} +
+ ))} + + {/* Category table */} + {categories.map((cat, i) => ( + +
{cat.name}
+ {cat.categoryLinks.map((categoryLinkCell, j) => ( +
+ {categoryLinkCell.links.map((cellLink, k) => ( + cellLink ? ( + + {categoryLinkCell.labels[k]} + + ) : ( + + {categoryLinkCell.labels[k]} + + ) + ))} +
+ ))} +
+ ))} +
+
+ ); +}; + +export default CategoryGrid; diff --git a/src/components/Cards/ja-jp/3.16.tsx b/src/components/Cards/ja-jp/3.16.tsx new file mode 100644 index 00000000..d5f9dac8 --- /dev/null +++ b/src/components/Cards/ja-jp/3.16.tsx @@ -0,0 +1,254 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable global-require */ + +import React from 'react'; +import clsx from 'clsx'; +import Translate from '@docusaurus/Translate'; +import Link from '@docusaurus/Link'; +import LiteYouTubeEmbed from 'react-lite-youtube-embed'; +import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faBook } from '@fortawesome/free-solid-svg-icons'; + +const new_content = [ + { + name: '新着コンテンツ', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['api-guide#読み取り専用モードでトランザクションを開始またはスタートする'], + labels: ['読み取り専用モードでトランザクションを開始またはスタートする'] + }, + { + cell: 1, // Second cell + links: [''], + labels: [''] + }, + { + cell: 2, // Third cell + links: [''], + labels: [''] + } + ] + } +]; + +const categories = [ + { + name: 'ScalarDB について', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['overview'], + labels: ['ScalarDB の概要'] + }, + { + cell: 1, // Second cell + links: ['design'], + labels: ['デザイン'] + }, + { + cell: 2, // Third cell + links: ['requirements'], + labels: ['要件'] + } + ] + }, + { + name: 'クイックスタート', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['quickstart-overview'], + labels: ['クイックスタートの概要'] + }, + { + cell: 1, // Second cell + links: ['getting-started-with-scalardb'], + labels: ['ScalarDB をはじめよう'] + }, + { + cell: 2, // Third cell + links: ['scalardb-cluster/getting-started-with-scalardb-cluster'], + labels: ['ScalarDB Cluster をはじめよう'] + } + ] + }, + { + name: '開発', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['develop-overview'], + labels: ['開発の概要'] + }, + { + cell: 1, // Second cell + links: ['develop-run-transactions-overview'], + labels: ['トランザクションの実行の概要'] + }, + { + cell: 2, // Third cell + links: ['develop-run-non-transactional-operations-overview'], + labels: ['非トランザクションストレージ操作を実行'] + } + ] + }, + { + name: 'デプロイ', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['deploy-overview'], + labels: ['デプロイの概要'] + }, + { + cell: 1, // Second cell + links: ['scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart'], + labels: ['ScalarDB Cluster をローカルにデプロイする方法'] + }, + { + cell: 2, // Third cell + links: ['scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS'], + labels: ['Amazon Elastic Kubernetes Service (EKS) に ScalarDB Cluster をデプロイする'] + } + ] + }, + { + name: '移行', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['migrate-overview'], + labels: ['移行の概要'] + }, + { + cell: 1, // Second cell + links: ['scalardb-sql/migration-guide'], + labels: ['アプリケーションとデータベースを ScalarDB ベースの環境に移行する方法'] + }, + { + cell: 2, // Third cell + links: ['scalardb-sql/migration-guide'], + labels: ['アプリケーションとデータベースを ScalarDB ベースの環境に移行する方法'] + } + ] + }, + { + name: '管理', + categoryLinks: [ + // To add a link, use the format ['link1', 'link2'] + // To add a label, use the format ['label1', 'label2'] + { + cell: 0, // First cell + links: ['manage-overview'], + labels: ['管理の概要'] + }, + { + cell: 1, // Second cell + links: ['scalar-kubernetes/HowToScaleScalarDB'], + labels: ['ScalarDB をスケーリングする方法'] + }, + { + cell: 2, // Third cell + links: ['scalar-kubernetes/HowToUpgradeScalarDB'], + labels: ['ScalarDB のアップグレード方法'] + } + ] + } +]; + +const CategoryGrid = () => { + return ( +
+ {/* Hero section */} +
+
+

ScalarDB

+

ScalarDB は、さまざまなデータベースに対応したユニバーサルなハイブリッドトランザクション/分析処理 (HTAP) エンジンです。データベース上でミドルウェアとして動作し、ACID トランザクションとリアルタイム分析を実現することで、複数のデータベースや複数インスタンスの管理の複雑さを簡素化し、仮想的に統合します。

+ {/* +

多用途なソリューションとして、ScalarDB は以下のような幅広いデータベースをサポートしています:

+ +
    +
  • MariaDB、Microsoft SQL Server、MySQL、Oracle Database、PostgreSQL、SQLite などの JDBC をサポートするリレーショナルデータベース、および Amazon Aurora や YugabyteDB のようなそれらに互換性のあるデータベース。
  • +
  • Amazon DynamoDB、Apache Cassandra、Azure Cosmos DB などの NoSQL データベース。
  • +
+
*/} +
+
+ +
+
+ + {/* New content table */} +
+ {new_content.map((doc, i) => ( + +
+ {/* +  {doc.name}*/} + {doc.name} +
+ {doc.categoryLinks.map((categoryLinkCell, j) => ( +
+ {categoryLinkCell.links.map((cellLink, k) => ( + cellLink ? ( + + {categoryLinkCell.labels[k]} + + ) : ( + + {categoryLinkCell.labels[k]} + + ) + ))} +
+ ))} +
+ ))} + + {/* Category table */} + {categories.map((cat, i) => ( + +
{cat.name}
+ {cat.categoryLinks.map((categoryLinkCell, j) => ( +
+ {categoryLinkCell.links.map((cellLink, k) => ( + cellLink ? ( + + {categoryLinkCell.labels[k]} + + ) : ( + + {categoryLinkCell.labels[k]} + + ) + ))} +
+ ))} +
+ ))} +
+
+ ); +}; + +export default CategoryGrid; diff --git a/src/data/notifications.js b/src/data/notifications.js index 0dae6d97..2a123812 100644 --- a/src/data/notifications.js +++ b/src/data/notifications.js @@ -1,14 +1,25 @@ // This file contains the notifications data and a function to retrieve it. // The notifications are stored in an array of objects, each containing a message in multiple languages and URLs for those messages. const notificationsList = [ + // { + // message: { + // en: 'Blog post: Explore the exciting new features in ScalarDB 3.16', + // ja: 'ブログ記事: データベースエンジニアリングの最新トレンドとベストプラクティスを学ぶ DBEM #7 のハイライト' + // }, + // url: { + // en: 'XXX_?utm_source=docs-site&utm_medium=notifications', + // ja: 'XXX_?utm_source=docs-site&utm_medium=notifications' + // }, + // unread: true + // }, { message: { - en: 'Check out the release notes for ScalarDB 3.15.4', - ja: 'ScalarDB 3.15.4 のリリースノートをご覧ください' + en: 'Support for IBM Db2 has been added in ScalarDB 3.16', + ja: 'ScalarDB 3.16 で IBM Db2 がサポートされました' }, url: { - en: 'releases/release-notes#v3154?utm_source=docs-site&utm_medium=notifications', - ja: 'releases/release-notes#v3154?utm_source=docs-site&utm_medium=notifications' + en: 'requirements?RDBs=Db2#relational-databases?utm_source=docs-site&utm_medium=notifications', + ja: 'requirements?RDBs=Db2#リレーショナルデータベース?utm_source=docs-site&utm_medium=notifications' }, unread: true }, @@ -23,17 +34,6 @@ const notificationsList = [ }, unread: true }, - { - message: { - en: 'Blog post: Explore the exciting new features in ScalarDB 3.15', - ja: 'ブログ記事: データベースエンジニアリングの最新トレンドとベストプラクティスを学ぶ DBEM #6 のハイライト' - }, - url: { - en: 'https://medium.com/scalar-engineering/scalardb-3-15-has-been-released-b1982718fa46?utm_source=docs-site&utm_medium=notifications', - ja: 'https://medium.com/scalar-engineering-ja/database-engineering-meetup-%E7%AC%AC6%E5%9B%9E-dbem-6-%E3%82%92%E9%96%8B%E5%82%AC%E3%81%97%E3%81%BE%E3%81%97%E3%81%9F-fccde39d2926?utm_source=docs-site&utm_medium=notifications' - }, - unread: true - }, { message: { en: 'Support for ScalarDB 3.11 will end soon: Please consider upgrading for enhanced features and continued support', diff --git a/versioned_docs/version-3.15/_develop-run-analytical-queries-overview.mdx b/versioned_docs/version-3.15/_develop-run-analytical-queries-overview.mdx new file mode 100644 index 00000000..e2be771f --- /dev/null +++ b/versioned_docs/version-3.15/_develop-run-analytical-queries-overview.mdx @@ -0,0 +1,14 @@ +--- +tags: + - Community + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# Run Analytical Queries Overview + +In this sub-category, you can learn how to set up and configure ScalarDB Analytics, an analytics component of ScalarDB. Then, you can run analytical queries over ScalarDB-managed databases, which are updated through ScalarDB transactions, and non-ScalarDB-managed databases. + +To learn how to run analytical queries, see the following guides: + +- [Run Analytical Queries on Sample Data by Using ScalarDB Analytics with PostgreSQL](scalardb-samples/scalardb-analytics-postgresql-sample/README.mdx) diff --git a/versioned_docs/version-3.15/add-scalardb-to-your-build.mdx b/versioned_docs/version-3.15/add-scalardb-to-your-build.mdx new file mode 100644 index 00000000..976e68d8 --- /dev/null +++ b/versioned_docs/version-3.15/add-scalardb-to-your-build.mdx @@ -0,0 +1,41 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Add ScalarDB to Your Build + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +The ScalarDB library is available on the [Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb). You can add the library as a build dependency to your application by using Gradle or Maven. + +## Configure your application based on your build tool + +Select your build tool, and follow the instructions to add the build dependency for ScalarDB to your application. + + + + To add the build dependency for ScalarDB by using Gradle, add the following to `build.gradle` in your application, replacing `` with the version of ScalarDB that you want to use: + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb:' + } + ``` + + + To add the build dependency for ScalarDB by using Maven, add the following to `pom.xml` in your application, replacing `` with the version of ScalarDB that you want to use: + + ```xml + + com.scalar-labs + scalardb + + + ``` + + diff --git a/versioned_docs/version-3.15/api-guide.mdx b/versioned_docs/version-3.15/api-guide.mdx new file mode 100644 index 00000000..09b28598 --- /dev/null +++ b/versioned_docs/version-3.15/api-guide.mdx @@ -0,0 +1,1700 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Java API Guide + +import JavadocLink from '/src/theme/JavadocLink.js'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +The ScalarDB Java API is mainly composed of the Administrative API and Transactional API. This guide briefly explains what kinds of APIs exist, how to use them, and related topics like how to handle exceptions. + +## Administrative API + +This section explains how to execute administrative operations programmatically by using the Administrative API in ScalarDB. + +:::note + +Another method for executing administrative operations is to use [Schema Loader](schema-loader.mdx). + +::: + +### Get a `DistributedTransactionAdmin` instance + +You first need to get a `DistributedTransactionAdmin` instance to execute administrative operations. + +To get a `DistributedTransactionAdmin` instance, you can use `TransactionFactory` as follows: + +```java +TransactionFactory transactionFactory = TransactionFactory.create(""); +DistributedTransactionAdmin admin = transactionFactory.getTransactionAdmin(); +``` + +For details about configurations, see [ScalarDB Configurations](configurations.mdx). + +After you have executed all administrative operations, you should close the `DistributedTransactionAdmin` instance as follows: + +```java +admin.close(); +``` + +### Create a namespace + +Before creating tables, namespaces must be created since a table belongs to one namespace. + +You can create a namespace as follows: + +```java +// Create the namespace "ns". If the namespace already exists, an exception will be thrown. +admin.createNamespace("ns"); + +// Create the namespace only if it does not already exist. +boolean ifNotExists = true; +admin.createNamespace("ns", ifNotExists); + +// Create the namespace with options. +Map options = ...; +admin.createNamespace("ns", options); +``` + +#### Creation options + +In the creation operations, like creating a namespace and creating a table, you can specify options that are maps of option names and values (`Map`). By using the options, you can set storage adapter–specific configurations. + +Select your database to see the options available: + + + + No options are available for JDBC databases. + + + | Name | Description | Default | + |------------|-----------------------------------------|---------| + | no-scaling | Disable auto-scaling for DynamoDB. | false | + | no-backup | Disable continuous backup for DynamoDB. | false | + | ru | Base resource unit. | 10 | + + + | Name | Description | Default | + |------------|-----------------------------------------------------|---------| + | ru | Base resource unit. | 400 | + | no-scaling | Disable auto-scaling for Cosmos DB for NoSQL. | false | + + + | Name | Description | Default | + |----------------------|----------------------------------------------------------------------------------------|------------------| + | replication-strategy | Cassandra replication strategy. Must be `SimpleStrategy` or `NetworkTopologyStrategy`. | `SimpleStrategy` | + | compaction-strategy | Cassandra compaction strategy, Must be `LCS`, `STCS` or `TWCS`. | `STCS` | + | replication-factor | Cassandra replication factor. | 1 | + + + +### Create a table + +When creating a table, you should define the table metadata and then create the table. + +To define the table metadata, you can use `TableMetadata`. The following shows how to define the columns, partition key, clustering key including clustering orders, and secondary indexes of a table: + +```java +// Define the table metadata. +TableMetadata tableMetadata = + TableMetadata.newBuilder() + .addColumn("c1", DataType.INT) + .addColumn("c2", DataType.TEXT) + .addColumn("c3", DataType.BIGINT) + .addColumn("c4", DataType.FLOAT) + .addColumn("c5", DataType.DOUBLE) + .addPartitionKey("c1") + .addClusteringKey("c2", Scan.Ordering.Order.DESC) + .addClusteringKey("c3", Scan.Ordering.Order.ASC) + .addSecondaryIndex("c4") + .build(); +``` + +For details about the data model of ScalarDB, see [Data Model](design.mdx#data-model). + +Then, create a table as follows: + +```java +// Create the table "ns.tbl". If the table already exists, an exception will be thrown. +admin.createTable("ns", "tbl", tableMetadata); + +// Create the table only if it does not already exist. +boolean ifNotExists = true; +admin.createTable("ns", "tbl", tableMetadata, ifNotExists); + +// Create the table with options. +Map options = ...; +admin.createTable("ns", "tbl", tableMetadata, options); +``` + +### Create a secondary index + +You can create a secondary index as follows: + +```java +// Create a secondary index on column "c5" for table "ns.tbl". If a secondary index already exists, an exception will be thrown. +admin.createIndex("ns", "tbl", "c5"); + +// Create the secondary index only if it does not already exist. +boolean ifNotExists = true; +admin.createIndex("ns", "tbl", "c5", ifNotExists); + +// Create the secondary index with options. +Map options = ...; +admin.createIndex("ns", "tbl", "c5", options); +``` + +### Add a new column to a table + +You can add a new, non-partition key column to a table as follows: + +```java +// Add a new column "c6" with the INT data type to the table "ns.tbl". +admin.addNewColumnToTable("ns", "tbl", "c6", DataType.INT) +``` + +:::warning + +You should carefully consider adding a new column to a table because the execution time may vary greatly depending on the underlying storage. Please plan accordingly and consider the following, especially if the database runs in production: + +- **For Cosmos DB for NoSQL and DynamoDB:** Adding a column is almost instantaneous as the table schema is not modified. Only the table metadata stored in a separate table is updated. +- **For Cassandra:** Adding a column will only update the schema metadata and will not modify the existing schema records. The cluster topology is the main factor for the execution time. Changes to the schema metadata are shared to each cluster node via a gossip protocol. Because of this, the larger the cluster, the longer it will take for all nodes to be updated. +- **For relational databases (MySQL, Oracle, etc.):** Adding a column shouldn't take a long time to execute. + +::: + +### Truncate a table + +You can truncate a table as follows: + +```java +// Truncate the table "ns.tbl". +admin.truncateTable("ns", "tbl"); +``` + +### Drop a secondary index + +You can drop a secondary index as follows: + +```java +// Drop the secondary index on column "c5" from table "ns.tbl". If the secondary index does not exist, an exception will be thrown. +admin.dropIndex("ns", "tbl", "c5"); + +// Drop the secondary index only if it exists. +boolean ifExists = true; +admin.dropIndex("ns", "tbl", "c5", ifExists); +``` + +### Drop a table + +You can drop a table as follows: + +```java +// Drop the table "ns.tbl". If the table does not exist, an exception will be thrown. +admin.dropTable("ns", "tbl"); + +// Drop the table only if it exists. +boolean ifExists = true; +admin.dropTable("ns", "tbl", ifExists); +``` + +### Drop a namespace + +You can drop a namespace as follows: + +```java +// Drop the namespace "ns". If the namespace does not exist, an exception will be thrown. +admin.dropNamespace("ns"); + +// Drop the namespace only if it exists. +boolean ifExists = true; +admin.dropNamespace("ns", ifExists); +``` + +### Get existing namespaces + +You can get the existing namespaces as follows: + +```java +Set namespaces = admin.getNamespaceNames(); +``` + +:::note + +This method extracts the namespace names of user tables dynamically. As a result, only namespaces that contain tables are returned. Starting from ScalarDB 4.0, we plan to improve the design to remove this limitation. + +::: + +### Get the tables of a namespace + +You can get the tables of a namespace as follows: + +```java +// Get the tables of the namespace "ns". +Set tables = admin.getNamespaceTableNames("ns"); +``` + +### Get table metadata + +You can get table metadata as follows: + +```java +// Get the table metadata for "ns.tbl". +TableMetadata tableMetadata = admin.getTableMetadata("ns", "tbl"); +``` +### Repair a table + +You can repair the table metadata of an existing table as follows: + +```java +// Repair the table "ns.tbl" with options. +TableMetadata tableMetadata = + TableMetadata.newBuilder() + ... + .build(); +Map options = ...; +admin.repairTable("ns", "tbl", tableMetadata, options); +``` + +### Specify operations for the Coordinator table + +The Coordinator table is used by the [Transactional API](#transactional-api) to track the statuses of transactions. + +When using a transaction manager, you must create the Coordinator table to execute transactions. In addition to creating the table, you can truncate and drop the Coordinator table. + +#### Create the Coordinator table + +You can create the Coordinator table as follows: + +```java +// Create the Coordinator table. +admin.createCoordinatorTables(); + +// Create the Coordinator table only if one does not already exist. +boolean ifNotExist = true; +admin.createCoordinatorTables(ifNotExist); + +// Create the Coordinator table with options. +Map options = ...; +admin.createCoordinatorTables(options); +``` + +#### Truncate the Coordinator table + +You can truncate the Coordinator table as follows: + +```java +// Truncate the Coordinator table. +admin.truncateCoordinatorTables(); +``` + +#### Drop the Coordinator table + +You can drop the Coordinator table as follows: + +```java +// Drop the Coordinator table. +admin.dropCoordinatorTables(); + +// Drop the Coordinator table if one exist. +boolean ifExist = true; +admin.dropCoordinatorTables(ifExist); +``` + +### Import a table + +You can import an existing table to ScalarDB as follows: + +```java +// Import the table "ns.tbl". If the table is already managed by ScalarDB, the target table does not +// exist, or the table does not meet the requirements of the ScalarDB table, an exception will be thrown. +admin.importTable("ns", "tbl", options, overrideColumnsType); +``` + +:::warning + +You should carefully plan to import a table to ScalarDB in production because it will add transaction metadata columns to your database tables and the ScalarDB metadata tables. In this case, there would also be several differences between your database and ScalarDB, as well as some limitations. For details, see [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](./schema-loader-import.mdx). + + +::: + +## Transactional API + +This section explains how to execute transactional operations by using the Transactional API in ScalarDB. + +### Get a `DistributedTransactionManager` instance + +You first need to get a `DistributedTransactionManager` instance to execute transactional operations. + +To get a `DistributedTransactionManager` instance, you can use `TransactionFactory` as follows: + +```java +TransactionFactory transactionFactory = TransactionFactory.create(""); +DistributedTransactionManager transactionManager = transactionFactory.getTransactionManager(); +``` + +After you have executed all transactional operations, you should close the `DistributedTransactionManager` instance as follows: + +```java +transactionManager.close(); +``` + +### Execute transactions + +This subsection explains how to execute transactions with multiple CRUD operations. + +#### Begin or start a transaction + +Before executing transactional CRUD operations, you need to begin or start a transaction. + +You can begin a transaction as follows: + +```java +// Begin a transaction. +DistributedTransaction transaction = transactionManager.begin(); +``` + +Or, you can start a transaction as follows: + +```java +// Start a transaction. +DistributedTransaction transaction = transactionManager.start(); +``` + +Alternatively, you can use the `begin` method for a transaction by specifying a transaction ID as follows: + +```java +// Begin a transaction with specifying a transaction ID. +DistributedTransaction transaction = transactionManager.begin(""); +``` + +Or, you can use the `start` method for a transaction by specifying a transaction ID as follows: + +```java +// Start a transaction with specifying a transaction ID. +DistributedTransaction transaction = transactionManager.start(""); +``` + +:::note + +Specifying a transaction ID is useful when you want to link external systems to ScalarDB. Otherwise, you should use the `begin()` method or the `start()` method. + +When you specify a transaction ID, make sure you specify a unique ID (for example, UUID v4) throughout the system since ScalarDB depends on the uniqueness of transaction IDs for correctness. + +::: + +#### Join a transaction + +Joining a transaction is particularly useful in a stateful application where a transaction spans multiple client requests. In such a scenario, the application can start a transaction during the first client request. Then, in subsequent client requests, the application can join the ongoing transaction by using the `join()` method. + +You can join an ongoing transaction that has already begun by specifying the transaction ID as follows: + +```java +// Join a transaction. +DistributedTransaction transaction = transactionManager.join(""); +``` + +:::note + +To get the transaction ID with `getId()`, you can specify the following: + +```java +tx.getId(); +``` + +::: + +#### Resume a transaction + +Resuming a transaction is particularly useful in a stateful application where a transaction spans multiple client requests. In such a scenario, the application can start a transaction during the first client request. Then, in subsequent client requests, the application can resume the ongoing transaction by using the `resume()` method. + +You can resume an ongoing transaction that you have already begun by specifying a transaction ID as follows: + +```java +// Resume a transaction. +DistributedTransaction transaction = transactionManager.resume(""); +``` + +:::note + +To get the transaction ID with `getId()`, you can specify the following: + +```java +tx.getId(); +``` + +::: + +#### Implement CRUD operations + +The following sections describe key construction and CRUD operations. + +:::note + +Although all the builders of the CRUD operations can specify consistency by using the `consistency()` methods, those methods are ignored. Instead, the `LINEARIZABLE` consistency level is always used in transactions. + +::: + +##### Key construction + +Most CRUD operations need to specify `Key` objects (partition-key, clustering-key, etc.). So, before moving on to CRUD operations, the following explains how to construct a `Key` object. + +For a single column key, you can use `Key.of()` methods to construct the key as follows: + +```java +// For a key that consists of a single column of INT. +Key key1 = Key.ofInt("col1", 1); + +// For a key that consists of a single column of BIGINT. +Key key2 = Key.ofBigInt("col1", 100L); + +// For a key that consists of a single column of DOUBLE. +Key key3 = Key.ofDouble("col1", 1.3d); + +// For a key that consists of a single column of TEXT. +Key key4 = Key.ofText("col1", "value"); +``` + +For a key that consists of two to five columns, you can use the `Key.of()` method to construct the key as follows. Similar to `ImmutableMap.of()` in Guava, you need to specify column names and values in turns: + +```java +// For a key that consists of two to five columns. +Key key1 = Key.of("col1", 1, "col2", 100L); +Key key2 = Key.of("col1", 1, "col2", 100L, "col3", 1.3d); +Key key3 = Key.of("col1", 1, "col2", 100L, "col3", 1.3d, "col4", "value"); +Key key4 = Key.of("col1", 1, "col2", 100L, "col3", 1.3d, "col4", "value", "col5", false); +``` + +For a key that consists of more than five columns, we can use the builder to construct the key as follows: + +```java +// For a key that consists of more than five columns. +Key key = Key.newBuilder() + .addInt("col1", 1) + .addBigInt("col2", 100L) + .addDouble("col3", 1.3d) + .addText("col4", "value") + .addBoolean("col5", false) + .addInt("col6", 100) + .build(); +``` + +##### `Get` operation + +`Get` is an operation to retrieve a single record specified by a primary key. + +You need to create a `Get` object first, and then you can execute the object by using the `transaction.get()` method as follows: + +```java +// Create a `Get` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .projections("c1", "c2", "c3", "c4") + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .build(); + +// Execute the `Get` operation. +Optional result = transaction.get(get); +``` + +You can specify projections to choose which columns are returned. + +###### Use the `WHERE` clause + +You can also specify arbitrary conditions by using the `where()` method. If the retrieved record does not match the conditions specified by the `where()` method, `Option.empty()` will be returned. As an argument of the `where()` method, you can specify a condition, an AND-wise condition set, or an OR-wise condition set. After calling the `where()` method, you can add more conditions or condition sets by using the `and()` method or `or()` method as follows: + +```java +// Create a `Get` operation with condition sets. +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .where( + ConditionSetBuilder.condition(ConditionBuilder.column("c1").isLessThanInt(10)) + .or(ConditionBuilder.column("c1").isGreaterThanInt(20)) + .build()) + .and( + ConditionSetBuilder.condition(ConditionBuilder.column("c2").isLikeText("a%")) + .or(ConditionBuilder.column("c2").isLikeText("b%")) + .build()) + .build(); +``` + +:::note + +In the `where()` condition method chain, the conditions must be an AND-wise junction of `ConditionalExpression` or `OrConditionSet` (known as conjunctive normal form) like the above example or an OR-wise junction of `ConditionalExpression` or `AndConditionSet` (known as disjunctive normal form). + +::: + +For more details about available conditions and condition sets, see the and pages in the Javadoc. + +###### Handle `Result` objects + +The `Get` operation and `Scan` operation return `Result` objects. The following shows how to handle `Result` objects. + +You can get a column value of a result by using `get("")` methods as follows: + +```java +// Get the BOOLEAN value of a column. +boolean booleanValue = result.getBoolean(""); + +// Get the INT value of a column. +int intValue = result.getInt(""); + +// Get the BIGINT value of a column. +long bigIntValue = result.getBigInt(""); + +// Get the FLOAT value of a column. +float floatValue = result.getFloat(""); + +// Get the DOUBLE value of a column. +double doubleValue = result.getDouble(""); + +// Get the TEXT value of a column. +String textValue = result.getText(""); + +// Get the BLOB value of a column as a `ByteBuffer`. +ByteBuffer blobValue = result.getBlob(""); + +// Get the BLOB value of a column as a `byte` array. +byte[] blobValueAsBytes = result.getBlobAsBytes(""); + +// Get the DATE value of a column as a `LocalDate`. +LocalDate dateValue = result.getDate(""); + +// Get the TIME value of a column as a `LocalTime`. +LocalTime timeValue = result.getTime(""); + +// Get the TIMESTAMP value of a column as a `LocalDateTime`. +LocalDateTime timestampValue = result.getTimestamp(""); + +// Get the TIMESTAMPTZ value of a column as a `Instant`. +Instant timestampTZValue = result.getTimestampTZ(""); +``` + +And if you need to check if a value of a column is null, you can use the `isNull("")` method. + +``` java +// Check if a value of a column is null. +boolean isNull = result.isNull(""); +``` + +For more details, see the page in the Javadoc. + +###### Execute `Get` by using a secondary index + +You can execute a `Get` operation by using a secondary index. + +Instead of specifying a partition key, you can specify an index key (indexed column) to use a secondary index as follows: + +```java +// Create a `Get` operation by using a secondary index. +Key indexKey = Key.ofFloat("c4", 1.23F); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .indexKey(indexKey) + .projections("c1", "c2", "c3", "c4") + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .build(); + +// Execute the `Get` operation. +Optional result = transaction.get(get); +``` + +You can also specify arbitrary conditions by using the `where()` method. For details, see [Use the `WHERE` clause](#use-the-where-clause). + +:::note + +If the result has more than one record, `transaction.get()` will throw an exception. If you want to handle multiple results, see [Execute `Scan` by using a secondary index](#execute-scan-by-using-a-secondary-index). + +::: + +##### `Scan` operation + +`Scan` is an operation to retrieve multiple records within a partition. You can specify clustering-key boundaries and orderings for clustering-key columns in `Scan` operations. + +You need to create a `Scan` object first, and then you can execute the object by using the `transaction.scan()` method as follows: + +```java +// Create a `Scan` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key startClusteringKey = Key.of("c2", "aaa", "c3", 100L); +Key endClusteringKey = Key.of("c2", "aaa", "c3", 300L); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .start(startClusteringKey, true) // Include startClusteringKey + .end(endClusteringKey, false) // Exclude endClusteringKey + .projections("c1", "c2", "c3", "c4") + .orderings(Scan.Ordering.desc("c2"), Scan.Ordering.asc("c3")) + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transaction.scan(scan); +``` + +You can omit the clustering-key boundaries or specify either a `start` boundary or an `end` boundary. If you don't specify `orderings`, you will get results ordered by the clustering order that you defined when creating the table. + +In addition, you can specify `projections` to choose which columns are returned and use `limit` to specify the number of records to return in `Scan` operations. + +###### Use the `WHERE` clause + +You can also specify arbitrary conditions by using the `where()` method to filter scanned records. As an argument of the `where()` method, you can specify a condition, an AND-wise condition set, or an OR-wise condition set. After calling the `where()` method, you can add more conditions or condition sets by using the `and()` method or `or()` method as follows: + +```java +// Create a `Scan` operation with condition sets. +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .where( + ConditionSetBuilder.condition(ConditionBuilder.column("c1").isLessThanInt(10)) + .or(ConditionBuilder.column("c1").isGreaterThanInt(20)) + .build()) + .and( + ConditionSetBuilder.condition(ConditionBuilder.column("c2").isLikeText("a%")) + .or(ConditionBuilder.column("c2").isLikeText("b%")) + .build()) + .limit(10) + .build(); +``` + +:::note + +In the `where()` condition method chain, the conditions must be an AND-wise junction of `ConditionalExpression` or `OrConditionSet` (known as conjunctive normal form) like the above example or an OR-wise junction of `ConditionalExpression` or `AndConditionSet` (known as disjunctive normal form). + +::: + +For more details about available conditions and condition sets, see the and pages in the Javadoc. + +###### Execute `Scan` by using a secondary index + +You can execute a `Scan` operation by using a secondary index. + +Instead of specifying a partition key, you can specify an index key (indexed column) to use a secondary index as follows: + +```java +// Create a `Scan` operation by using a secondary index. +Key indexKey = Key.ofFloat("c4", 1.23F); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .indexKey(indexKey) + .projections("c1", "c2", "c3", "c4") + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transaction.scan(scan); +``` + +You can also specify arbitrary conditions using the `where()` method. For details, see [Use the `WHERE` clause](#use-the-where-clause-1). + +:::note + +You can't specify clustering-key boundaries and orderings in `Scan` by using a secondary index. + +::: + +###### Execute cross-partition `Scan` without specifying a partition key to retrieve all the records of a table + +You can execute a `Scan` operation across all partitions, which we call *cross-partition scan*, without specifying a partition key by enabling the following configuration in the ScalarDB properties file. + +```properties +scalar.db.cross_partition_scan.enabled=true +``` + +:::warning + +For non-JDBC databases, transactions could be executed at read-committed snapshot isolation (`SNAPSHOT`), which is a lower isolation level, even if you enable cross-partition scan with the `SERIALIZABLE` isolation level. When using non-JDBC databases, use cross-partition scan only if consistency does not matter for your transactions. + +::: + +Instead of calling the `partitionKey()` method in the builder, you can call the `all()` method to scan a table without specifying a partition key as follows: + +```java +// Create a `Scan` operation without specifying a partition key. +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .projections("c1", "c2", "c3", "c4") + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transaction.scan(scan); +``` + +:::note + +You can't specify any orderings in cross-partition `Scan` when using non-JDBC databases. For details on how to use cross-partition `Scan` with filtering or ordering, see [Execute cross-partition `Scan` with filtering and ordering](#execute-cross-partition-scan-with-filtering-and-ordering). + +::: + +###### Execute cross-partition `Scan` with filtering and ordering + +By enabling the cross-partition scan option with filtering and ordering as follows, you can execute a cross-partition `Scan` operation with flexible conditions and orderings: + +```properties +scalar.db.cross_partition_scan.enabled=true +scalar.db.cross_partition_scan.filtering.enabled=true +scalar.db.cross_partition_scan.ordering.enabled=true +``` + +:::note + +You can't enable `scalar.db.cross_partition_scan.ordering` in non-JDBC databases. + +::: + +You can call the `where()` and `ordering()` methods after calling the `all()` method to specify arbitrary conditions and orderings as follows: + +```java +// Create a `Scan` operation with arbitrary conditions and orderings. +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .where(ConditionBuilder.column("c1").isNotEqualToInt(10)) + .projections("c1", "c2", "c3", "c4") + .orderings(Scan.Ordering.desc("c3"), Scan.Ordering.asc("c4")) + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transaction.scan(scan); +``` + +For details about the `WHERE` clause, see [Use the `WHERE` clause](#use-the-where-clause-1). + +##### `Put` operation + +:::note + +The `Put` operation is deprecated as of ScalarDB 3.13 and will be removed in a future release. Instead of using the `Put` operation, use the `Insert` operation, the `Upsert` operation, or the `Update` operation. + +::: + +`Put` is an operation to put a record specified by a primary key. The operation behaves as an upsert operation for a record, in which the operation updates the record if the record exists or inserts the record if the record does not exist. + +:::note + +When you update an existing record, you need to read the record by using `Get` or `Scan` before using a `Put` operation. Otherwise, the operation will fail due to a conflict. This occurs because of the specification of ScalarDB to manage transactions properly. Instead of reading the record explicitly, you can enable implicit pre-read. For details, see [Enable implicit pre-read for `Put` operations](#enable-implicit-pre-read-for-put-operations). + +::: + +You need to create a `Put` object first, and then you can execute the object by using the `transaction.put()` method as follows: + +```java +// Create a `Put` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Put` operation. +transaction.put(put); +``` + +You can also put a record with `null` values as follows: + +```java +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", null) + .doubleValue("c5", null) + .build(); +``` + +###### Enable implicit pre-read for `Put` operations + +In Consensus Commit, an application must read a record before mutating the record with `Put` and `Delete` operations to obtain the latest states of the record if the record exists. Instead of reading the record explicitly, you can enable *implicit pre-read*. By enabling implicit pre-read, if an application does not read the record explicitly in a transaction, ScalarDB will read the record on behalf of the application before committing the transaction. + +You can enable implicit pre-read for a `Put` operation by specifying `enableImplicitPreRead()` in the `Put` operation builder as follows: + +```java +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .enableImplicitPreRead() + .build(); +``` + +:::note + +If you are certain that a record you are trying to mutate does not exist, you should not enable implicit pre-read for the `Put` operation for better performance. For example, if you load initial data, you should not enable implicit pre-read. A `Put` operation without implicit pre-read is faster than `Put` operation with implicit pre-read because the operation skips an unnecessary read. + +::: + +##### `Insert` operation + +`Insert` is an operation to insert an entry into the underlying storage through a transaction. If the entry already exists, a conflict error will occur. + +You need to create an `Insert` object first, and then you can execute the object by using the `transaction.insert()` method as follows: + +```java +// Create an `Insert` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Insert insert = + Insert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Insert` operation. +transaction.insert(insert); +``` + +##### `Upsert` operation + +`Upsert` is an operation to insert an entry into or update an entry in the underlying storage through a transaction. If the entry already exists, it will be updated; otherwise, the entry will be inserted. + +You need to create an `Upsert` object first, and then you can execute the object by using the `transaction.upsert()` method as follows: + +```java +// Create an `Upsert` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Upsert upsert = + Upsert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Upsert` operation. +transaction.upsert(upsert); +``` + +##### `Update` operation + +`Update` is an operation to update an entry in the underlying storage through a transaction. If the entry does not exist, the operation will not make any changes. + +You need to create an `Update` object first, and then you can execute the object by using the `transaction.update()` method as follows: + +```java +// Create an `Update` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Update update = + Update.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Update` operation. +transaction.update(update); +``` + +##### `Delete` operation + +`Delete` is an operation to delete a record specified by a primary key. + +:::note + +When you delete a record, you don't have to read the record beforehand because implicit pre-read is always enabled for `Delete` operations. + +::: + +You need to create a `Delete` object first, and then you can execute the object by using the `transaction.delete()` method as follows: + +```java +// Create a `Delete` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .build(); + +// Execute the `Delete` operation. +transaction.delete(delete); +``` + +##### `Put`, `Delete`, and `Update` with a condition + +You can write arbitrary conditions (for example, a bank account balance must be equal to or more than zero) that you require a transaction to meet before being committed by implementing logic that checks the conditions in the transaction. Alternatively, you can write simple conditions in a mutation operation, such as `Put`, `Delete`, and `Update`. + +When a `Put`, `Delete`, or `Update` operation includes a condition, the operation is executed only if the specified condition is met. If the condition is not met when the operation is executed, an exception called `UnsatisfiedConditionException` will be thrown. + +:::note + +When you specify a condition in a `Put` operation, you need to read the record beforehand or enable implicit pre-read. + +::: + +###### Conditions for `Put` + +You can specify a condition in a `Put` operation as follows: + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.putIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .condition(condition) // condition + .build(); + +// Execute the `Put` operation. +transaction.put(put); +``` + +In addition to using the `putIf` condition, you can specify the `putIfExists` and `putIfNotExists` conditions as follows: + +```java +// Build a `putIfExists` condition. +MutationCondition putIfExistsCondition = ConditionBuilder.putIfExists(); + +// Build a `putIfNotExists` condition. +MutationCondition putIfNotExistsCondition = ConditionBuilder.putIfNotExists(); +``` + +###### Conditions for `Delete` + +You can specify a condition in a `Delete` operation as follows: + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.deleteIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .condition(condition) // condition + .build(); + +// Execute the `Delete` operation. +transaction.delete(delete); +``` + +In addition to using the `deleteIf` condition, you can specify the `deleteIfExists` condition as follows: + +```java +// Build a `deleteIfExists` condition. +MutationCondition deleteIfExistsCondition = ConditionBuilder.deleteIfExists(); +``` + +###### Conditions for `Update` + +You can specify a condition in an `Update` operation as follows: + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.updateIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Update update = + Update.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .condition(condition) // condition + .build(); + +// Execute the `Update` operation. +transaction.update(update); +``` + +In addition to using the `updateIf` condition, you can specify the `updateIfExists` condition as follows: + +```java +// Build a `updateIfExists` condition. +MutationCondition updateIfExistsCondition = ConditionBuilder.updateIfExists(); +``` + +##### Mutate operation + +Mutate is an operation to execute multiple operations for `Put`, `Insert`, `Upsert`, `Update`, and `Delete`. + +You need to create mutation objects first, and then you can execute the objects by using the `transaction.mutate()` method as follows: + +```java +// Create `Put` and `Delete` operations. +Key partitionKey = Key.ofInt("c1", 10); + +Key clusteringKeyForPut = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForPut) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +Key clusteringKeyForDelete = Key.of("c2", "bbb", "c3", 200L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForDelete) + .build(); + +// Execute the operations. +transaction.mutate(Arrays.asList(put, delete)); +``` + +##### Default namespace for CRUD operations + +A default namespace for all CRUD operations can be set by using a property in the ScalarDB configuration. + +```properties +scalar.db.default_namespace_name= +``` + +Any operation that does not specify a namespace will use the default namespace set in the configuration. + +```java +// This operation will target the default namespace. +Scan scanUsingDefaultNamespace = + Scan.newBuilder() + .table("tbl") + .all() + .build(); +// This operation will target the "ns" namespace. +Scan scanUsingSpecifiedNamespace = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .build(); +``` + +##### Operation attributes + +The operation attribute is a key-value pair that can be used to store additional information about an operation. You can set operation attributes by using the `attribute()` or `attributes()` method in the operation builder, as shown below: + +```java +// Set operation attributes in the `Get` operation. +Get get = Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Scan` operation. +Scan scan = Scan.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .projections("c1", "c2", "c3", "c4") + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Insert` operation. +Insert insert = Insert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Upsert` operation. +Upsert upsert = Upsert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Update` operation. +Update update = Update.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); + +// Set operation attributes in the `Delete` operation. +Delete delete = Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .attribute("attribute1", "value1") + .attributes(ImmutableMap.of("attribute2", "value2", "attribute3", "value3")) + .build(); +``` + +:::note + +ScalarDB currently has no available operation attributes. + +::: + +#### Commit a transaction + +After executing CRUD operations, you need to commit a transaction to finish it. + +You can commit a transaction as follows: + +```java +// Commit a transaction. +transaction.commit(); +``` + +#### Roll back or abort a transaction + +If an error occurs when executing a transaction, you can roll back or abort the transaction. + +You can roll back a transaction as follows: + +```java +// Roll back a transaction. +transaction.rollback(); +``` + +Or, you can abort a transaction as follows: + +```java +// Abort a transaction. +transaction.abort(); +``` + +For details about how to handle exceptions in ScalarDB, see [How to handle exceptions](#how-to-handle-exceptions). + +### Execute transactions without beginning or starting a transaction + +You can execute transactional operations without beginning or starting a transaction. In this case, ScalarDB will automatically begin a transaction before executing the operations and commit the transaction after executing the operations. This section explains how to execute transactions without beginning or starting a transaction. + +#### Execute `Get` operation + +`Get` is an operation to retrieve a single record specified by a primary key. + +You need to create a `Get` object first, and then you can execute the object by using the `transactionManager.get()` method as follows: + +```java +// Create a `Get` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .projections("c1", "c2", "c3", "c4") + .build(); + +// Execute the `Get` operation. +Optional result = transactionManager.get(get); +``` + +For details about the `Get` operation, see [`Get` operation](#get-operation). + +#### Execute `Scan` operation + +`Scan` is an operation to retrieve multiple records within a partition. You can specify clustering-key boundaries and orderings for clustering-key columns in `Scan` operations. + +You need to create a `Scan` object first, and then you can execute the object by using the `transactionManager.scan()` method as follows: + +```java +// Create a `Scan` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key startClusteringKey = Key.of("c2", "aaa", "c3", 100L); +Key endClusteringKey = Key.of("c2", "aaa", "c3", 300L); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .start(startClusteringKey, true) // Include startClusteringKey + .end(endClusteringKey, false) // Exclude endClusteringKey + .projections("c1", "c2", "c3", "c4") + .orderings(Scan.Ordering.desc("c2"), Scan.Ordering.asc("c3")) + .limit(10) + .build(); + +// Execute the `Scan` operation. +List results = transactionManager.scan(scan); +``` + +For details about the `Scan` operation, see [`Scan` operation](#scan-operation). + +#### Execute `Put` operation + +:::note + +The `Put` operation is deprecated as of ScalarDB 3.13 and will be removed in a future release. Instead of using the `Put` operation, use the `Insert` operation, the `Upsert` operation, or the `Update` operation. + +::: + +You need to create a `Put` object first, and then you can execute the object by using the `transactionManager.put()` method as follows: + +```java +// Create a `Put` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Put` operation. +transactionManager.put(put); +``` + +For details about the `Put` operation, see [`Put` operation](#put-operation). + +#### Execute `Insert` operation + +`Insert` is an operation to insert an entry into the underlying storage through a transaction. If the entry already exists, a conflict error will occur. + +You need to create an `Insert` object first, and then you can execute the object by using the `transactionManager.insert()` method as follows: + +```java +// Create an `Insert` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Insert insert = + Insert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Insert` operation. +transactionManager.insert(insert); +``` + +For details about the `Insert` operation, see [`Insert` operation](#insert-operation). + +#### Execute `Upsert` operation + +`Upsert` is an operation to insert an entry into or update an entry in the underlying storage through a transaction. If the entry already exists, it will be updated; otherwise, the entry will be inserted. + +You need to create an `Upsert` object first, and then you can execute the object by using the `transactionManager.upsert()` method as follows: + +```java +// Create an `Upsert` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Upsert upsert = + Upsert.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Upsert` operation. +transactionManager.upsert(upsert); +``` + +For details about the `Insert` operation, see [`Upsert` operation](#upsert-operation). + +#### Execute `Update` operation + +`Update` is an operation to update an entry in the underlying storage through a transaction. If the entry does not exist, the operation will not make any changes. + +You need to create an `Update` object first, and then you can execute the object by using the `transactionManager.update()` method as follows: + +```java +// Create an `Update` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Update update = + Update.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Update` operation. +transactionManager.update(update); +``` + +For details about the `Update` operation, see [`Update` operation](#update-operation). + +#### Execute `Delete` operation + +`Delete` is an operation to delete a record specified by a primary key. + +You need to create a `Delete` object first, and then you can execute the object by using the `transaction.delete()` method as follows: + +```java +// Create a `Delete` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .build(); + +// Execute the `Delete` operation. +transactionManager.delete(delete); +``` + +For details about the `Delete` operation, see [`Delete` operation](#delete-operation). + +#### Execute Mutate operation + +Mutate is an operation to execute multiple mutations (`Put`, `Insert`, `Upsert`, `Update`, and `Delete` operations). + +You need to create mutation objects first, and then you can execute the objects by using the `transactionManager.mutate()` method as follows: + +```java +// Create `Put` and `Delete` operations. +Key partitionKey = Key.ofInt("c1", 10); + +Key clusteringKeyForPut = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForPut) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +Key clusteringKeyForDelete = Key.of("c2", "bbb", "c3", 200L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForDelete) + .build(); + +// Execute the operations. +transactionManager.mutate(Arrays.asList(put, delete)); +``` + +For details about the Mutate operation, see [Mutate operation](#mutate-operation). + +In addition, for details about how to handle exceptions in ScalarDB, see [How to handle exceptions](#how-to-handle-exceptions). + +## How to handle exceptions + +When executing a transaction, you will also need to handle exceptions properly. + +:::warning + +If you don't handle exceptions properly, you may face anomalies or data inconsistency. + +::: + +The following sample code shows how to handle exceptions: + +```java +public class Sample { + public static void main(String[] args) throws Exception { + TransactionFactory factory = TransactionFactory.create(""); + DistributedTransactionManager transactionManager = factory.getTransactionManager(); + + int retryCount = 0; + TransactionException lastException = null; + + while (true) { + if (retryCount++ > 0) { + // Retry the transaction three times maximum. + if (retryCount >= 3) { + // Throw the last exception if the number of retries exceeds the maximum. + throw lastException; + } + + // Sleep 100 milliseconds before retrying the transaction. + TimeUnit.MILLISECONDS.sleep(100); + } + + DistributedTransaction transaction = null; + try { + // Begin a transaction. + transaction = transactionManager.begin(); + + // Execute CRUD operations in the transaction. + Optional result = transaction.get(...); + List results = transaction.scan(...); + transaction.put(...); + transaction.delete(...); + + // Commit the transaction. + transaction.commit(); + } catch (UnsatisfiedConditionException e) { + // You need to handle `UnsatisfiedConditionException` only if a mutation operation specifies a condition. + // This exception indicates the condition for the mutation operation is not met. + + try { + transaction.rollback(); + } catch (RollbackException ex) { + // Rolling back the transaction failed. Since the transaction should eventually recover, + // you don't need to do anything further. You can simply log the occurrence here. + } + + // You can handle the exception here, according to your application requirements. + + return; + } catch (UnknownTransactionStatusException e) { + // If you catch `UnknownTransactionStatusException` when committing the transaction, + // it indicates that the status of the transaction, whether it was successful or not, is unknown. + // In such a case, you need to check if the transaction is committed successfully or not and + // retry the transaction if it failed. How to identify a transaction status is delegated to users. + return; + } catch (TransactionException e) { + // For other exceptions, you can try retrying the transaction. + + // For `CrudConflictException`, `CommitConflictException`, and `TransactionNotFoundException`, + // you can basically retry the transaction. However, for the other exceptions, the transaction + // will still fail if the cause of the exception is non-transient. In such a case, you will + // exhaust the number of retries and throw the last exception. + + if (transaction != null) { + try { + transaction.rollback(); + } catch (RollbackException ex) { + // Rolling back the transaction failed. The transaction should eventually recover, + // so you don't need to do anything further. You can simply log the occurrence here. + } + } + + lastException = e; + } + } + } +} +``` + +### `TransactionException` and `TransactionNotFoundException` + +The `begin()` API could throw `TransactionException` or `TransactionNotFoundException`: + +- If you catch `TransactionException`, this exception indicates that the transaction has failed to begin due to transient or non-transient faults. You can try retrying the transaction, but you may not be able to begin the transaction due to non-transient faults. +- If you catch `TransactionNotFoundException`, this exception indicates that the transaction has failed to begin due to transient faults. In this case, you can retry the transaction. + +The `join()` API could also throw `TransactionNotFoundException`. You can handle this exception in the same way that you handle the exceptions for the `begin()` API. + +### `CrudException` and `CrudConflictException` + +The APIs for CRUD operations (`get()`, `scan()`, `put()`, `delete()`, and `mutate()`) could throw `CrudException` or `CrudConflictException`: + +- If you catch `CrudException`, this exception indicates that the transaction CRUD operation has failed due to transient or non-transient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is non-transient. +- If you catch `CrudConflictException`, this exception indicates that the transaction CRUD operation has failed due to transient faults (for example, a conflict error). In this case, you can retry the transaction from the beginning. + +### `UnsatisfiedConditionException` + +The APIs for mutation operations (`put()`, `delete()`, and `mutate()`) could also throw `UnsatisfiedConditionException`. + +If you catch `UnsatisfiedConditionException`, this exception indicates that the condition for the mutation operation is not met. You can handle this exception according to your application requirements. + +### `CommitException`, `CommitConflictException`, and `UnknownTransactionStatusException` + +The `commit()` API could throw `CommitException`, `CommitConflictException`, or `UnknownTransactionStatusException`: + +- If you catch `CommitException`, this exception indicates that committing the transaction fails due to transient or non-transient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is non-transient. +- If you catch `CommitConflictException`, this exception indicates that committing the transaction has failed due to transient faults (for example, a conflict error). In this case, you can retry the transaction from the beginning. +- If you catch `UnknownTransactionStatusException`, this exception indicates that the status of the transaction, whether it was successful or not, is unknown. In this case, you need to check if the transaction is committed successfully and retry the transaction if it has failed. + +How to identify a transaction status is delegated to users. You may want to create a transaction status table and update it transactionally with other application data so that you can get the status of a transaction from the status table. + +### Notes about some exceptions + +Although not illustrated in the sample code, the `resume()` API could also throw `TransactionNotFoundException`. This exception indicates that the transaction associated with the specified ID was not found and/or the transaction might have expired. In either case, you can retry the transaction from the beginning since the cause of this exception is basically transient. + +In the sample code, for `UnknownTransactionStatusException`, the transaction is not retried because the application must check if the transaction was successful to avoid potential duplicate operations. For other exceptions, the transaction is retried because the cause of the exception is transient or non-transient. If the cause of the exception is transient, the transaction may succeed if you retry it. However, if the cause of the exception is non-transient, the transaction will still fail even if you retry it. In such a case, you will exhaust the number of retries. + +:::note + +In the sample code, the transaction is retried three times maximum and sleeps for 100 milliseconds before it is retried. But you can choose a retry policy, such as exponential backoff, according to your application requirements. + +::: + +## Group commit for the Coordinator table + +The Coordinator table that is used for Consensus Commit transactions is a vital data store, and using robust storage for it is recommended. However, utilizing more robust storage options, such as internally leveraging multi-AZ or multi-region replication, may lead to increased latency when writing records to the storage, resulting in poor throughput performance. + +ScalarDB provides a group commit feature for the Coordinator table that groups multiple record writes into a single write operation, improving write throughput. In this case, latency may increase or decrease, depending on the underlying database and the workload. + +To enable the group commit feature, add the following configuration: + +```properties +# By default, this configuration is set to `false`. +scalar.db.consensus_commit.coordinator.group_commit.enabled=true + +# These properties are for tuning the performance of the group commit feature. +# scalar.db.consensus_commit.coordinator.group_commit.group_size_fix_timeout_millis=40 +# scalar.db.consensus_commit.coordinator.group_commit.delayed_slot_move_timeout_millis=800 +# scalar.db.consensus_commit.coordinator.group_commit.old_group_abort_timeout_millis=30000 +# scalar.db.consensus_commit.coordinator.group_commit.timeout_check_interval_millis=10 +# scalar.db.consensus_commit.coordinator.group_commit.metrics_monitor_log_enabled=true +``` + +### Limitations + +This section describes the limitations of the group commit feature. + +#### Custom transaction ID passed by users + +The group commit feature implicitly generates an internal value and uses it as a part of transaction ID. Therefore, a custom transaction ID manually passed by users via `com.scalar.db.transaction.consensuscommit.ConsensusCommitManager.begin(String txId)` or `com.scalar.db.transaction.consensuscommit.TwoPhaseConsensusCommitManager.begin(String txId)` can't be used as is for later API calls. You need to use a transaction ID returned from`com.scalar.db.transaction.consensuscommit.ConsensusCommit.getId()` or `com.scalar.db.transaction.consensuscommit.TwoPhaseConsensusCommit.getId()` instead. + +```java + // This custom transaction ID needs to be used for ScalarDB transactions. + String myTxId = UUID.randomUUID().toString(); + + ... + + DistributedTransaction transaction = manager.begin(myTxId); + + ... + + // When the group commit feature is enabled, a custom transaction ID passed by users can't be used as is. + // logger.info("The transaction state: {}", manager.getState(myTxId)); + logger.info("The transaction state: {}", manager.getState(transaction.getId())); +``` + +#### Prohibition of use with a two-phase commit interface + +The group commit feature manages all ongoing transactions in memory. If this feature is enabled with a two-phase commit interface, the information must be solely maintained by the coordinator service to prevent conflicts caused by participant services' inconsistent writes to the Coordinator table, which may contain different transaction distributions over groups. + +This limitation introduces some complexities and inflexibilities related to application development. Therefore, combining the use of the group commit feature with a two-phase commit interface is currently prohibited. + +##### Enabling the feature on existing applications is not supported + +The group commit feature uses a new column in the Coordinator table. The current [Schema Loader](schema-loader.mdx), as of ScalarDB 3, doesn't support table schema migration for the Coordinator table. + +Therefore, enabling the group commit feature on existing applications where any transactions have been executed is not supported. To use this feature, you'll need to start your application in a clean state. + +Coordinator table schema migration in [Schema Loader](schema-loader.mdx) is expected to be supported in ScalarDB 4.0. + +## Investigating Consensus Commit transaction manager errors + +To investigate errors when using the Consensus Commit transaction manager, you can enable a configuration that will return table metadata augmented with transaction metadata columns, which can be helpful when investigating transaction-related issues. This configuration, which is only available when troubleshooting the Consensus Commit transaction manager, enables you to see transaction metadata column details for a given table by using the `DistributedTransactionAdmin.getTableMetadata()` method. + +By adding the following configuration, `Get` and `Scan` operations results will contain [transaction metadata](schema-loader.mdx#internal-metadata-for-consensus-commit): + +```properties +# By default, this configuration is set to `false`. +scalar.db.consensus_commit.include_metadata.enabled=true +``` diff --git a/versioned_docs/version-3.15/backup-restore.mdx b/versioned_docs/version-3.15/backup-restore.mdx new file mode 100644 index 00000000..55db1dbf --- /dev/null +++ b/versioned_docs/version-3.15/backup-restore.mdx @@ -0,0 +1,178 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to Back Up and Restore Databases Used Through ScalarDB + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +Since ScalarDB provides transaction capabilities on top of non-transactional or transactional databases non-invasively, you need to take special care to back up and restore the databases in a transactionally consistent way. + +This guide describes how to back up and restore the databases that ScalarDB supports. + +## Create a backup + +How you create a backup depends on which database you're using and whether or not you're using multiple databases. The following decision tree shows which approach you should take. + +```mermaid +flowchart TD + A[Are you using a single database with ScalarDB?] + A -->|Yes| B[Does the database have transaction support?] + B -->|Yes| C[Perform back up without explicit pausing] + B ---->|No| D[Perform back up with explicit pausing] + A ---->|No| D +``` + +### Back up without explicit pausing + +If you're using ScalarDB with a single database with support for transactions, you can create a backup of the database even while ScalarDB continues to accept transactions. + +:::warning + +Before creating a backup, you should consider the safest way to create a transactionally consistent backup of your databases and understand any risks that are associated with the backup process. + +::: + +One requirement for creating a backup in ScalarDB is that backups for all the ScalarDB-managed tables (including the Coordinator table) need to be transactionally consistent or automatically recoverable to a transactionally consistent state. That means that you need to create a consistent backup by dumping all tables in a single transaction. + +How you create a transactionally consistent backup depends on the type of database that you're using. Select a database to see how to create a transactionally consistent backup for ScalarDB. + +:::note + +The backup methods by database listed below are just examples of some of the databases that ScalarDB supports. + +::: + + + + You can restore to any point within the backup retention period by using the automated backup feature. + + + Use the `mysqldump` command with the `--single-transaction` option. + + + Use the `pg_dump` command. + + + Use the `.backup` command with the `.timeout` command as specified in [Special commands to sqlite3 (dot-commands)](https://www.sqlite.org/cli.html#special_commands_to_sqlite3_dot_commands_) + + For an example, see [BASH: SQLite3 .backup command](https://stackoverflow.com/questions/23164445/bash-sqlite3-backup-command). + + + Clusters are backed up automatically based on the backup policy, and these backups are retained for a specific duration. You can also perform on-demand backups. For details on performing backups, see [YugabyteDB Managed: Back up and restore clusters](https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-clusters/backup-clusters/). + + + +### Back up with explicit pausing + +Another way to create a transactionally consistent backup is to create a backup while a cluster of ScalarDB instances does not have any outstanding transactions. Creating the backup depends on the following: + +- If the underlying database has a point-in-time snapshot or backup feature, you can create a backup during the period when no outstanding transactions exist. +- If the underlying database has a point-in-time restore or recovery (PITR) feature, you can set a restore point to a time (preferably the mid-time) in the pause duration period when no outstanding transactions exist. + +:::note + +When using a PITR feature, you should minimize the clock drifts between clients and servers by using clock synchronization, such as NTP. Otherwise, the time you get as the paused duration might be too different from the time in which the pause was actually conducted, which could restore the backup to a point where ongoing transactions exist. + +In addition, you should pause for a sufficient amount of time (for example, five seconds) and use the mid-time of the paused duration as a restore point since clock synchronization cannot perfectly synchronize clocks between nodes. + +::: + +To make ScalarDB drain outstanding requests and stop accepting new requests so that a pause duration can be created, you should implement the [Scalar Admin](https://github.com/scalar-labs/scalar-admin) interface properly in your application that uses ScalarDB or use [ScalarDB Cluster](scalardb-cluster/index.mdx), which implements the Scalar Admin interface. + +By using the [Scalar Admin client tool](https://github.com/scalar-labs/scalar-admin/blob/main/README.md#scalar-admin-client-tool), you can pause nodes, servers, or applications that implement the Scalar Admin interface without losing ongoing transactions. + +How you create a transactionally consistent backup depends on the type of database that you're using. Select a database to see how to create a transactionally consistent backup for ScalarDB. + +:::note + +The backup methods by database listed below are just examples of some of the databases that ScalarDB supports. + +::: + + + + You must enable the PITR feature for DynamoDB tables. If you're using [ScalarDB Schema Loader](schema-loader.mdx) to create schemas, the tool enables the PITR feature for tables by default. + + To specify a transactionally consistent restore point, pause your application that is using ScalarDB with DynamoDB as described in [Back up with explicit pausing](#back-up-with-explicit-pausing). + + + You must create a Cosmos DB for NoSQL account with a continuous backup policy that has the PITR feature enabled. After enabling the feature, backups are created continuously. + + To specify a transactionally consistent restore point, pause your application that is using ScalarDB with Cosmos DB for NoSQL as described in [Back up with explicit pausing](#back-up-with-explicit-pausing). + + + Cassandra has a built-in replication feature, so you do not always have to create a transactionally consistent backup. For example, if the replication factor is set to `3` and only the data of one of the nodes in a Cassandra cluster is lost, you won't need a transactionally consistent backup (snapshot) because the node can be recovered by using a normal, transactionally inconsistent backup (snapshot) and the repair feature. + + However, if the quorum of cluster nodes loses their data, you will need a transactionally consistent backup (snapshot) to restore the cluster to a certain transactionally consistent point. + + To create a transactionally consistent cluster-wide backup (snapshot), pause the application that is using ScalarDB or [ScalarDB Cluster](scalardb-cluster/index.mdx) and create backups (snapshots) of the nodes as described in [Back up with explicit pausing](#back-up-with-explicit-pausing) or stop the Cassandra cluster, take copies of all the data in the nodes, and start the cluster. + + + You can perform on-demand backups or scheduled backups during a paused duration. For details on performing backups, see [YugabyteDB Managed: Back up and restore clusters](https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-clusters/backup-clusters/). + + + +## Restore a backup + +How you restore a transactionally consistent backup depends on the type of database that you're using. Select a database to see how to create a transactionally consistent backup for ScalarDB. + +:::note + +The restore methods by database listed below are just examples of some of the databases that ScalarDB supports. + +::: + + + + You can restore to any point within the backup retention period by using the automated backup feature. + + + First, stop all the nodes of the Cassandra cluster. Then, clean the `data`, `commitlog`, and `hints` directories, and place the backups (snapshots) in each node. + + After placing the backups (snapshots) in each node, start all the nodes of the Cassandra Cluster. + + + Follow the official Azure documentation for [restore an account by using Azure portal](https://docs.microsoft.com/en-us/azure/cosmos-db/restore-account-continuous-backup#restore-account-portal). After restoring a backup, [configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level) of the restored databases to `STRONG`. In addition, you should use the mid-time of the paused duration as the restore point as previously explained. + + ScalarDB implements the Cosmos DB adapter by using its stored procedures, which are installed when creating schemas by using ScalarDB Schema Loader. However, the PITR feature of Cosmos DB doesn't restore stored procedures. Because of this, you need to re-install the required stored procedures for all tables after restoration. You can do this by using ScalarDB Schema Loader with the `--repair-all` option. For details, see [Repair tables](schema-loader.mdx#repair-tables). + + + Follow the official AWS documentation for [restoring a DynamoDB table to a point in time](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/PointInTimeRecovery.Tutorial.html), but keep in mind that a table can only be restored with an alias. Because of this, you will need to restore the table with an alias, delete the original table, and rename the alias to the original name to restore the tables with the same name. + + To do this procedure: + + 1. Create a backup. + 1. Select the mid-time of the paused duration as the restore point. + 2. Restore by using the PITR of table A to table B. + 3. Create a backup of the restored table B (assuming that the backup is named backup B). + 4. Remove table B. + 2. Restore the backup. + 1. Remove table A. + 2. Create a table named A by using backup B. + +:::note + +* You must do the steps mentioned above for each table because tables can only be restored one at a time. +* Configurations such as PITR and auto-scaling policies are reset to the default values for restored tables, so you must manually configure the required settings. For details, see the official AWS documentation for [How to restore DynamoDB tables with DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CreateBackup.html#CreateBackup_HowItWorks-restore). + +::: + + + If you used `mysqldump` to create the backup file, use the `mysql` command to restore the backup as specified in [Reloading SQL-Format Backups](https://dev.mysql.com/doc/mysql-backup-excerpt/8.0/en/reloading-sql-format-dumps.html). + + + If you used `pg_dump` to create the backup file, use the `psql` command to restore the backup as specified in [Restoring the Dump](https://www.postgresql.org/docs/current/backup-dump.html#BACKUP-DUMP-RESTORE). + + + Use the `.restore` command as specified in [Special commands to sqlite3 (dot-commands)](https://www.sqlite.org/cli.html#special_commands_to_sqlite3_dot_commands_). + + + You can restore from the scheduled or on-demand backup within the backup retention period. For details on performing backups, see [YugabyteDB Managed: Back up and restore clusters](https://docs.yugabyte.com/preview/yugabyte-cloud/cloud-clusters/backup-clusters/). + + diff --git a/versioned_docs/version-3.15/configurations.mdx b/versioned_docs/version-3.15/configurations.mdx new file mode 100644 index 00000000..5a05fd51 --- /dev/null +++ b/versioned_docs/version-3.15/configurations.mdx @@ -0,0 +1,232 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Core Configurations + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This page describes the available configurations for ScalarDB Core. + +:::tip + +If you are using ScalarDB Cluster, please refer to [ScalarDB Cluster Configurations](./scalardb-cluster/scalardb-cluster-configurations.mdx) instead. + +::: + +## General configurations + +The following configurations are available for the Consensus Commit transaction manager: + +| Name | Description | Default | +|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------| +| `scalar.db.transaction_manager` | Transaction manager of ScalarDB. Specify `consensus-commit` to use [Consensus Commit](./consensus-commit.mdx) or `single-crud-operation` to [run non-transactional storage operations](./run-non-transactional-storage-operations-through-library.mdx). Note that the configurations under the `scalar.db.consensus_commit` prefix are ignored if you use `single-crud-operation`. | `consensus-commit` | +| `scalar.db.consensus_commit.isolation_level` | Isolation level used for Consensus Commit. Either `SNAPSHOT` or `SERIALIZABLE` can be specified. | `SNAPSHOT` | +| `scalar.db.consensus_commit.serializable_strategy` | Serializable strategy used for Consensus Commit. Either `EXTRA_READ` or `EXTRA_WRITE` can be specified. If `SNAPSHOT` is specified in the property `scalar.db.consensus_commit.isolation_level`, this configuration will be ignored. | `EXTRA_READ` | +| `scalar.db.consensus_commit.coordinator.namespace` | Namespace name of Coordinator tables. | `coordinator` | +| `scalar.db.consensus_commit.include_metadata.enabled` | If set to `true`, `Get` and `Scan` operations results will contain transaction metadata. To see the transaction metadata columns details for a given table, you can use the `DistributedTransactionAdmin.getTableMetadata()` method, which will return the table metadata augmented with the transaction metadata columns. Using this configuration can be useful to investigate transaction-related issues. | `false` | + +## Performance-related configurations + +The following performance-related configurations are available for the Consensus Commit transaction manager: + +| Name | Description | Default | +|----------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------| +| `scalar.db.consensus_commit.parallel_executor_count` | Number of executors (threads) for parallel execution. This number refers to the total number of threads across transactions in a ScalarDB Cluster node or a ScalarDB process. | `128` | +| `scalar.db.consensus_commit.parallel_preparation.enabled` | Whether or not the preparation phase is executed in parallel. | `true` | +| `scalar.db.consensus_commit.parallel_validation.enabled` | Whether or not the validation phase (in `EXTRA_READ`) is executed in parallel. | The value of `scalar.db.consensus_commit.parallel_commit.enabled` | +| `scalar.db.consensus_commit.parallel_commit.enabled` | Whether or not the commit phase is executed in parallel. | `true` | +| `scalar.db.consensus_commit.parallel_rollback.enabled` | Whether or not the rollback phase is executed in parallel. | The value of `scalar.db.consensus_commit.parallel_commit.enabled` | +| `scalar.db.consensus_commit.async_commit.enabled` | Whether or not the commit phase is executed asynchronously. | `false` | +| `scalar.db.consensus_commit.async_rollback.enabled` | Whether or not the rollback phase is executed asynchronously. | The value of `scalar.db.consensus_commit.async_commit.enabled` | +| `scalar.db.consensus_commit.parallel_implicit_pre_read.enabled` | Whether or not implicit pre-read is executed in parallel. | `true` | +| `scalar.db.consensus_commit.coordinator.group_commit.enabled` | Whether or not committing the transaction state is executed in batch mode. This feature can't be used with a two-phase commit interface. | `false` | +| `scalar.db.consensus_commit.coordinator.group_commit.slot_capacity` | Maximum number of slots in a group for the group commit feature. A large value improves the efficiency of group commit, but may also increase latency and the likelihood of transaction conflicts.[^1] | `20` | +| `scalar.db.consensus_commit.coordinator.group_commit.group_size_fix_timeout_millis` | Timeout to fix the size of slots in a group. A large value improves the efficiency of group commit, but may also increase latency and the likelihood of transaction conflicts.[^1] | `40` | +| `scalar.db.consensus_commit.coordinator.group_commit.delayed_slot_move_timeout_millis` | Timeout to move delayed slots from a group to another isolated group to prevent the original group from being affected by delayed transactions. A large value improves the efficiency of group commit, but may also increase the latency and the likelihood of transaction conflicts.[^1] | `1200` | +| `scalar.db.consensus_commit.coordinator.group_commit.old_group_abort_timeout_millis` | Timeout to abort an old ongoing group. A small value reduces resource consumption through aggressive aborts, but may also increase the likelihood of unnecessary aborts for long-running transactions. | `60000` | +| `scalar.db.consensus_commit.coordinator.group_commit.timeout_check_interval_millis` | Interval for checking the group commit–related timeouts. | `20` | +| `scalar.db.consensus_commit.coordinator.group_commit.metrics_monitor_log_enabled` | Whether or not the metrics of the group commit are logged periodically. | `false` | + +## Storage-related configurations + +ScalarDB has a storage (database) abstraction layer that supports multiple storage implementations. You can specify the storage implementation by using the `scalar.db.storage` property. + +Select a database to see the configurations available for each storage. + + + + The following configurations are available for JDBC databases: + + | Name | Description | Default | + |------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| + | `scalar.db.storage` | `jdbc` must be specified. | - | + | `scalar.db.contact_points` | JDBC connection URL. | | + | `scalar.db.username` | Username to access the database. | | + | `scalar.db.password` | Password to access the database. | | + | `scalar.db.jdbc.connection_pool.min_idle` | Minimum number of idle connections in the connection pool. | `20` | + | `scalar.db.jdbc.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool. | `50` | + | `scalar.db.jdbc.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool. Use a negative value for no limit. | `100` | + | `scalar.db.jdbc.prepared_statements_pool.enabled` | Setting this property to `true` enables prepared-statement pooling. | `false` | + | `scalar.db.jdbc.prepared_statements_pool.max_open` | Maximum number of open statements that can be allocated from the statement pool at the same time. Use a negative value for no limit. | `-1` | + | `scalar.db.jdbc.isolation_level` | Isolation level for JDBC. `READ_UNCOMMITTED`, `READ_COMMITTED`, `REPEATABLE_READ`, or `SERIALIZABLE` can be specified. | Underlying-database specific | + | `scalar.db.jdbc.table_metadata.schema` | Schema name for the table metadata used for ScalarDB. | `scalardb` | + | `scalar.db.jdbc.table_metadata.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for the table metadata. | `5` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for the table metadata. | `10` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for the table metadata. Use a negative value for no limit. | `25` | + | `scalar.db.jdbc.admin.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for admin. | `5` | + | `scalar.db.jdbc.admin.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for admin. | `10` | + | `scalar.db.jdbc.admin.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for admin. Use a negative value for no limit. | `25` | + | `scalar.db.jdbc.mysql.variable_key_column_size` | Column size for TEXT and BLOB columns in MySQL when they are used as a primary key or secondary key. Minimum 64 bytes. | `128` | + | `scalar.db.jdbc.oracle.variable_key_column_size` | Column size for TEXT and BLOB columns in Oracle when they are used as a primary key or secondary key. Minimum 64 bytes. | `128` | + | `scalar.db.jdbc.oracle.time_column.default_date_component` | Value of the date component used for storing `TIME` data in Oracle. Since Oracle has no data type to only store a time without a date component, ScalarDB stores `TIME` data with the same date component value for ease of comparison and sorting. | `1970-01-01` | + +:::note + +**SQLite3** + +If you're using SQLite3 as a JDBC database, you must set `scalar.db.contact_points` as follows: + +```properties +scalar.db.contact_points=jdbc:sqlite:?busy_timeout=10000 +``` + +Unlike other JDBC databases, [SQLite3 doesn't fully support concurrent access](https://www.sqlite.org/lang_transaction.html). To avoid frequent errors caused internally by [`SQLITE_BUSY`](https://www.sqlite.org/rescode.html#busy), setting a [`busy_timeout`](https://www.sqlite.org/c3ref/busy_timeout.html) parameter is recommended. + +**YugabyteDB** + +If you're using YugabyteDB as a JDBC database, you can specify multiple endpoints in `scalar.db.contact_points` as follows: + +```properties +scalar.db.contact_points=jdbc:yugabytedb://127.0.0.1:5433\\,127.0.0.2:5433\\,127.0.0.3:5433/?load-balance=true +``` + +Multiple endpoints should be separated by escaped commas. + +For information on YugabyteDB's smart driver and load balancing, see [YugabyteDB smart drivers for YSQL](https://docs.yugabyte.com/preview/drivers-orms/smart-drivers/). + +::: + + + + The following configurations are available for DynamoDB: + + | Name | Description | Default | + |---------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------| + | `scalar.db.storage` | `dynamo` must be specified. | - | + | `scalar.db.contact_points` | AWS region with which ScalarDB should communicate (e.g., `us-east-1`). | | + | `scalar.db.username` | AWS access key used to identify the user interacting with AWS. | | + | `scalar.db.password` | AWS secret access key used to authenticate the user interacting with AWS. | | + | `scalar.db.dynamo.endpoint_override` | Amazon DynamoDB endpoint with which ScalarDB should communicate. This is primarily used for testing with a local instance instead of an AWS service. | | + | `scalar.db.dynamo.table_metadata.namespace` | Namespace name for the table metadata used for ScalarDB. | `scalardb` | + | `scalar.db.dynamo.namespace.prefix` | Prefix for the user namespaces and metadata namespace names. Since AWS requires having unique tables names in a single AWS region, this is useful if you want to use multiple ScalarDB environments (development, production, etc.) in a single AWS region. | | + + + The following configurations are available for CosmosDB for NoSQL: + + | Name | Description | Default | + |--------------------------------------------|----------------------------------------------------------------------------------------------------------|------------| + | `scalar.db.storage` | `cosmos` must be specified. | - | + | `scalar.db.contact_points` | Azure Cosmos DB for NoSQL endpoint with which ScalarDB should communicate. | | + | `scalar.db.password` | Either a master or read-only key used to perform authentication for accessing Azure Cosmos DB for NoSQL. | | + | `scalar.db.cosmos.table_metadata.database` | Database name for the table metadata used for ScalarDB. | `scalardb` | + | `scalar.db.cosmos.consistency_level` | Consistency level used for Cosmos DB operations. `STRONG` or `BOUNDED_STALENESS` can be specified. | `STRONG` | + + + The following configurations are available for Cassandra: + + | Name | Description | Default | + |-----------------------------------------|-----------------------------------------------------------------------|------------| + | `scalar.db.storage` | `cassandra` must be specified. | - | + | `scalar.db.contact_points` | Comma-separated contact points. | | + | `scalar.db.contact_port` | Port number for all the contact points. | | + | `scalar.db.username` | Username to access the database. | | + | `scalar.db.password` | Password to access the database. | | + + + +##### Multi-storage support + +ScalarDB supports using multiple storage implementations simultaneously. You can use multiple storages by specifying `multi-storage` as the value for the `scalar.db.storage` property. + +For details about using multiple storages, see [Multi-Storage Transactions](multi-storage-transactions.mdx). + +##### Cross-partition scan configurations + +By enabling the cross-partition scan option as described below, the `Scan` operation can retrieve all records across partitions. In addition, you can specify arbitrary conditions and orderings in the cross-partition `Scan` operation by enabling `cross_partition_scan.filtering` and `cross_partition_scan.ordering`, respectively. Currently, the cross-partition scan with ordering option is available only for JDBC databases. To enable filtering and ordering, `scalar.db.cross_partition_scan.enabled` must be set to `true`. + +For details on how to use cross-partition scan, see [Scan operation](./api-guide.mdx#scan-operation). + +:::warning + +For non-JDBC databases, transactions could be executed at read-committed snapshot isolation (`SNAPSHOT`), which is a lower isolation level, even if you enable cross-partition scan with the `SERIALIZABLE` isolation level. When using non-JDBC databases, use cross-partition scan only if consistency does not matter for your transactions. + +::: + +| Name | Description | Default | +|----------------------------------------------------|-----------------------------------------------|---------| +| `scalar.db.cross_partition_scan.enabled` | Enable cross-partition scan. | `true` | +| `scalar.db.cross_partition_scan.filtering.enabled` | Enable filtering in cross-partition scan. | `false` | +| `scalar.db.cross_partition_scan.ordering.enabled` | Enable ordering in cross-partition scan. | `false` | + +## Other ScalarDB configurations + +The following are additional configurations available for ScalarDB: + +| Name | Description | Default | +|------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| +| `scalar.db.metadata.cache_expiration_time_secs` | ScalarDB has a metadata cache to reduce the number of requests to the database. This setting specifies the expiration time of the cache in seconds. If you specify `-1`, the cache will never expire. | `60` | +| `scalar.db.active_transaction_management.expiration_time_millis` | ScalarDB maintains ongoing transactions, which can be resumed by using a transaction ID. This setting specifies the expiration time of this transaction management feature in milliseconds. | `-1` (no expiration) | +| `scalar.db.default_namespace_name` | The given namespace name will be used by operations that do not already specify a namespace. | | + +## Placeholder usage + +You can use placeholders in the values, and they are replaced with environment variables (`${env:}`) or system properties (`${sys:}`). You can also specify default values in placeholders like `${sys::-}`. + +The following is an example of a configuration that uses placeholders: + +```properties +scalar.db.username=${env:SCALAR_DB_USERNAME:-admin} +scalar.db.password=${env:SCALAR_DB_PASSWORD} +``` + +In this example configuration, ScalarDB reads the username and password from environment variables. If the environment variable `SCALAR_DB_USERNAME` does not exist, ScalarDB uses the default value `admin`. + +## Configuration example - App and database + +```mermaid +flowchart LR + app["App
(ScalarDB library with
Consensus Commit)"] + db[(Underlying storage or database)] + app --> db +``` + +In this example configuration, the app (ScalarDB library with Consensus Commit) connects to an underlying storage or database (in this case, Cassandra) directly. + +:::warning + +This configuration exists only for development purposes and isn't suitable for a production environment. This is because the app needs to implement the [Scalar Admin](https://github.com/scalar-labs/scalar-admin) interface to take transactionally consistent backups for ScalarDB, which requires additional configurations. + +::: + +The following is an example of the configuration for connecting the app to the underlying database through ScalarDB: + +```properties +# Transaction manager implementation. +scalar.db.transaction_manager=consensus-commit + +# Storage implementation. +scalar.db.storage=cassandra + +# Comma-separated contact points. +scalar.db.contact_points= + +# Credential information to access the database. +scalar.db.username= +scalar.db.password= +``` diff --git a/versioned_docs/version-3.15/consensus-commit.mdx b/versioned_docs/version-3.15/consensus-commit.mdx new file mode 100644 index 00000000..d61d31fb --- /dev/null +++ b/versioned_docs/version-3.15/consensus-commit.mdx @@ -0,0 +1,232 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Consensus Commit Protocol + +import JavadocLink from '/src/theme/JavadocLink.js'; + +Consensus Commit is the transaction protocol used in ScalarDB and is designed for executing transactions spanning multiple diverse databases. Its uniqueness is that the protocol achieves ACID transactions without relying on the transaction capabilities of the underlying databases, unlike X/Open XA-based solutions. This document explains the details of the protocol, including how it works, the guaranteed isolation levels, the interfaces, the performance optimization that it employs, and its limitations. + +## The protocol + +This section explains how the Consensus Commit protocol works. The Consensus Commit protocol uses a concurrency control protocol to guarantee isolation and an atomic commitment protocol to guarantee atomicity and durability. + +### Concurrency control protocol + +The Consensus Commit protocol employs optimistic concurrency control (OCC) as its concurrency control protocol. OCC operates under the assumption that conflicts are rare, allowing transactions to proceed without the need for locks and resolving conflicts only when they actually occur. Therefore, OCC performs great in low-contention environments. It is also particularly beneficial in distributed environments, where managing locks is tricky. + +:::note + +Pessimistic concurrency control (PCC), on the other hand, assumes conflicts are common and takes locks on resources when they are used to avoid interference. Therefore, PCC performs great in high-contention environments. + +::: + +The OCC protocol of ScalarDB has three phases, as the commonly used OCC protocols, each of which does the following: + +* Read phase: + * ScalarDB tracks the read and write sets of transactions. ScalarDB copies every record that a transaction accesses from databases to its local workspace and stores its writes in the local workspace. +* Validation phase: + * ScalarDB checks if the committing transaction conflicts with other transactions. ScalarDB uses backward validation; it goes to the write phase only if other transactions have not written what the transaction reads and writes, which are called read validation and write validation, respectively. +* Write phase: + * ScalarDB propagates the changes in the transaction's write set to the database and makes them visible to other transactions. + +As described next, ScalarDB provides an isolation mode (isolation level) where it skips the read validation in the validation phase to allow for more performance for some workloads that don't require the read validation for correctness. + +:::note + +The OCC of ScalarDB without the read validation works similarly to snapshot isolation. However, it works with a single version and causes read-skew anomalies because it does not create global snapshots. + +::: + +### Atomic commitment protocol + +The Consensus Commit protocol employs a variant of the two-phase commit protocol as an atomic commitment protocol (ACP). The ACP of ScalarDB comprises two phases, each of which has two sub-phases, and briefly works as follows: + +* Prepare phase (prepare-records phase \+ validate-records phase): + * In the prepare-records phase, ScalarDB runs the write validation of the OCC protocol for all the records written by the transaction by updating the statuses of the records to PREPARED and moves on to the next phase if all the records are successfully validated. + * In the validate-records phase, ScalarDB runs the read validation of the OCC protocol for all the records read by the transaction and moves on to the next phase if all the records are successfully validated. +* Commit phase (commit-state phase \+ commit-records phase): + * In the commit-state phase, ScalarDB commits the transaction by writing a COMMITTED state to a special table called a coordinator table. + * In the commit-records phase, ScalarDB runs the write phase of the OCC protocol for all the records written by the transaction by updating the statuses of the records to COMMITTED. + +:::note + +In case of deleting records, the statuses of the records are first changed to DELETED in the prepare phase and later physically deleted in the commit phase. + +::: + +#### How it works in more detail + +Let's see how the protocol works in each phase in more detail. + +##### Before the prepare phase + +First, a transaction begins when a client accesses ScalarDB (or a ScalarDB Cluster node) and issues a `begin` command. When a transaction begins, ScalarDB acts as a transaction coordinator, accessing the underlying databases, and first generates a transaction ID (TxID) with UUID version 4. Then, when the client is ready to commit the transaction after performing operations such as reading and writing records, it calls a `commit` command to request ScalarDB to commit the transaction and enters the prepare phase. As described previously, ScalarDB holds the read set (readSet) and write set (writeSet) of the transaction in its local workspace at the time of committing. + +##### Prepare phase + +ScalarDB first prepares the records of the write set by propagating the records, including transaction logs like TxID as described later, with PREPARED states to the underlying databases as the prepare-records phase. Here, we assume a write set maintains updated records composed of the original records and updated columns. If any preparation fails, it aborts the transaction by writing an ABORTED state record to a Coordinator table, where all the transactions’ final states are determined and managed. We explain the Coordinator table in more detail later in this section. + +:::note + +ScalarDB checks conflicting preparations by using linearizable conditional writes. A transaction updates a record if the record has not been updated by another transaction since the transaction read it by checking if the TxID of the record has not been changed. + +::: + +ScalarDB then moves on to the validate-records phase as necessary. The validate-records phase is only necessary if the isolation level is set to SERIALIZABLE. In this phase, ScalarDB re-reads all the records in the read set to see if other transactions have written the records that the transaction has read before. If the read set has not been changed, the transaction can go to the commit-state phase since there are no anti-dependencies; otherwise, it aborts the transaction. + +##### Commit phase +If all the validations in the prepare phase are done successfully, ScalarDB commits the transaction by writing a COMMITTED state record to the Coordinator table as the commit-state phase. + +:::note + +ScalarDB uses linearizable conditional writes to coordinate concurrent writes to the Coordinator table, creating a state record with a TxID if there is no record for the TxID. Once the COMMITTED state is correctly written to the Coordinator table, the transaction is regarded as committed. + +::: + +Then, ScalarDB commits all the validated (prepared) records by changing the states of the records to COMMITTED as the commit-records phase. + +#### Distributed WAL + +ScalarDB stores transaction logs, which are for write-ahead logging (WAL), in the underlying database records that it manages. Specifically, as shown in the following figure, ScalarDB manages special columns for the log information in a record in addition to the columns that an application manages. The log information comprises, for example, a transaction ID (TxID) that has updated the corresponding record most recently, a record version number (Version), a record state (TxState) (for example, COMMITTED or PREPARED), timestamps (not shown in the diagram), and a before image that comprises the previous version's application data and its metadata. + +ScalarDB also manages transaction states separately from the application records in the Coordinator table. The Coordinator table determines and manages transaction states as a single source of truth. The Coordinator table can be collocated with application-managed tables or located in a separate dedicated database. + +![Distributed WAL](images/scalardb-metadata.png) + +:::note + +The Coordinator table can be replicated for high availability by using the replication and consensus capabilities of the underlying databases. For example, if you manage the Coordinator table by using Cassandra with a replication factor of three, you can make the transaction coordination of ScalarDB tolerate one replica crash. Hence, you can make the atomic commitment protocol of ScalarDB perform like the Paxos Commit protocol; it could mitigate liveness issues (for example, blocking problems) without sacrificing safety. + +::: + +#### Lazy recovery + +Transactions can crash at any time and could leave records in an uncommitted state. ScalarDB recovers uncommitted records lazily when it reads them, depending on the transaction states of the Coordinator table. Specifically, if a record is in the PREPARED state, but the transaction that updated the record has expired or been aborted, the record will be rolled back. If a record is in the PREPARED state and the transaction that updated the record is committed, the record will be rolled forward. + +A transaction expires after a certain amount of time (currently 15 seconds). When ScalarDB observes a record that has been prepared by an expired transaction, ScalarDB writes the ABORTED state for the transaction to the Coordinator table (with retries). If ScalarDB successfully writes the ABORTED state to the Coordinator table, the transaction is aborted. Otherwise, the transaction will be committed by the original process that is slow but still alive for some reason, or it will remain in the UNKNOWN state until it is either aborted or committed. + +## Isolation levels + +The Consensus Commit protocol supports two isolation levels: a weaker variant of snapshot isolation, read-committed snapshot isolation, and serializable, each of which has the following characteristics: + +* Read-committed snapshot isolation (SNAPSHOT - default) + * Possible anomalies: read skew, write skew, read only + * Faster than serializable, but guarantees weaker correctness. +* Serializable (SERIALIZABLE) + * Possible anomalies: None + * Slower than read-committed snapshot isolation, but guarantees stronger (strongest) correctness. + +As described above, serializable is preferable from a correctness perspective, but slower than read-committed snapshot isolation. Choose the appropriate one based on your application requirements and workload. For details on how to configure read-committed snapshot isolation and serializable, see [ScalarDB Configuration](configurations.mdx#basic-configurations). + +:::note + +The Consensus Commit protocol of ScalarDB requires each underlying database to provide linearizable operations, as described in [Configurations for the Underlying Databases of ScalarDB](database-configurations.mdx#transactions); thus, it guarantees strict serializability. + +::: + +:::warning + +Scanning records without specifying a partition key (for example, or `SELECT * FROM table`) for non-JDBC databases does not always guarantee serializability, even if `SERIALIZABLE` is specified. Therefore, you should do so at your own discretion and consider updating the schemas if possible. For more details, refer to [Cross-partition scan configurations](configurations.mdx#cross-partition-scan-configurations). + +::: + +## Interfaces + +The Consensus Commit protocol provides two interfaces: [a one-phase commit interface and a two-phase commit interface](scalardb-cluster/run-transactions-through-scalardb-cluster.mdx#run-transactions). + +The one-phase commit interface is a simple interface that provides only a single `commit` method, where all the phases of the atomic commitment protocol are executed in the method. On the other hand, the two-phase commit interface exposes each phase of the protocol with `prepare`, `validate`, and `commit` methods. + +:::note + +The `prepare` method is for the prepare-records phase, and the `validate` method is for the validate-records phase. + +::: + +In most cases, using the one-phase commit interface is recommended since it is easier to use and handle errors. But the two-phase commit interface is useful when running a transaction across multiple applications or services without directly accessing databases from ScalarDB, such as maintaining the consistency of databases in microservices. + +## Performance optimization + +The Consensus Commit protocol employs several performance optimizations. + +### Parallel execution + +Consensus Commit executes each phase of the atomic commitment protocol in parallel, using intra-transaction parallelism without sacrificing correctness. Specifically, it tries to execute the prepare-records phase by writing records with PREPARED status in parallel. Likewise, it uses a similar parallel execution for the validate-records phase, the commit-records phase, and the rollback process. + +You can enable respective parallel execution by using the following parameters: + +* Prepare-records phase + * `scalar.db.consensus_commit.parallel_preparation.enabled` +* Validate-records phase + * `scalar.db.consensus_commit.parallel_validation.enabled` +* Commit-records phase + * `scalar.db.consensus_commit.parallel_commit.enabled` +* Rollback processing + * `scalar.db.consensus_commit.parallel_rollback.enabled` + +You can also configure the execution parallelism by using the following parameter: + +* `scalar.db.consensus_commit.parallel_executor_count` + +For details about the configuration, refer to [Performance-related configurations](configurations.mdx#performance-related-configurations). + +### Asynchronous execution + +Since a transaction is regarded as committed if the commit-state phase completes successfully, it can also return to the client without waiting for the completion of the commit-records phase, executing the phase asynchronously. Likewise, when a transaction fails for some reason and does a rollback, the rollback process can also be executed asynchronously without waiting for its completion. + +You can enable respective asynchronous execution by using the following parameters: + +* Commit-records phase + * `scalar.db.consensus_commit.async_commit.enabled` +* Rollback processing + * `scalar.db.consensus_commit.async_rollback.enabled` + +### Group commit + +Consensus Commit provides a group-commit feature to execute the commit-state phase of multiple transactions in a batch, reducing the number of writes for the commit-state phase. It is especially useful when writing to a Coordinator table is slow, for example, when the Coordinator table is deployed in a multi-region environment for high availability. + +You can enable group commit by using the following parameter: + +* `scalar.db.consensus_commit.coordinator.group_commit.enabled` + +Group commit has several other parameters. For more details, refer to [Performance-related configurations](configurations.mdx#performance-related-configurations). + +## Limitations + +ScalarDB has several limitations in achieving database-agnostic transactions. + +### Applications must access ScalarDB to access the underlying databases + +Since ScalarDB with the Consensus Commit protocol handles transactions in its layer without depending on the transactional capability of the underlying databases, your applications cannot bypass ScalarDB. Bypassing it will cause unexpected behavior, mostly resulting in facing some database anomalies. Even for read operations, accessing the underlying databases of ScalarDB directly will give you inconsistent data with the transaction metadata, so it is not allowed. + +However, for tables that are not managed or touched by ScalarDB transactions, you can read from and write to the tables. For example, it is OK to check tables' metadata information, such as information schema, by directly accessing the tables without going through ScalarDB. Also, there are several other cases where you can access databases directly without going through ScalarDB. The basic criterion is whether or not you update the data of the underlying databases. If you are sure that you do not write to the databases, you can access the databases directly. For example, it is OK to take a backup of databases by using database-native tools. + +:::note + +If you take backups from multiple databases or from non-transactional databases, you need to pause your applications or ScalarDB Cluster. For more details, refer to [How to Back Up and Restore Databases Used Through ScalarDB](backup-restore.mdx). + +::: + +### Executing particular operations in a certain sequence is prohibited for correctness + +In the current implementation, ScalarDB throws an exception in the following cases: + +* Executing scan operations after write (Put, Insert, Update, Upsert, Delete) operations for the same record in a transaction. +* Executing write (Put, Insert, Update, and Upsert) operations after Delete operations for the same record in a transaction. + +## See also + +You can learn more about the Consesnus Commit protocol by seeing the following presentation and YouTube video, which summarizes, visually, how the protocol works: + +- **Speaker Deck presentation:** [ScalarDB: Universal Transaction Manager](https://speakerdeck.com/scalar/scalar-db-universal-transaction-manager) +- **YouTube (Japanese):** [How ScalarDB runs transactions (a part of DBSJ lecture)](https://www.youtube.com/watch?v=s6Q7QQccDTc) + +In addition, more details about the protocol, including the background, the challenges, and the novelty, are discussed in the following research paper and its presentation: + +- **Research paper:** [ScalarDB: Universal Transaction Manager for Polystores](https://www.vldb.org/pvldb/vol16/p3768-yamada.pdf) +- **Speaker Deck presentation:** [ScalarDB: Universal Transaction Manager for Polystores](https://speakerdeck.com/scalar/scalardb-universal-transaction-manager-for-polystores-vldb23) diff --git a/versioned_docs/version-3.15/data-modeling.mdx b/versioned_docs/version-3.15/data-modeling.mdx new file mode 100644 index 00000000..3995a8bb --- /dev/null +++ b/versioned_docs/version-3.15/data-modeling.mdx @@ -0,0 +1,132 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Model Your Data + +Data modeling (or in other words, designing your database schemas) is the process of conceptualizing and visualizing how data will be stored and used by identifying the patterns used to access data and the types of queries to be performed within business operations. + +This page first explains the ScalarDB data model and then describes how to design your database schemas based on the data model. + +## ScalarDB data model + +ScalarDB's data model is an extended key-value model inspired by the Bigtable data model. It is similar to the relational model but differs in several ways, as described below. The data model is chosen to abstract various databases, such as relational databases, NoSQL databases, and NewSQL databases. + +The following diagram shows an example of ScalarDB tables, each of which is a collection of records. This section first explains what objects, such as tables and records, ScalarDB defines and then describes how to locate the records. + +![ScalarDB data model](images/scalardb_data_model.png) + +### Objects in ScalarDB + +The ScalarDB data model has several objects. + +#### Namespace + +A namespace is a collection of tables analogous to an SQL namespace or database. + +#### Table + +A table is a collection of partitions. A namespace most often contains one or more tables, each identified by a name. + +#### Partition + +A partition is a collection of records and a unit of distribution to nodes, whether logical or physical. Therefore, records within the same partition are placed in the same node. ScalarDB assumes multiple partitions are distributed by hashing. + +#### Record / row + +A record or row is a set of columns that is uniquely identifiable among all other records. + +#### Column + +A column is a fundamental data element and does not need to be broken down any further. Each record is composed of one or more columns. Each column has a data type. For details about the data type, refer to [Data-type mapping between ScalarDB and other databases](schema-loader.mdx#data-type-mapping-between-scalardb-and-other-databases). + +#### Secondary index + +A secondary index is a sorted copy of a column in a single base table. Each index entry is linked to a corresponding table partition. ScalarDB currently doesn't support multi-column indexes, so it can create indexes with only one column. + +### How to locate records + +This section discusses how to locate records from a table. + +#### Primary key + +A primary key uniquely identifies each record; no two records can have the same primary key. Therefore, you can locate a record by specifying a primary key. A primary key comprises a partition key and, optionally, a clustering key. + +#### Partition key + +A partition key uniquely identifies a partition. A partition key comprises a set of columns, which are called partition key columns. When you specify only a partition key, you can get a set of records that belong to the partition. + +#### Clustering key + +A clustering key uniquely identifies a record within a partition. It comprises a set of columns called clustering-key columns. When you want to specify a clustering key, you should specify a partition key for efficient lookups. When you specify a clustering key without a partition key, you end up scanning all the partitions. Scanning all the partitions is time consuming, especially when the amount of data is large, so only do so at your own discretion. + +Records within a partition are assumed to be sorted by clustering-key columns, specified as a clustering order. Therefore, you can specify a part of clustering-key columns in the defined order to narrow down the results to be returned. + +#### Index key + +An index key identifies records by looking up the key in indexes. An index key lookup spans all the partitions, so it is not necessarily efficient, especially if the selectivity of a lookup is not low. + +## How to design your database schemas + +You can design your database schemas similarly to the relational model, but there is a basic principle and are a few best practices to follow. + +### Query-driven data modeling + +In relational databases, data is organized in normalized tables with foreign keys used to reference related data in other tables. The queries that the application will make are structured by the tables, and the related data is queried as table joins. + +Although ScalarDB supports join operations in ScalarDB SQL, data modeling should be more query-driven, like NoSQL databases. The data access patterns and application queries should determine the structure and organization of tables. + +### Best practices + +This section describes best practices for designing your database schemas. + +#### Consider data distribution + +Preferably, you should try to balance loads to partitions by properly selecting partition and clustering keys. + +For example, in a banking application, if you choose an account ID as a partition key, you can perform any account operations for a specific account within the partition to which the account belongs. So, if you operate on different account IDs, you will access different partitions. + +On the other hand, if you choose a branch ID as a partition key and an account ID as a clustering key, all the accesses to a branch's account IDs go to the same partition, causing an imbalance in loads and data sizes. In addition, you should choose a high-cardinality column as a partition key because creating a small number of large partitions also causes an imbalance in loads and data sizes. + +#### Try to read a single partition + +Because of the data model characteristics, single partition lookup is most efficient. If you need to issue a scan or select a request that requires multi-partition lookups or scans, which you can [enable with cross-partition scan](configurations.mdx#cross-partition-scan-configurations), do so at your own discretion and consider updating the schemas if possible. + +For example, in a banking application, if you choose email as a partition key and an account ID as a clustering key, and issue a query that specifies an account ID, the query will span all the partitions because it cannot identify the corresponding partition efficiently. In such a case, you should always look up the table with an account ID. + +:::note + +If you read multiple partitions on a relational database with proper indexes, your query might be efficient because the query is pushed down to the database. + +::: + +#### Try to avoid using secondary indexes + +Similarly to the above, if you need to issue a scan or select a request that uses a secondary index, the request will span all the partitions of a table. Therefore, you should try to avoid using secondary indexes. If you need to use a secondary index, use it through a low-selectivity query, which looks up a small portion. + +As an alternative to secondary indexes, you can create another table that works as a clustered index of a base table. + +For example, assume there is a table with three columns: `table1(A, B, C)`, with the primary key `A`. Then, you can create a table like `index-table1(C, A, B)` with `C` as the primary key so that you can look up a single partition by specifying a value for `C`. This approach could speed up read queries but might create more load to write queries because you need to write to two tables by using ScalarDB transactions. + +:::note + +There are plans to have a table-based secondary-index feature in ScalarDB in the future. + +::: + +#### Consider data is assumed to be distributed by hashing + +In the current ScalarDB data model, data is assumed to be distributed by hashing. Therefore, you can't perform range queries efficiently without a partition key. + +If you want to issue range queries efficiently, you need to do so within a partition. However, if you follow this approach, you must specify a partition key. This can pose scalability issues as the range queries always go to the same partition, potentially overloading it. This limitation is not specific to ScalarDB but to databases where data is distributed by hashing for scalability. + +:::note + +If you run ScalarDB on a relational database with proper indexes, your range query might be efficient because the query is pushed down to the database. + +::: + diff --git a/versioned_docs/version-3.15/database-configurations.mdx b/versioned_docs/version-3.15/database-configurations.mdx new file mode 100644 index 00000000..e2b599f2 --- /dev/null +++ b/versioned_docs/version-3.15/database-configurations.mdx @@ -0,0 +1,120 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Configurations for the Underlying Databases of ScalarDB + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This document explains how to configure the underlying databases of ScalarDB to make applications that use ScalarDB work correctly and efficiently. + +## General requirements for the underlying databases + +ScalarDB requires each underlying database to provide certain capabilities to run transactions and analytics on the databases. This document explains the general requirements and how to configure each database to achieve the requirements. + +### Transactions + +ScalarDB requires each underlying database to provide at least the following capabilities to run transactions on the databases: + +- Linearizable read and conditional mutations (write and delete) on a single database record. +- Durability of written database records. +- Ability to store arbitrary data beside application data in each database record. + +### Analytics + +ScalarDB requires each underlying database to provide the following capability to run analytics on the databases: + +- Ability to return only committed records. + +:::note + +You need to have database accounts that have enough privileges to access the databases through ScalarDB since ScalarDB runs on the underlying databases not only for CRUD operations but also for performing operations like creating or altering schemas, tables, or indexes. ScalarDB basically requires a fully privileged account to access the underlying databases. + +::: + +## How to configure databases to achieve the general requirements + +Select your database for details on how to configure it to achieve the general requirements. + + + +

Transactions

+ + - Use a single primary server or synchronized multi-primary servers for all operations (no read operations on read replicas that are asynchronously replicated from a primary database). + - Use read-committed or stricter isolation levels. + +

Analytics

+ + - Use read-committed or stricter isolation levels. +
+ +

Transactions

+ + - Use a single primary region for all operations. (No read and write operations on global tables in non-primary regions.) + - There is no concept for primary regions in DynamoDB, so you must designate a primary region by yourself. + +

Analytics

+ + - Not applicable. DynamoDB always returns committed records, so there are no DynamoDB-specific requirements. +
+ +

Transactions

+ + - Use a single primary region for all operations with `Strong` or `Bounded Staleness` consistency. + +

Analytics

+ + - Not applicable. Cosmos DB always returns committed records, so there are no Cosmos DB–specific requirements. +
+ +

Transactions

+ + - Use a single primary cluster for all operations (no read or write operations in non-primary clusters). + - Use `batch` or `group` for `commitlog_sync`. + - If you're using Cassandra-compatible databases, those databases must properly support lightweight transactions (LWT). + +

Analytics

+ + - Not applicable. Cassandra always returns committed records, so there are no Cassandra-specific requirements. +
+
+ +## Recommendations + +Properly configuring each underlying database of ScalarDB for high performance and high availability is recommended. The following recommendations include some knobs and configurations to update. + +:::note + +ScalarDB can be seen as an application of underlying databases, so you may want to try updating other knobs and configurations that are commonly used to improve efficiency. + +::: + + + + - Use read-committed isolation for better performance. + - Follow the performance optimization best practices for each database. For example, increasing the buffer size (for example, `shared_buffers` in PostgreSQL) and increasing the number of connections (for example, `max_connections` in PostgreSQL) are usually recommended for better performance. + + + - Increase the number of read capacity units (RCUs) and write capacity units (WCUs) for high throughput. + - Enable point-in-time recovery (PITR). + +:::note + +Since DynamoDB stores data in multiple availability zones by default, you don’t need to adjust any configurations to improve availability. + +::: + + + - Increase the number of Request Units (RUs) for high throughput. + - Enable point-in-time restore (PITR). + - Enable availability zones. + + + - Increase `concurrent_reads` and `concurrent_writes` for high throughput. For details, see the official Cassandra documentation about [`concurrent_writes`](https://cassandra.apache.org/doc/stable/cassandra/configuration/cass_yaml_file.html#concurrent_writes). + + diff --git a/versioned_docs/version-3.15/deploy-overview.mdx b/versioned_docs/version-3.15/deploy-overview.mdx new file mode 100644 index 00000000..d72a68d1 --- /dev/null +++ b/versioned_docs/version-3.15/deploy-overview.mdx @@ -0,0 +1,23 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Deploy Overview + +In this category, you can follow guides to help you become more familiar with deploying ScalarDB, specifically ScalarDB Cluster and ScalarDB Analytics, in local and cloud-based Kubernetes environments. + +## Deploy ScalarDB Cluster in a local Kubernetes environment + +To learn how to deploy ScalarDB Cluster in a local Kubernetes environment by using a Helm Chart and a PostgreSQL database, see [Deploy ScalarDB Cluster Locally](scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +## Deploy ScalarDB Cluster in a cloud-based Kubernetes environment + +To learn how to deploy ScalarDB Cluster in a cloud-based Kubernetes environment by using a Helm Chart, see [Deploy ScalarDB Cluster on Amazon Elastic Kubernetes Service (EKS)](scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS.mdx). + +## Deploy ScalarDB Analytics in a public cloud-based environment + +To learn how to deploy ScalarDB Analytics in a public cloud-based environment, see [Deploy ScalarDB Analytics in Public Cloud Environments](scalardb-analytics/deployment.mdx). diff --git a/versioned_docs/version-3.15/design.mdx b/versioned_docs/version-3.15/design.mdx new file mode 100644 index 00000000..34b85e49 --- /dev/null +++ b/versioned_docs/version-3.15/design.mdx @@ -0,0 +1,80 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Design + +This document briefly explains the design and implementation of ScalarDB. For what ScalarDB is and its use cases, see [ScalarDB Overview](./overview.mdx). + +## Overall architecture + +ScalarDB is hybrid transaction/analytical processing (HTAP) middleware that sits in between applications and databases. As shown in the following figure, ScalarDB consists of three components: Core, Cluster, and Analytics. ScalarDB basically employs a layered architecture, so the Cluster and Analytics components use the Core component to interact with underlying databases but sometimes bypass the Core component for performance optimization without sacrificing correctness. Likewise, each component also consists of several layers. + +![ScalarDB architecture](images/scalardb-architecture.png) + +## Components + +The following subsections explain each component one by one. + +### Core + +ScalarDB Core, which is provided as open-source software under the Apache 2 License, is an integral part of ScalarDB. Core provides a database manager that has an abstraction layer that abstracts underlying databases and adapters (or shims) that implement the abstraction for each database. In addition, it provides a transaction manager on top of the database abstraction that achieves database-agnostic transaction management based on Scalar's novel distributed transaction protocol called [Consensus Commit](./consensus-commit.mdx). Core is provided as a library that offers a simple CRUD interface. + +### Cluster + +ScalarDB Cluster, which is licensed under a commercial license, is a component that provides a clustering solution for the Core component to work as a clustered server. Cluster is mainly designed for OLTP workloads, which have many small, transactional and non-transactional reads and writes. In addition, it provides several enterprise features such as authentication, authorization, encryption at rest, and fine-grained access control (attribute-based access control). Not only does Cluster offer the same CRUD interface as the Core component, but it also offers SQL and GraphQL interfaces. Furthermore, it offers a vector store interface to interact with several vector stores. Since Cluster is provided as a container in a Kubernetes Pod, you can increase performance and availability by having more containers. + +### Analytics + +ScalarDB Analytics, which is licensed under a commercial license, is a component that provides scalable analytical processing for the data managed by the Core component or managed by applications that don’t use ScalarDB. Analytics is mainly designed for OLAP workloads, which have a small number of large, analytical read queries. In addition, it offers a SQL and DataSet API through Spark. Since the Analytics component is provided as a Java package that can be installed on Apache Spark engines, you can increase performance by having more Spark worker nodes. + +## Metadata tables + +ScalarDB manages various types of metadata in the underlying databases to provide its capabilities. The following table summarizes the metadata managed by each component. + +| Component | Metadata tables | Purpose | Location | +| --------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | +| Core | `scalardb.metadata` | For database schema information | In all the databases under ScalarDB | +| Core | `coordinator.state` | For transaction statuses | In one designated database specified to store the Coordinator table | +| Core | Application-managed tables | For WAL information | In all the tables accessed by Consensus Commit | +| Cluster | `scalardb.users`, `scalardb.namespace_privileges`, `scalardb.table_privileges`, `scalardb.auth_tokens` | For [authentication and authorization](./scalardb-cluster/scalardb-auth-with-sql.mdx) | In one designated database specified to store the scalardb system namespace | +| Cluster | `scalardb.encrypted_columns` | For [encryption at rest](./scalardb-cluster/encrypt-data-at-rest.mdx) | In one designated database specified to store the scalardb system namespace | +| Cluster | `scalardb.abac_*` | For [attribute-based access control](./scalardb-cluster/authorize-with-abac.mdx) | In one designated database specified to store the scalardb system namespace | +| Analytics | All the tables managed by the catalog server | For [data catalog](./scalardb-analytics/design.mdx#universal-data-catalog) | In the catalog server database | + +:::note + +If you need to take backups of the databases accessed by ScalarDB, you will also need to take backups of the metadata managed by ScalarDB. For more details, see [How to Back Up and Restore Databases Used Through ScalarDB](./backup-restore.mdx). + +::: + +## Limitations + +ScalarDB operates between applications and databases, which leads to certain limitations. This section summarizes the limitations of ScalarDB. + +### Applications cannot bypass ScalarDB to run transactions and analytical queries + +ScalarDB Core offers a database-agnostic transaction capability that operates outside of databases. Therefore, applications must interact with ScalarDB to execute transactions; otherwise, ScalarDB cannot ensure transaction correctness, such as snapshot and serializable isolation. For more details, see [Consensus Commit](./consensus-commit.mdx). + +Likewise, ScalarDB Analytics offers a scalable analytical query processing capability that operates outside of databases. Therefore, applications must interact with ScalarDB Analytics to execute analytical queries; otherwise, ScalarDB cannot ensure correctness, such as read-committed isolation. For more details, see [ScalarDB Analytics Design](./scalardb-analytics/design.mdx). + +### Applications cannot use all the capabilities of the underlying databases + +ScalarDB serves as an abstraction layer over the underlying databases, which means that applications cannot use all the capabilities and data types of these databases. For instance, ScalarDB does not support database-specific features such as Oracle PL/SQL. + +ScalarDB has been enhanced to provide features that are commonly found in most supported databases. For a list of features, see [ScalarDB Features](./features.mdx). To learn about the features planned for future releases, see [Roadmap](./roadmap.mdx). + +## Further reading + +For more details about the design and implementation of ScalarDB, see the following documents: + +- **Speaker Deck presentation:** [ScalarDB: Universal Transaction Manager](https://speakerdeck.com/scalar/scalar-db-universal-transaction-manager) + +In addition, the following materials were presented at the VLDB 2023 conference: + +- **Speaker Deck presentation:** [ScalarDB: Universal Transaction Manager for Polystores](https://speakerdeck.com/scalar/scalardb-universal-transaction-manager-for-polystores-vldb23) +- **Detailed paper:** [ScalarDB: Universal Transaction Manager for Polystores](https://www.vldb.org/pvldb/vol16/p3768-yamada.pdf) diff --git a/versioned_docs/version-3.15/develop-overview.mdx b/versioned_docs/version-3.15/develop-overview.mdx new file mode 100644 index 00000000..652ca411 --- /dev/null +++ b/versioned_docs/version-3.15/develop-overview.mdx @@ -0,0 +1,35 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Develop Overview + +In this category, you can follow guides to help you become more familiar with ScalarDB, specifically with how to run transactions, analytical queries, and non-transactional storage operations. + +To get started with developing applications for ScalarDB, see the following sub-categories. + +## Run transactions + +In this sub-category, you can learn how to model your data based on the ScalarDB data model and create schemas. Then, you can learn how to run transactions through the ScalarDB Core library and ScalarDB Cluster, a gRPC server that wraps the Core library. + +For an overview of this sub-category, see [Run Transactions Overview](develop-run-transactions-overview.mdx). + +## Run non-transactional operations + +In this sub-category, you can learn how to run such non-transactional storage operations. + +For an overview of this sub-category, see [Run Non-Transactional Operations Overview](develop-run-non-transactional-operations-overview.mdx). + +## Run analytical queries + +To learn how to run analytical queries by using ScalarDB Analytics, see [Run Analytical Queries Through ScalarDB Analytics](scalardb-analytics/run-analytical-queries.mdx). + +## Run sample applications + +In this sub-category, you can learn how to run various sample applications that take advantage of ScalarDB. + +For an overview of this sub-category, see [Run Sample Applications Overview](scalardb-samples/README.mdx). diff --git a/versioned_docs/version-3.15/develop-run-non-transactional-operations-overview.mdx b/versioned_docs/version-3.15/develop-run-non-transactional-operations-overview.mdx new file mode 100644 index 00000000..a4c22448 --- /dev/null +++ b/versioned_docs/version-3.15/develop-run-non-transactional-operations-overview.mdx @@ -0,0 +1,21 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Non-Transactional Storage Operations Overview + +ScalarDB was initially designed to provide a unified abstraction between diverse databases and transactions across such databases. However, there are cases where you only need the unified abstraction to simplify your applications that use multiple, possibly diverse, databases. + +ScalarDB can be configured to provide only the unified abstraction, without transaction capabilities, so that it only runs non-transactional operations on the underlying database and storage. Since ScalarDB in this configuration doesn't guarantee ACID across multiple operations, you can perform operations with better performance. + +In this sub-category, you can learn how to run such non-transactional storage operations. + +- Run Through the CRUD Interface + - [Use the ScalarDB Core Library](run-non-transactional-storage-operations-through-library.mdx) + - [Use ScalarDB Cluster](scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx) +- [Run Through the SQL Interface](scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx) +- [Run Through the Primitive CRUD Interface](run-non-transactional-storage-operations-through-primitive-crud-interface.mdx) diff --git a/versioned_docs/version-3.15/develop-run-transactions-overview.mdx b/versioned_docs/version-3.15/develop-run-transactions-overview.mdx new file mode 100644 index 00000000..17cc7831 --- /dev/null +++ b/versioned_docs/version-3.15/develop-run-transactions-overview.mdx @@ -0,0 +1,17 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Transactions Overview + +In this sub-category, you can learn how to model your data based on the ScalarDB data model and create schemas. Then, you can learn how to run transactions through the ScalarDB Core library and ScalarDB Cluster, a gRPC server that wraps the Core library. + +- [Model Your Data](data-modeling.mdx) +- Run Through the CRUD Interface + - [Use the ScalarDB Core Library](run-transactions-through-scalardb-core-library.mdx) + - [Use ScalarDB Cluster](scalardb-cluster/run-transactions-through-scalardb-cluster.mdx) +- [Run Through the SQL Interface](scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx) diff --git a/versioned_docs/version-3.15/features.mdx b/versioned_docs/version-3.15/features.mdx new file mode 100644 index 00000000..0ba5766d --- /dev/null +++ b/versioned_docs/version-3.15/features.mdx @@ -0,0 +1,29 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Features + +This document briefly explains which features are available in which editions of ScalarDB. + +| | ScalarDB Core (Community) | ScalarDB Cluster (Enterprise Standard) | ScalarDB Cluster (Enterprise Premium) | ScalarDB Analytics (Enterprise) | +|-------------------------------------------------------------------------------------------------------------------------------------|---------------------------|----------------------------------------|------------------------------------------------------------|---------------------------------| +| [Transaction processing across databases with primitive interfaces](getting-started-with-scalardb.mdx) | ✅ | ✅ | ✅ | – | +| [Clustering](scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx) | - | ✅ | ✅ | – | +| [Non-transactional storage operations](develop-run-non-transactional-operations-overview.mdx) | – | ✅ (3.14+) | ✅ (3.14+) | – | +| [Authentication/authorization](scalardb-cluster/scalardb-auth-with-sql.mdx) | – | ✅ | ✅ | – | +| [Encryption](scalardb-cluster/encrypt-data-at-rest.mdx) | – | – | ✅ (3.14+) | – | +| [Attribute-based access control](scalardb-cluster/authorize-with-abac.mdx) | – | – | ✅ (3.15+) (Enterprise Premium Option*, Private Preview**) | – | +| [SQL interface (SQL API, JDBC, Spring Data JDBC, and LINQ)](scalardb-sql/index.mdx) | – | – | ✅ | – | +| [GraphQL interface](scalardb-graphql/index.mdx) | – | – | ✅ | – | +| [Vector search interface](scalardb-cluster/getting-started-with-vector-search.mdx) | – | – | ✅ (3.15+) (Private Preview**) | – | +| [Analytical query processing across ScalarDB-managed data sources](scalardb-samples/scalardb-analytics-spark-sample/README.mdx) | – | – | – | ✅ (3.14+) | +| [Analytical query processing across non-ScalarDB-managed data sources](scalardb-samples/scalardb-analytics-spark-sample/README.mdx) | – | – | – | ✅ (3.15+) | + +\* This feature is not available in the Enterprise Premium edition. If you want to use this feature, please [contact us](https://www.scalar-labs.com/contact). + +\*\* This feature is currently in Private Preview. For details, please [contact us](https://www.scalar-labs.com/contact) or wait for this feature to become publicly available in a future version. diff --git a/versioned_docs/version-3.15/getting-started-with-scalardb-by-using-kotlin.mdx b/versioned_docs/version-3.15/getting-started-with-scalardb-by-using-kotlin.mdx new file mode 100644 index 00000000..2284966c --- /dev/null +++ b/versioned_docs/version-3.15/getting-started-with-scalardb-by-using-kotlin.mdx @@ -0,0 +1,413 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB by Using Kotlin + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This getting started tutorial explains how to configure your preferred database in ScalarDB and set up a basic electronic money application by using Kotlin. Since Kotlin has Java interoperability, you can use ScalarDB directly from Kotlin. + +:::warning + +The electronic money application is simplified for this tutorial and isn't suitable for a production environment. + +::: + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](./requirements.mdx). + +::: + +## Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/scalardb-kotlin-sample +``` + +## Set up your database for ScalarDB + +Select your database, and follow the instructions to configure it for ScalarDB. + +For a list of databases that ScalarDB supports, see [Databases](requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-kotlin-sample` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-kotlin-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for MySQL in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://localhost:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-kotlin-sample` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-kotlin-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for PostgreSQL in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://localhost:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-kotlin-sample` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-kotlin-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Oracle Database in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//localhost:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-kotlin-sample` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-kotlin-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for SQL Server in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-kotlin-sample` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-kotlin-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Amazon DynamoDB Local in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://localhost:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **database.properties** file in the `scalardb-samples/scalardb-kotlin-sample` directory contains database configurations for ScalarDB. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-kotlin-sample` directory. + + To start Apache Cassandra, run the following command: + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-kotlin-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Cassandra in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +## Load the database schema + +You need to define the database schema (the method in which the data will be organized) in the application. For details about the supported data types, see [Data type mapping between ScalarDB and other databases](schema-loader.mdx#data-type-mapping-between-scalardb-and-other-databases). + +For this tutorial, a file named **schema.json** already exists in the `scalardb-samples/scalardb-kotlin-sample` directory. To apply the schema, go to the [`scalardb` Releases](https://github.com/scalar-labs/scalardb/releases) page and download the ScalarDB Schema Loader that matches the version of ScalarDB that you are using to the `scalardb-samples/scalardb-kotlin-sample` directory. + +Then, based on your database, run the following command, replacing `` with the version of the ScalarDB Schema Loader that you downloaded: + + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator --no-backup --no-scaling + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +Also, `--no-backup` and `--no-scaling` options are specified because Amazon DynamoDB Local does not support continuous backup and auto-scaling. + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator --replication-factor=1 + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +In addition, the `--replication-factor=1` option has an effect only when using Cassandra. The default replication factor is `3`, but to facilitate the setup in this tutorial, `1` is used so that you only need to prepare a cluster with one node instead of three nodes. However, keep in mind that a replication factor of `1` is not suited for production. + +::: + + + +## Execute transactions and retrieve data in the basic electronic money application + +After loading the schema, you can execute transactions and retrieve data in the basic electronic money application that is included in the repository that you cloned. + +The application supports the following types of transactions: + +- Create an account. +- Add funds to an account. +- Send funds between two accounts. +- Get an account balance. + +:::note + +When you first execute a Gradle command, Gradle will automatically install the necessary libraries. + +::: + +### Create an account with a balance + +You need an account with a balance so that you can send funds between accounts. + +To create an account for **customer1** that has a balance of **500**, run the following command: + +```console +./gradlew run --args="-action charge -amount 500 -to customer1" +``` + +### Create an account without a balance + +After setting up an account that has a balance, you need another account for sending funds to. + +To create an account for **merchant1** that has a balance of **0**, run the following command: + +```console +./gradlew run --args="-action charge -amount 0 -to merchant1" +``` + +### Add funds to an account + +You can add funds to an account in the same way that you created and added funds to an account in [Create an account with a balance](#create-an-account-with-a-balance). + +To add **500** to the account for **customer1**, run the following command: + +```console +./gradlew run --args="-action charge -amount 500 -to customer1" +``` + +The account for **customer1** will now have a balance of **1000**. + +### Send electronic money between two accounts + +Now that you have created two accounts, with at least one of those accounts having a balance, you can send funds from one account to the other account. + +To have **customer1** pay **100** to **merchant1**, run the following command: + +```console +./gradlew run --args="-action pay -amount 100 -from customer1 -to merchant1" +``` + +### Get an account balance + +After sending funds from one account to the other, you can check the balance of each account. + +To get the balance of **customer1**, run the following command: + +```console +./gradlew run --args="-action getBalance -id customer1" +``` + +You should see the following output: + +```console +... +The balance for customer1 is 900 +... +``` + +To get the balance of **merchant1**, run the following command: + +```console +./gradlew run --args="-action getBalance -id merchant1" +``` + +You should see the following output: + +```console +... +The balance for merchant1 is 100 +... +``` + +## Stop the database + +To stop the database, stop the Docker container by running the following command: + +```console +docker compose down +``` + +## Reference + +To see the source code for the electronic money application used in this tutorial, see [`ElectronicMoney.kt`](https://github.com/scalar-labs/scalardb-samples/blob/main/scalardb-kotlin-sample/src/main/kotlin/sample/ElectronicMoney.kt). diff --git a/versioned_docs/version-3.15/getting-started-with-scalardb.mdx b/versioned_docs/version-3.15/getting-started-with-scalardb.mdx new file mode 100644 index 00000000..2e21cefc --- /dev/null +++ b/versioned_docs/version-3.15/getting-started-with-scalardb.mdx @@ -0,0 +1,533 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This getting started tutorial explains how to configure your preferred database in ScalarDB and illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a credit card by using ScalarDB. The sample e-commerce application shows how users can order and pay for items by using a line of credit. + +:::warning + +Since the focus of the sample application is to demonstrate using ScalarDB, application-specific error handling, authentication processing, and similar functions are not included in the sample application. For details about exception handling in ScalarDB, see [How to handle exceptions](api-guide.mdx#how-to-handle-exceptions). + +::: + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](./requirements.mdx). + +::: + +## Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/scalardb-sample +``` + +## Set up your database for ScalarDB + +Select your database, and follow the instructions to configure it for ScalarDB. + +For a list of databases that ScalarDB supports, see [Databases](requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for MySQL in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://localhost:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for PostgreSQL in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://localhost:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Oracle Database in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//localhost:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for SQL Server in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Amazon DynamoDB Local in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://localhost:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Apache Cassandra, run the following command: + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Cassandra in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +## Load the database schema + +You need to define the database schema (the method in which the data will be organized) in the application. For details about the supported data types, see [Data type mapping between ScalarDB and other databases](schema-loader.mdx#data-type-mapping-between-scalardb-and-other-databases). + +For this tutorial, a file named **schema.json** already exists in the `scalardb-samples/scalardb-sample` directory. To apply the schema, go to the [`scalardb` Releases](https://github.com/scalar-labs/scalardb/releases) page and download the ScalarDB Schema Loader that matches the version of ScalarDB that you are using to the `scalardb-samples/scalardb-sample` directory. + +Then, run the following command, replacing `` with the version of the ScalarDB Schema Loader that you downloaded: + + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator --no-backup --no-scaling + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +Also, `--no-backup` and `--no-scaling` options are specified because Amazon DynamoDB Local does not support continuous backup and auto-scaling. + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +::: + + + ```console + java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator --replication-factor=1 + ``` + +:::note + +The `--coordinator` option is specified because a table with `transaction` set to `true` exists in the schema. For details about configuring and loading a schema, see [ScalarDB Schema Loader](schema-loader.mdx). + +In addition, the `--replication-factor=1` option has an effect only when using Cassandra. The default replication factor is `3`, but to facilitate the setup in this tutorial, `1` is used so that you only need to prepare a cluster with one node instead of three nodes. However, keep in mind that a replication factor of `1` is not suited for production. + +::: + + + +### Schema details + +As shown in [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sample/schema.json) for the sample application, all the tables are created in the `sample` namespace. + +- `sample.customers`: a table that manages customer information + - `credit_limit`: the maximum amount of money that the lender will allow the customer to spend from their line of credit + - `credit_total`: the amount of money that the customer has spent from their line of credit +- `sample.orders`: a table that manages order information +- `sample.statements`: a table that manages order statement information +- `sample.items`: a table that manages information for items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/getting-started-ERD.png) + +### Load the initial data + +Before running the sample application, you need to load the initial data by running the following command: + +```console +./gradlew run --args="LoadInitialData" +``` + +After the initial data has loaded, the following records should be stored in the tables. + +**`sample.customers` table** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` table** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Execute transactions and retrieve data in the sample application + +The following sections describe how to execute transactions and retrieve data in the sample e-commerce application. + +### Get customer information + +Start with getting information about the customer whose ID is `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 0} +... +``` + +### Place an order + +Then, have customer ID `1` place an order for three apples and two oranges by running the following command: + +:::note + +The order format in this command is `./gradlew run --args="PlaceOrder :,:,..."`. + +::: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e"} +... +``` + +### Check order details + +Check details about the order by running the following command, replacing `` with the UUID for the `order_id` that was shown after running the previous command: + +```console +./gradlew run --args="GetOrder " +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`: + +```console +... +{"order": {"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +### Place another order + +Place an order for one melon that uses the remaining amount in `credit_total` for customer ID `1` by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 5:1" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d"} +... +``` + +### Check order history + +Get the history of all orders for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetOrders 1" +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`, which shows the history of all orders for customer ID `1` in descending order by timestamp: + +```console +... +{"order": [{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000},{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d","timestamp": 1650948412766,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000}]} +... +``` + +### Check credit total + +Get the credit total for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output, which shows that customer ID `1` has reached their `credit_limit` in `credit_total` and cannot place anymore orders: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +``` + +Try to place an order for one grape and one mango by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +You should see the following output, which shows that the order failed because the `credit_total` amount would exceed the `credit_limit` amount. + +```console +... +java.lang.RuntimeException: Credit limit exceeded + at sample.Sample.placeOrder(Sample.java:205) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:33) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:8) + at picocli.CommandLine.executeUserObject(CommandLine.java:1783) + at picocli.CommandLine.access$900(CommandLine.java:145) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2141) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2108) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:1975) + at picocli.CommandLine.execute(CommandLine.java:1904) + at sample.command.SampleCommand.main(SampleCommand.java:35) +... +``` + +### Make a payment + +To continue making orders, customer ID `1` must make a payment to reduce the `credit_total` amount. + +Make a payment by running the following command: + +```console +./gradlew run --args="Repayment 1 8000" +``` + +Then, check the `credit_total` amount for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output, which shows that a payment was applied to customer ID `1`, reducing the `credit_total` amount: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 2000} +... +``` + +Now that customer ID `1` has made a payment, place an order for one grape and one melon by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "8911cab3-1c2b-4322-9386-adb1c024e078"} +... +``` + +## Stop the database + +To stop the database, stop the Docker container by running the following command: + +```console +docker compose down +``` + +## Reference + +To see the source code for the e-commerce application used in this tutorial, see [`Sample.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/scalardb-sample/src/main/java/sample/Sample.java). diff --git a/versioned_docs/version-3.15/glossary.mdx b/versioned_docs/version-3.15/glossary.mdx new file mode 100644 index 00000000..6cd569d6 --- /dev/null +++ b/versioned_docs/version-3.15/glossary.mdx @@ -0,0 +1,119 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Glossary + +This glossary includes database and distributed-system terms that are often used when using ScalarDB. + +## ACID + +Atomicity, consistency, isolation, and durability (ACID) is a set of properties that ensure database transactions are processed reliably, maintaining integrity even in cases of errors or system failures. + +## concurrency control + +Concurrency control in databases ensures that multiple transactions can occur simultaneously without causing data inconsistency, usually through mechanisms like locking or timestamp ordering. + +## consensus + +Consensus in distributed systems refers to the process of achieving agreement among multiple computers or nodes on a single data value or system state. + +## data federation + +Data federation is the process of integrating data from different sources without moving the data, creating a unified view for querying and analysis. + +## data mesh + +A data mesh is a decentralized data architecture that enables each business domain within a company to autonomously manage data and use it efficiently. + +## data virtualization + +Data virtualization is similar to data federation in many aspects, meaning that it virtualizes multiple data sources into a unified view, simplifying queries without moving the data. + +## database anomalies + +Database anomalies are inconsistencies or errors in data that can occur when operations such as insertions, updates, or deletions are performed without proper transaction management. + +## federation engine + +A federation engine facilitates data integration and querying across multiple disparate data sources, often as part of a data federation architecture. + +## global transaction + +A global transaction spans multiple databases or distributed systems and ensures that all involved systems commit or roll back changes as a single unit. + +## heterogeneous databases + +Heterogeneous databases refer to systems composed of different database technologies that may have distinct data models, query languages, and transaction mechanisms. + +## HTAP + +Hybrid transactional/analytical processing (HTAP) refers to a system that can handle both transactional and analytical workloads concurrently on the same data set, removing the need for separate databases. + +## JDBC + +Java Database Connectivity (JDBC) is an API that allows Java applications to interact with databases, providing methods for querying and updating data in relational databases. + +## linearizability + +Linearizability is a strong consistency model in distributed systems where operations appear to occur atomically in some order, and each operation takes effect between its start and end. + +## NoSQL database + +A NoSQL database is a non-relational databases designed for specific data models, such as document, key-value, wide-column, or graph stores, often used for handling large-scale, distributed data. + +## Paxos + +Paxos is a family of protocols used in distributed systems to achieve consensus, even in the presence of node failures. + +## PITR + +Point-in-time recovery (PITR) allows a database to be restored to a previous state at any specific time, usually after an unintended event like data corruption. + +## polystores + +Polystores are database architectures that allow users to interact with multiple, heterogeneous data stores, each optimized for a specific workload or data type, as if they were a single system. + +## read-committed isolation + +Read-committed isolation is an isolation level where each transaction sees only committed data, preventing dirty reads but allowing non-repeatable reads. + +## relational database + +A relational database stores data in tables with rows and columns, using a structured query language (SQL) to define, query, and manipulate the data. + +## replication + +Replication in databases involves copying and distributing data across multiple machines or locations to ensure reliability, availability, and fault tolerance. + +## Saga + +The Saga pattern is a method for managing long-running transactions in a distributed system, where each operation in the transaction is followed by a compensating action in case of failure. + +## serializable isolation + +Serializable isolation (serializability) is the highest isolation level in transactional systems, ensuring that the outcome of concurrently executed transactions is the same as if they were executed sequentially. + +## snapshot isolation + +Snapshot isolation is an isolation level that allows transactions to read a consistent snapshot of the database, protecting them from seeing changes made by other transactions until they complete. + +## TCC + +Try-Confirm/Cancel (TCC) is a pattern for distributed transactions that splits an operation into three steps, allowing for coordination and recovery across multiple systems. + +## transaction + +A transaction in databases is a sequence of operations treated as a single logical unit of work, ensuring consistency and integrity, typically conforming to ACID properties. + +## transaction manager + +A transaction manager coordinates the execution of transactions across multiple systems or databases, ensuring that all steps of the transaction succeed or fail as a unit. + +## two-phase commit + +Two-phase commit is a protocol for ensuring all participants in a distributed transaction either commit or roll back the transaction, ensuring consistency across systems. diff --git a/versioned_docs/version-3.15/helm-charts/conf/scalar-loki-stack-custom-values.yaml b/versioned_docs/version-3.15/helm-charts/conf/scalar-loki-stack-custom-values.yaml new file mode 100644 index 00000000..997537a5 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/conf/scalar-loki-stack-custom-values.yaml @@ -0,0 +1,80 @@ +promtail: + config: + snippets: + # -- `scapeConfigs` is exactly the part of https://grafana.com/docs/loki/latest/clients/promtail/configuration/#scrape_configs + # -- The value will be created as a Kubernetes ConfigMap and then mounted to the Promtail Pod. + # -- Not really need to change this value. It's set to scrape all logs of ScalarDL/DB Pods by using regular expression. + scrapeConfigs: | + # -- the `scalardl` job scrapes all the logs from Scalar Ledger Pods, Scalar Auditor Pods, and the corresponding Envoy Pods + - job_name: scalardl + pipeline_stages: + - docker: {} + kubernetes_sd_configs: + - role: pod + relabel_configs: + - source_labels: + - __meta_kubernetes_pod_node_name + target_label: __host__ + - action: replace + source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - action: keep + regex: (.*)scalardl-(.+) + source_labels: + - pod + - replacement: /var/log/pods/*$1/*.log + separator: / + source_labels: + - __meta_kubernetes_pod_uid + - __meta_kubernetes_pod_container_name + target_label: __path__ + # -- the `scalardb` job scrapes all the logs of ScalarDB Server Pods and the corresponding Envoy Pods + - job_name: scalardb + pipeline_stages: + - docker: {} + kubernetes_sd_configs: + - role: pod + relabel_configs: + - source_labels: + - __meta_kubernetes_pod_node_name + target_label: __host__ + - action: replace + source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - action: keep + regex: (.*)scalardb-(.+) + source_labels: + - pod + - replacement: /var/log/pods/*$1/*.log + separator: / + source_labels: + - __meta_kubernetes_pod_uid + - __meta_kubernetes_pod_container_name + target_label: __path__ + # -- the `scalar-admin-for-kubernetes` job scrapes all the logs of Scalar Admin for Kubernetes Pods + - job_name: scalar-admin-for-kubernetes + pipeline_stages: + - docker: {} + - cri: {} + kubernetes_sd_configs: + - role: pod + relabel_configs: + - source_labels: + - __meta_kubernetes_pod_node_name + target_label: __host__ + - action: replace + source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - action: keep + regex: (.*)scalar-admin-for-kubernetes-(.+) + source_labels: + - pod + - replacement: /var/log/pods/*$1/*.log + separator: / + source_labels: + - __meta_kubernetes_pod_uid + - __meta_kubernetes_pod_container_name + target_label: __path__ diff --git a/versioned_docs/version-3.15/helm-charts/conf/scalar-prometheus-custom-values.yaml b/versioned_docs/version-3.15/helm-charts/conf/scalar-prometheus-custom-values.yaml new file mode 100644 index 00000000..816ead1b --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/conf/scalar-prometheus-custom-values.yaml @@ -0,0 +1,167 @@ +defaultRules: + # -- Default PrometheusRules are not enabled + create: false + +alertmanager: + # -- alertmanager is enabled + enabled: true + + # -- Only check own namespace + alertmanagerConfigNamespaceSelector: null + +grafana: + # -- grafana is enabled + enabled: true + + # -- Default Grafana dashboards are not enabled + defaultDashboardsEnabled: false + + sidecar: + datasources: + enabled: true + defaultDatasourceEnabled: false + label: grafana_datasource + labelValue: "1" + dashboards: + enabled: true + label: grafana_dashboard + labelValue: "1" + # -- Resource limits & requests + resources: {} + # requests: + # memory: 400Mi + + # -- Grafana's primary configuration + grafana.ini: + security: + # -- allow Grafana to be embedded (not set the X-Frame-Options header) + # -- If you use Scalar Manager, you need to set allow_embedding to true. + # -- https://grafana.com/docs/grafana/latest/administration/configuration/#allow_embedding + allow_embedding: false + + # -- Additional data source configurations + additionalDataSources: + - name: Prometheus + type: prometheus + uid: prometheus + url: http://scalar-monitoring-kube-pro-prometheus:9090/ + access: proxy + editable: false + isDefault: false + jsonData: + timeInterval: 30s + # - name: Loki + # type: loki + # uid: loki + # url: http://scalar-logging-loki:3100/ + # access: proxy + # editable: false + # isDefault: false + +kubeApiServer: + # -- Scraping kube-apiserver is disabled + enabled: false + +kubeControllerManager: + # -- Scraping kube-controller-manager is disabled + enabled: false + +coreDns: + # -- Scraping CoreDNS is disabled + enabled: false + +kubeEtcd: + # -- Scraping etcd is disabled + enabled: false + +kubeScheduler: + # -- Scraping kube-scheduler is disabled + enabled: false + +kubeProxy: + # -- Scraping kube-proxy is disabled + enabled: false + +kubelet: + # -- Scraping kubelet is disabled + enabled: false + +kubeStateMetrics: + # -- kube-state-metrics is disabled + enabled: false + +nodeExporter: + # -- node-exporter is disabled + enabled: false + +prometheusOperator: + # -- Prometheus Operator is enabled + enabled: true + + admissionWebhooks: + patch: + # -- Resource limits & requests + resources: {} + # requests: + # memory: 400Mi + + namespaces: + # -- Only check own namespace + releaseNamespace: true + + kubeletService: + # -- kubelet service for scraping kubelets is disabled + enabled: false + + ## -- Resource limits & requests + resources: {} + # requests: + # memory: 400Mi + +prometheus: + # -- Prometheus is enabled + enabled: true + + prometheusSpec: + # -- All PrometheusRules are enabled + ruleSelectorNilUsesHelmValues: false + + # -- Only check own namespace + ruleNamespaceSelector: {} + + # -- All ServiceMonitors are enabled + serviceMonitorSelectorNilUsesHelmValues: false + + # -- Only check own namespace + serviceMonitorNamespaceSelector: {} + + # -- All PodMonitors are enabled + podMonitorSelectorNilUsesHelmValues: false + + # -- Only check own namespace + podMonitorNamespaceSelector: {} + + # -- All Probes are enabled + probeSelectorNilUsesHelmValues: false + + # -- Only check own namespace + probeNamespaceSelector: {} + + ## -- Resource limits & requests + resources: {} + # requests: + # memory: 400Mi + + ## -- Prometheus StorageSpec for persistent data + ## ref: https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/user-guides/storage.md + storageSpec: {} + ## Using PersistentVolumeClaim + ## + # volumeClaimTemplate: + # spec: + # storageClassName: gluster + # accessModes: ["ReadWriteOnce"] + # resources: + # requests: + # storage: 50Gi + # selector: {} diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-envoy.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-envoy.mdx new file mode 100644 index 00000000..57f7b0cd --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-envoy.mdx @@ -0,0 +1,392 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Configure a custom values file for Scalar Envoy + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This document explains how to create your custom values file for the Scalar Envoy chart. If you want to know the details of the parameters, please refer to the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/envoy/README.md) of the Scalar Envoy chart. + +## Configure custom values for Scalar Envoy chart + +The Scalar Envoy chart is used via other charts (scalardb, scalardb-cluster, scalardl, and scalardl-audit), so you don't need to create a custom values file for the Scalar Envoy chart. If you want to configure Scalar Envoy, you need to add the `envoy.*` configuration to the other charts. + +For example, if you want to configure the Scalar Envoy for ScalarDB Server, you can configure some Scalar Envoy configurations in the custom values file of ScalarDB as follows. + +* Example (scalardb-custom-values.yaml) + ```yaml + envoy: + configurationsForScalarEnvoy: + ... + + scalardb: + configurationsForScalarDB: + ... + ``` + +## Required configurations + +### Service configurations + +You must set `envoy.service.type` to specify the Service resource type of Kubernetes. + +If you accept client requests from inside of the Kubernetes cluster only (for example, if you deploy your client applications on the same Kubernetes cluster as Scalar products), you can set `envoy.service.type` to `ClusterIP`. This configuration doesn't create any load balancers provided by cloud service providers. + +```yaml +envoy: + service: + type: ClusterIP +``` + +If you want to use a load balancer provided by a cloud service provider to accept client requests from outside of the Kubernetes cluster, you need to set `envoy.service.type` to `LoadBalancer`. + +```yaml +envoy: + service: + type: LoadBalancer +``` + +If you want to configure the load balancer via annotations, you can also set annotations to `envoy.service.annotations`. + +```yaml +envoy: + service: + type: LoadBalancer + annotations: + service.beta.kubernetes.io/aws-load-balancer-internal: "true" + service.beta.kubernetes.io/aws-load-balancer-type: "nlb" +``` + +## Optional configurations + +### Resource configurations (Recommended in the production environment) + +If you want to control pod resources using the requests and limits of Kubernetes, you can use `envoy.resources`. + +You can configure them using the same syntax as the requests and limits of Kubernetes. So, please refer to the official document [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) for more details on the requests and limits of Kubernetes. + +```yaml +envoy: + resources: + requests: + cpu: 1000m + memory: 2Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### Affinity configurations (Recommended in the production environment) + +If you want to control pod deployment using the affinity and anti-affinity of Kubernetes, you can use `envoy.affinity`. + +You can configure them using the same syntax as the affinity of Kubernetes. So, please refer to the official document [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) for more details on the affinity configuration of Kubernetes. + +```yaml +envoy: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardb-cluster + - key: app.kubernetes.io/app + operator: In + values: + - envoy + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus and Grafana configurations (Recommended in production environments) + +If you want to monitor Scalar Envoy pods using [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack), you can deploy a ConfigMap, a ServiceMonitor, and a PrometheusRule resource for kube-prometheus-stack using `envoy.grafanaDashboard.enabled`, `envoy.serviceMonitor.enabled`, and `envoy.prometheusRule.enabled`. + +```yaml +envoy: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext configurations (Default value is recommended) + +If you want to set SecurityContext and PodSecurityContext for Scalar Envoy pods, you can use `envoy.securityContext` and `envoy.podSecurityContext`. + +You can configure them using the same syntax as SecurityContext and PodSecurityContext of Kubernetes. So, please refer to the official document [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for more details on the SecurityContext and PodSecurityContext configurations of Kubernetes. + +```yaml +envoy: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### Image configurations (Default value is recommended) + +If you want to change the image repository and version, you can use `envoy.image.repository` to specify the container repository information of the Scalar Envoy container image that you want to pull. + +```yaml +envoy: + image: + repository: +``` + +If you're using AWS or Azure, please refer to the following documents for more details: + +* [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) +* [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +### TLS configurations (optional based on your environment) + +You can enable TLS in: + +- Downstream connections between the client and Scalar Envoy. +- Upstream connections between Scalar Envoy and Scalar products. + +In addition, you have several options from the following two perspectives: + +1. Management of private key and certificate files + 1. Manage your private key and certificate files automatically by using [cert-manager](https://cert-manager.io/docs/). + - You can reduce maintenance or operation costs. For example, cert-manager automatically renews certificates before they expire and Scalar Helm Chart automatically mounts private key and certificate files on the Scalar product pods. + - You cannot use a CA that cert-manager does not support. You can see the supported issuer in the [cert-manager documentation](https://cert-manager.io/docs/configuration/issuers/). + 1. Manage your private key and certificate files manually. + - You can issue and manage your private key and certificate files by using your preferred method on your own. + - You can use any certificate even if cert-manager does not support it. + - You must update secret resources when certificates expire. +1. Kinds of certificates + 1. Use a trusted CA (signed certificate by third party). + - You can use trusted certificates from a third-party certificate issuer. + - You can encrypt packets. + - You must pay costs to issue trusted certificates. + 1. Use self-signed certificates. + - You can reduce costs to issue certificates. + - Reliability of certificates is lower than a trusted CA, but you can encrypt packets. + +In other words, you have the following four options: + +1. Use a self-signed CA with automatic management. +1. Use a trusted CA with automatic management. +1. Use a self-signed CA with manual management. +1. Use a trusted CA with manual management. + +You should consider which method you use based on your security requirements. For guidance and related documentation for each method, refer to the following decision tree: + +```mermaid +flowchart TD + A[Do you want to use
cert-manager to manage your
private key and certificate
files automatically?] + A -->|Yes, I want to manage my
certificates automatically.| B + A -->|No, I want to manage my
certificates manually by myself.| C + B[Do you want to use a
self-signed CA or a trusted CA?] + C[Do you want to use a
self-signed CA or a trusted CA?] + B -->|I want to use a
self-signed CA.| D + B -->|I want to use a
trusted CA.| E + C -->|I want to use a
self-signed CA.| F + C -->|I want to use a
trusted CA.| G + D[See the Use a self-signed
CA with cert-manager to
manage your private key and
certificate files
section.] + E[See the Use a trusted
CA with cert-manager to
manage private key and
certificate files
section.] + F[See the Use your private
key and certificate files

section, and use the self-signed
certificate you generated.] + G[See the Use your private key
and certificate files
section,
and use the trusted certificate
generated by the third party.] +``` + +#### Enable TLS in downstream connections + +You can enable TLS in downstream connections by using the following configurations: + +```yaml +envoy: + tls: + downstream: + enabled: true +``` + +##### Use your private key and certificate files + +You can set your private key and certificate files by using the following configurations: + +```yaml +envoy: + tls: + downstream: + enabled: true + certChainSecret: "envoy-tls-cert" + privateKeySecret: "envoy-tls-key" +``` + +In this case, you have to create secret resources that include private key and certificate files for Scalar Envoy as follows, replacing the contents in the angle brackets as described: + +```console +kubectl create secret generic envoy-tls-cert --from-file=tls.crt=/ -n +kubectl create secret generic envoy-tls-key --from-file=tls.key=/ -n +``` + +For more details on how to prepare private key and certificate files, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx). + +##### Use a trusted CA with cert-manager to manage your private key and certificate files + +You can manage your private key and certificate files with cert-manager by using the following configurations, replacing the content in the angle brackets as described: + +:::note + +* If you want to use cert-manager, you must deploy cert-manager and prepare the `Issuers` resource. For details, see the cert-manager documentation, [Installation](https://cert-manager.io/docs/installation/) and [Issuer Configuration](https://cert-manager.io/docs/configuration/). +* By default, Scalar Helm Chart creates a `Certificate` resource that satisfies the certificate requirements of Scalar products. The default certificate configuration is recommended, but if you use a custom certificate configuration, you must satisfy the certificate requirements of Scalar products. For details, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements). + +::: + +```yaml +envoy: + tls: + downstream: + enabled: true + certManager: + enabled: true + issuerRef: + name: + dnsNames: + - envoy.scalar.example.com +``` + +In this case, cert-manager issues your private key and certificate files by using your trusted issuer. By using cert-manager, you don't need to mount your private key and certificate files manually. + +##### Use a self-signed CA with cert-manager to manage your private key and certificate files + +You can manage your private key and self-signed certificate files with cert-manager by using the following configurations: + +:::note + +* If you want to use cert-manager, you must deploy cert-manager. For details, see the cert-manager documentation, [Installation](https://cert-manager.io/docs/installation/). +* By default, Scalar Helm Chart creates a `Certificate` resource that satisfies the certificate requirements of Scalar products. The default certificate configuration is recommended, but if you use a custom certificate configuration, you must satisfy the certificate requirements of Scalar products. For details, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements). + +::: + +```yaml +envoy: + tls: + downstream: + enabled: true + certManager: + enabled: true + selfSigned: + enabled: true + dnsNames: + - envoy.scalar.example.com +``` + +In this case, Scalar Helm Charts and cert-manager issue your private key and self-signed certificate files. You don't need to mount your private key and certificate files manually. + +#### Enable TLS in upstream connections + +You can enable TLS in upstream connections by using the following configurations: + +```yaml +envoy: + tls: + upstream: + enabled: true +``` + +Also, you must set root CA certificate file of upstream Scalar products. To determine which approach you should take, refer to the following decision tree: + +```mermaid +flowchart TD + A[Are you using cert-manager?] + A -->|Yes| B + A -->|No| D + B[Are you using a self-signed CA with cert-manager?] + B -->|No| C[Are you using the same trusted CA for Envoy and
upstream Scalar products with cert-manager?] + C -->|No| D[You must set upstream Scalar products'
root CA certificate
manually.] + C ---->|Yes| E[Scalar Helm Chart automatically sets the root CA certificate. You
don't need to set `envoy.tls.upstream.caRootCertSecret` explicitly.] + B ---->|Yes| E +``` + +##### Set your root CA certificate file of upstream Scalar products + +You can set your root CA certificate file by using the following configurations: + +```yaml +envoy: + tls: + upstream: + enabled: true + caRootCertSecret: "envoy-upstream-scalardb-cluster-root-ca" +``` + +In this case, you have to create secret resources that include CA certificate files as follows. You must set the root CA certificate file based on the upstream that you use (ScalarDB Cluster, ScalarDL Ledger, or ScalarDL Auditor). Be sure to replace the contents in the angle brackets as described. + + + + ```console + kubectl create secret generic envoy-upstream-scalardb-cluster-root-ca --from-file=ca.crt=/ -n + ``` + + + ```console + kubectl create secret generic envoy-upstream-scalardl-ledger-root-ca --from-file=ca.crt=/ -n + ``` + + + ```console + kubectl create secret generic envoy-upstream-scalardl-auditor-root-ca --from-file=ca.crt=/ -n + ``` + + + +For more details on how to prepare private key and certificate files, see [How to create key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx). + +##### Set custom authority for TLS communications + +You can set the custom authority for TLS communications by using `envoy.tls.upstream.overrideAuthority`. This value doesn't change what host is actually connected. This value is intended for testing but may safely be used outside of tests as an alternative to DNS overrides. For example, you can specify the hostname presented in the certificate chain file that you set by using `scalardbCluster.tls.certChainSecret`, `ledger.tls.certChainSecret`, or `auditor.tls.certChainSecret`, depending on which product you're using. Envoy uses this value for verifying the certificate of the TLS connection with ScalarDB Cluster or ScalarDL. + +```yaml +envoy: + tls: + upstream: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" +``` + +### Replica configurations (Optional based on your environment) + +You can specify the number of replicas (pods) of Scalar Envoy using `envoy.replicaCount`. + +```yaml +envoy: + replicaCount: 3 +``` + +### Taint and toleration configurations (Optional based on your environment) + +If you want to control pod deployment by using the taints and tolerations in Kubernetes, you can use `envoy.tolerations`. + +You can configure taints and tolerations by using the same syntax as the tolerations in Kubernetes. For details on configuring tolerations in Kubernetes, see the official Kubernetes documentation [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). + +```yaml +envoy: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb +``` diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-file.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-file.mdx new file mode 100644 index 00000000..9e59653a --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-file.mdx @@ -0,0 +1,21 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Configure a custom values file for Scalar Helm Charts + +When you deploy Scalar products using Scalar Helm Charts, you must prepare your custom values file based on your environment. Please refer to the following documents for more details on how to a create custom values file for each product. + +* [ScalarDB Cluster](configure-custom-values-scalardb-cluster.mdx) +* [ScalarDB Analytics with PostgreSQL](configure-custom-values-scalardb-analytics-postgresql.mdx) +* [ScalarDL Ledger](configure-custom-values-scalardl-ledger.mdx) +* [ScalarDL Auditor](configure-custom-values-scalardl-auditor.mdx) +* [ScalarDL Schema Loader](configure-custom-values-scalardl-schema-loader.mdx) +* [Scalar Admin for Kubernetes](configure-custom-values-scalar-admin-for-kubernetes.mdx) +* [Scalar Manager](configure-custom-values-scalar-manager.mdx) +* [Envoy](configure-custom-values-envoy.mdx) +* [[Deprecated] ScalarDB Server](configure-custom-values-scalardb.mdx) +* [[Deprecated] ScalarDB GraphQL](configure-custom-values-scalardb-graphql.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalar-admin-for-kubernetes.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalar-admin-for-kubernetes.mdx new file mode 100644 index 00000000..43b8f5e3 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalar-admin-for-kubernetes.mdx @@ -0,0 +1,136 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Configure a custom values file for Scalar Admin for Kubernetes + +This document explains how to create your custom values file for the Scalar Admin for Kubernetes chart. For details on the parameters, see the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalar-admin-for-kubernetes/README.md) of the Scalar Admin for Kubernetes chart. + +## Required configurations + +This section explains the required configurations when setting up a custom values file for Scalar Admin for Kubernetes. + +### Flag configurations + +You must specify several flags to `scalarAdminForKubernetes.commandArgs` as an array to run Scalar Admin for Kubernetes. For more details on the flags, see [README](https://github.com/scalar-labs/scalar-admin-for-kubernetes/blob/main/README.md) of Scalar Admin for Kubernetes. + +```yaml +scalarAdminForKubernetes: + commandArgs: + - -r + - + - -n + - + - -d + - + - -z + - +``` + +## Optional configurations + +This section explains the optional configurations when setting up a custom values file for Scalar Admin for Kubernetes. + +### CronJob configurations (optional based on your environment) + +By default, the Scalar Admin for Kubernetes chart creates a [Job](https://kubernetes.io/docs/concepts/workloads/controllers/job/) resource to run the Scalar Admin for Kubernetes CLI tool once. If you want to run the Scalar Admin for Kubernetes CLI tool periodically by using [CronJob](https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/), you can set `scalarAdminForKubernetes.jobType` to `cronjob`. Also, you can set some configurations for the CronJob resource. + +```yaml +scalarAdminForKubernetes: + cronJob: + timeZone: "Etc/UTC" + schedule: "0 0 * * *" +``` + +### Resource configurations (recommended in production environments) + +To control pod resources by using requests and limits in Kubernetes, you can use `scalarAdminForKubernetes.resources`. + +You can configure requests and limits by using the same syntax as requests and limits in Kubernetes. For more details on requests and limits in Kubernetes, see [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/). + +```yaml +scalarAdminForKubernetes: + resources: + requests: + cpu: 1000m + memory: 2Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### SecurityContext configurations (default value is recommended) + +To set SecurityContext and PodSecurityContext for Scalar Admin for Kubernetes pods, you can use `scalarAdminForKubernetes.securityContext` and `scalarAdminForKubernetes.podSecurityContext`. + +You can configure SecurityContext and PodSecurityContext by using the same syntax as SecurityContext and PodSecurityContext in Kubernetes. For more details on the SecurityContext and PodSecurityContext configurations in Kubernetes, see [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/). + +```yaml +scalarAdminForKubernetes: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### Image configurations (default value is recommended) + +If you want to change the image repository, you can use `scalarAdminForKubernetes.image.repository` to specify the container repository information of the Scalar Admin for Kubernetes image that you want to pull. + +```yaml +scalarAdminForKubernetes: + image: + repository: +``` + +### Taint and toleration configurations (optional based on your environment) + +If you want to control pod deployment by using taints and tolerations in Kubernetes, you can use `scalarAdminForKubernetes.tolerations`. + +You can configure taints and tolerations by using the same syntax as the tolerations in Kubernetes. For details on configuring tolerations in Kubernetes, see the official Kubernetes documentation [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). + +```yaml +scalarAdminForKubernetes: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb-analytics-postgresql +``` + +### TLS configurations (optional based on your environment) + +You can enable TLS between Scalar Admin for Kubernetes and the pause targets (ScalarDB Cluster or ScalarDL) by using the following configurations: + +```yaml +scalarAdminForKubernetes: + commandArgs: + - (omit other options) + - --tls + - --ca-root-cert-path + - /tls/certs/ca.crt + - --override-authority + - cluster.scalardb.example.com +``` + +You can mount the `/tls/certs/ca.crt` file on a pod by using a secret resource. To mount the file, specify the name of the secret resource that includes the root CA certificate file to `scalarAdminForKubernetes.tls.caRootCertSecret` as follows: + +```yaml +scalarAdminForKubernetes: + tls: + caRootCertSecret: "scalar-admin-tls-ca" +``` + +In this case, you have to create a secret resource that includes the root CA certificate file for the pause targets (ScalarDB Cluster or ScalarDL) as follows: + +```console +kubectl create secret generic scalar-admin-tls-ca --from-file=ca.crt=/path/to/your/ca/certificate/file -n +``` diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalar-manager.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalar-manager.mdx new file mode 100644 index 00000000..5c910762 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalar-manager.mdx @@ -0,0 +1,149 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# Configure a Custom Values File for Scalar Manager + +This document provides instructions on how to configure a custom values file for the Scalar Manager Helm Chart. For details about the available parameters, see the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalar-manager/README.md) in the Scalar Manager chart repository. + +## Required configurations + +This section describes the service, image, and Scalar Manager configurations that you must include in the Scalar Manager values file. + +### Service configurations + +You must configure `web.service.type` to define the Kubernetes Service resource type. To use a load balancer that cloud service providers offer for exposing the service, set `web.service.type` to `LoadBalancer`. + +```yaml +web: + service: + type: LoadBalancer + # other web configurations +``` + +#### Security considerations for exposing Scalar Manager + +Setting `web.service.type` to `LoadBalancer` exposes Scalar Manager externally via `HTTP` by default, which creates security risks on untrusted networks due to unencrypted traffic. If external access is not required, using a private network or properly configuring network access to your Kubernetes cluster is recommended. + +Scalar Manager supports authentication and authorization mechanisms. You can configure these mechanisms to ensure authorized actions for features like scheduling jobs to pause Scalar products. For details, see [Authentication configuration for Scalar Manager](#authentication-configuration-for-scalar-manager). + +### Container image configurations + +You must configure `api.image.repository` and `web.image.repository`. These settings specify the Scalar Manager container images, ensuring you can pull them from the container repository. + +```yaml +api: + image: + repository: +web: + image: + repository: +``` + +## Optional configurations + +This section describes optional configurations for customizing the Scalar Manager values file. + +### Scalar Manager configurations (optional based on your environment) + +You can override the `api.applicationProperties` setting to modify the default Scalar Manager configurations. + +```yaml +api: + applicationProperties: | + prometheus.kubernetes-service-label-name="app" + prometheus.kubernetes-service-label-value="kube-prometheus-stack-prometheus" + prometheus.kubernetes-service-port-name="http-web" + # other application properties +``` + +Scalar Manager includes default configurations to discover Scalar product deployments and the Prometheus service within the cluster. In most scenarios, especially when following the guides to deploy `kube-prometheus-stack` and `loki-stack`, these default configurations are sufficient and do not require modification. + +#### Configurable properties in `api.applicationProperties` + +The configurations for Scalar Manager are in the format of Java application properties, which are `key=value` pairs. These application properties can be set by using the `api.applicationProperties` custom value in the Scalar Manager Helm Chart. + +| Name | Description | Default Value | +|:--------------------------------------------------------------------|:----------------------------------------------------------------------------|:---------------------------------------------------------------------------| +| `prometheus.kubernetes-service-label-name` | The label name used to discover the Prometheus service in Kubernetes | `app` | +| `prometheus.kubernetes-service-label-value` | The label value corresponding to `prometheus.kubernetes-service-label-name` | `kube-prometheus-stack-prometheus` | +| `prometheus.kubernetes-service-port-name` | The port name used to discover the Prometheus service port in Kubernetes | `http-web` | +| `springdoc.swagger-ui.enabled` | Whether to enable the Swagger UI or not | `false` | +| `springdoc.swagger-ui.path` | The path of the Swagger UI | `/swagger-ui.html` | +| `app.cors.allowed-origins` | The allowed origins for CORS | `*` | +| `app.cors.allowed-methods` | The allowed methods for CORS | `*` | +| `app.cors.allowed-headers` | The allowed headers for CORS | `*` | +| `authentication.providers.static-jwt.secret` | Secret key used for signing JWT tokens; minimum 32 characters | `example-jwt-secret-with-minimum-32-characters` | +| `authentication.providers.static-jwt.issuer-uri` | The issuer URI of the JWT tokens | `https://scalar-manager.example.com` | +| `authentication.providers.static-jwt.access-token-expiration-time` | The expiration time of the access token | `1h` | +| `authentication.providers.static-jwt.refresh-token-expiration-time` | The expiration time of the refresh token | `3d` | +| `app.initial-admin-user.enabled` | Whether to enable the initial admin user or not | `true` | +| `app.initial-admin-user.email` | The email address of the initial admin user | `admin@example.com` | +| `app.initial-admin-user.name` | The name of the initial admin user | `Administrator` | +| `app.initial-admin-user.password` | The password of the initial admin user | `Password@123!` | +| `spring.jpa.hibernate.ddl-auto` | The DDL mode for Hibernate | `update` | +| `spring.jpa.show-sql` | Whether to show the SQL query | `false` | +| `spring.jpa.properties.hibernate.format_sql` | Whether to format the SQL query | `false` | +| `spring.datasource.url` | The URL of the database | `jdbc:postgresql://scalar-manager-postgres-postgresql:5432/scalar-manager` | +| `spring.datasource.username` | The username of the database | `scalar-manager` | +| `spring.datasource.password` | The password of the database | `scalar-manager` | +| `spring.datasource.driver-class-name` | The driver class name of the database | `org.postgresql.Driver` | + +:::note + +There are more configurations that you can set in `api.applicationProperties` regarding the JPA, Hibernate, and Spring Data. If you're familiar with these configurations, you can set them to customize the database connection and the behavior of Scalar Manager. + +::: + +##### Authentication configuration for Scalar Manager + +By default, to access Scalar Manager, you need to authenticate by using a username and password. + +The following are the prerequisites for setting up authentication: + +- You need to have a PostgreSQL database, either your own or one that a cloud service provider hosts. For example, you can use the [Bitnami package for PostgreSQL](https://artifacthub.io/packages/helm/bitnami/postgresql) to deploy a PostgreSQL database in your Kubernetes cluster. +- You must set the `authentication.providers.static-jwt.secret` configuration. This configuration is used for signing JWT tokens, and the minimum length of the secret is 32 characters. + +The following is an example of the additional configurations you need to set in the `api.applicationProperties` to apply the above prerequisites. Be sure to change the configurations to match your environment. + +```properties +# JWT configuration +# Secret key used for signing JWT tokens, minimum 32 characters +authentication.providers.static-jwt.secret=${AUTHENTICATION_PROVIDERS_STATIC_JWT_SECRET:example-jwt-secret-with-minimum-32-characters} +authentication.providers.static-jwt.issuer-uri=${AUTHENTICATION_PROVIDERS_STATIC_JWT_ISSUER_URI:https://scalar-manager.example.com} +authentication.providers.static-jwt.access-token-expiration-time=${AUTHENTICATION_PROVIDERS_STATIC_JWT_ACCESS_TOKEN_EXPIRATION_TIME:1h} +authentication.providers.static-jwt.refresh-token-expiration-time=${AUTHENTICATION_PROVIDERS_STATIC_JWT_REFRESH_TOKEN_EXPIRATION_TIME:3d} + +# Initial admin configuration +app.initial-admin-user.enabled=${APP_INITIAL_ADMIN_USER_ENABLED:true} +app.initial-admin-user.email=${APP_INITIAL_ADMIN_USER_EMAIL:admin@example.com} +app.initial-admin-user.name=${APP_INITIAL_ADMIN_USER_NAME:Administrator} +app.initial-admin-user.password=${APP_INITIAL_ADMIN_USER_PASSWORD:Password@123!} + +# JPA configuration +spring.jpa.hibernate.ddl-auto=${SPRING_JPA_HIBERNATE_DDL_AUTO:update} +spring.jpa.show-sql=${SPRING_JPA_SHOW_SQL:false} +spring.jpa.properties.hibernate.format_sql=${SPRING_JPA_PROPERTIES_HIBERNATE_FORMAT_SQL:false} + +# Database configuration +spring.datasource.url=jdbc:postgresql://${DATABASE_HOST:scalar-manager-postgres-postgresql}:${DATABASE_PORT:5432}/${DATABASE_NAME:scalar-manager} +spring.datasource.username=${DATABASE_USERNAME:scalar-manager} +spring.datasource.password=${DATABASE_PASSWORD:scalar-manager} +spring.datasource.driver-class-name=org.postgresql.Driver +``` + +##### Service discovery + +Scalar Manager uses labels to discover the Prometheus service in Kubernetes, and then uses the port name to connect to them. You can modify the labels and the port name by setting the `prometheus.kubernetes-service-label-name`, `prometheus.kubernetes-service-label-value`, and `prometheus.kubernetes-service-port-name` configurations. + +In general, you don't need to modify these configurations. However, if you customized the labels or port names of the Prometheus service when installing their Helm Charts, you should adjust these configurations to match your customizations. + +#### Configurable environment variables in `web.env` + +| Name | Description | Default Value | +|:---------------------|:---------------------------------------------------------|:---------------------------------------------------------------------| +| `GRAFANA_SERVER_URL` | The URL of the Grafana service in the Kubernetes cluster | `http://scalar-monitoring-grafana.monitoring.svc.cluster.local:3000` | + +Currently, the `GRAFANA_SERVER_URL` variable can be set in `web.env` to customize the proxy from the Scalar Manager web UI to the Grafana UI. By default, the variable is set to the Grafana service `scalar-monitoring-grafana` installed in the `monitoring` namespace. If you have installed Grafana in different namespace or have changed the name of the Grafana service, you will need to update the `GRAFANA_SERVER_URL` variable accordingly. diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-analytics-postgresql.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-analytics-postgresql.mdx new file mode 100644 index 00000000..5d1eb638 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-analytics-postgresql.mdx @@ -0,0 +1,189 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# Configure a custom values file for ScalarDB Analytics with PostgreSQL + +This document explains how to create your custom values file for the ScalarDB Analytics with PostgreSQL chart. For details on the parameters, see the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardb-analytics-postgresql/README.md) of the ScalarDB Analytics with PostgreSQL chart. + +## Required configurations + +This section explains the required configurations when setting up a custom values file for ScalarDB Analytics with PostgreSQL. + +### Database configurations + +To access databases via ScalarDB Analytics with PostgreSQL, you must set the `scalardbAnalyticsPostgreSQL.databaseProperties` parameter by following the same syntax that you use to configure the `database.properties` file. For details about configurations, see [ScalarDB Configurations](https://scalardb.scalar-labs.com/docs/latest/configurations/). + +```yaml +scalardbAnalyticsPostgreSQL: + databaseProperties: | + scalar.db.contact_points=localhost + scalar.db.username=${env:SCALAR_DB_USERNAME:-} + scalar.db.password=${env:SCALAR_DB_PASSWORD:-} + scalar.db.storage=cassandra +``` + +### Database namespaces configurations + +You must set `schemaImporter.namespaces` to all the database namespaces that include tables you want to read via ScalarDB Analytics with PostgreSQL. + +```yaml +schemaImporter: + namespaces: + - namespace1 + - namespace2 + - namespace3 +``` + +## Optional configurations + +This section explains the optional configurations when setting up a custom values file for ScalarDB Analytics with PostgreSQL. + +### Resource configurations (recommended in production environments) + +To control pod resources by using requests and limits in Kubernetes, you can use `scalardbAnalyticsPostgreSQL.resources`. + +You can configure requests and limits by using the same syntax as requests and limits in Kubernetes. For more details on requests and limits in Kubernetes, see [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/). + +```yaml +scalardbAnalyticsPostgreSQL: + resources: + requests: + cpu: 1000m + memory: 2Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### Secret configurations (recommended in production environments) + +To use environment variables to set some properties, like credentials, in `scalardbAnalyticsPostgreSQL.databaseProperties`, you can use `scalardbAnalyticsPostgreSQL.secretName` to specify the secret resource that includes some credentials. + +For example, you can set credentials for a backend database (`scalar.db.username` and `scalar.db.password`) by using environment variables, which makes your pods more secure. + +For more details on how to use a secret resource, see [How to use Secret resources to pass the credentials as the environment variables into the properties file](use-secret-for-credentials.mdx). + +```yaml +scalardbAnalyticsPostgreSQL: + secretName: "scalardb-analytics-postgresql-credentials-secret" +``` + +### Affinity configurations (recommended in production environments) + +To control pod deployment by using affinity and anti-affinity in Kubernetes, you can use `scalardbAnalyticsPostgreSQL.affinity`. + +You can configure affinity and anti-affinity by using the same syntax for affinity and anti-affinity in Kubernetes. For more details on configuring affinity in Kubernetes, see [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/). + +```yaml +scalardbAnalyticsPostgreSQL: + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardb-analytics-postgresql + - key: app.kubernetes.io/app + operator: In + values: + - scalardb-analytics-postgresql + topologyKey: kubernetes.io/hostname +``` + +### SecurityContext configurations (default value is recommended) + +To set SecurityContext and PodSecurityContext for ScalarDB Analytics with PostgreSQL pods, you can use `scalardbAnalyticsPostgreSQL.securityContext`, `scalardbAnalyticsPostgreSQL.podSecurityContext`, and `schemaImporter.securityContext`. + +You can configure SecurityContext and PodSecurityContext by using the same syntax as SecurityContext and PodSecurityContext in Kubernetes. For more details on the SecurityContext and PodSecurityContext configurations in Kubernetes, see [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/). + +```yaml +scalardbAnalyticsPostgreSQL: + podSecurityContext: + fsGroup: 201 + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + runAsUser: 999 + allowPrivilegeEscalation: false + +schemaImporter: + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### Image configurations (default value is recommended) + +If you want to change the image repository, you can use `scalardbAnalyticsPostgreSQL.image.repository` and `schemaImporter.image.repository` to specify the container repository information of the ScalarDB Analytics with PostgreSQL and Schema Importer images that you want to pull. + +```yaml +scalardbAnalyticsPostgreSQL: + image: + repository: + +schemaImporter: + image: + repository: +``` + +### Replica configurations (optional based on your environment) + +You can specify the number of ScalarDB Analytics with PostgreSQL replicas (pods) by using `scalardbAnalyticsPostgreSQL.replicaCount`. + +```yaml +scalardbAnalyticsPostgreSQL: + replicaCount: 3 +``` + +### PostgreSQL database name configuration (optional based on your environment) + +You can specify the database name that you create in PostgreSQL. Schema Importer creates some objects, such as a view of ScalarDB Analytics with PostgreSQL, in this database. + +```yaml +scalardbAnalyticsPostgreSQL: + postgresql: + databaseName: scalardb +``` + +### PostgreSQL superuser password configuration (optional based on your environment) + +You can specify the secret name that includes the superuser password for PostgreSQL. + +```yaml +scalardbAnalyticsPostgreSQL: + postgresql: + secretName: scalardb-analytics-postgresql-superuser-password +``` + +:::note + +You must create a secret resource with this name (`scalardb-analytics-postgresql-superuser-password` by default) before you deploy ScalarDB Analytics with PostgreSQL. For details, see [Prepare a secret resource](how-to-deploy-scalardb-analytics-postgresql.mdx#prepare-a-secret-resource). + +::: + +### Taint and toleration configurations (optional based on your environment) + +If you want to control pod deployment by using taints and tolerations in Kubernetes, you can use `scalardbAnalyticsPostgreSQL.tolerations`. + +You can configure taints and tolerations by using the same syntax as the tolerations in Kubernetes. For details on configuring tolerations in Kubernetes, see the official Kubernetes documentation [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). + +```yaml +scalardbAnalyticsPostgreSQL: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb-analytics-postgresql +``` diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-cluster.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-cluster.mdx new file mode 100644 index 00000000..f4d29e79 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-cluster.mdx @@ -0,0 +1,419 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Configure a custom values file for ScalarDB Cluster + +This document explains how to create your custom values file for the ScalarDB Cluster chart. For details on the parameters, see the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardb-cluster/README.md) of the ScalarDB Cluster chart. + +## Required configurations + +### Image configurations + +You must set `scalardbCluster.image.repository`. Be sure to specify the ScalarDB Cluster container image so that you can pull the image from the container repository. + +```yaml +scalardbCluster: + image: + repository: +``` + +### Database configurations + +You must set `scalardbCluster.scalardbClusterNodeProperties`. Please set `scalardb-cluster-node.properties` to this parameter. For more details on the configurations of ScalarDB Cluster, see [ScalarDB Cluster Configurations](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-configurations/). + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} + scalar.db.contact_points=localhost + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + scalar.db.storage=cassandra +``` + +Note that you must always set the following three properties if you deploy ScalarDB Cluster in a Kubernetes environment by using Scalar Helm Chart. These properties are fixed values. Since the properties don't depend on individual environments, you can set the same values by copying the following values and pasting them in `scalardbCluster.scalardbClusterNodeProperties`. + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} +``` + +## Optional configurations + +### Resource configurations (recommended in production environments) + +To control pod resources by using requests and limits in Kubernetes, you can use `scalardbCluster.resources`. + +Note that, for commercial licenses, the resources for each pod of Scalar products are limited to 2vCPU / 4GB memory. Also, if you use the pay-as-you-go containers that the AWS Marketplace provides, you will not be able to run any containers that exceed the 2vCPU / 4GB memory configuration in `resources.limits`. If you exceed this resource limitation, the pods will automatically stop. + +You can configure requests and limits by using the same syntax as requests and limits in Kubernetes. For more details on requests and limits in Kubernetes, see [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/). + +```yaml +scalardbCluster: + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### Secret configurations (recommended in production environments) + +To use environment variables to set some properties (e.g., credentials) in `scalardbCluster.scalardbClusterNodeProperties`, you can use `scalardbCluster.secretName` to specify the Secret resource that includes some credentials. + +For example, you can set credentials for a backend database (`scalar.db.username` and `scalar.db.password`) by using environment variables, which makes your pods more secure. + +For more details on how to use a Secret resource, see [How to use Secret resources to pass the credentials as the environment variables into the properties file](use-secret-for-credentials.mdx). + +```yaml +scalardbCluster: + secretName: "scalardb-cluster-credentials-secret" +``` + +### Affinity configurations (recommended in production environments) + +To control pod deployment by using affinity and anti-affinity in Kubernetes, you can use `scalardbCluster.affinity`. + +You can configure affinity and anti-affinity by using the same syntax for affinity and anti-affinity in Kubernetes. For more details on configuring affinity in Kubernetes, see [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/). + +```yaml +scalardbCluster: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardb-cluster + - key: app.kubernetes.io/app + operator: In + values: + - scalardb-cluster + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus and Grafana configurations (recommended in production environments) + +To monitor ScalarDB Cluster pods by using [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack), you can set `scalardbCluster.grafanaDashboard.enabled`, `scalardbCluster.serviceMonitor.enabled`, and `scalardbCluster.prometheusRule.enabled` to `true`. When you set these configurations to `true`, the chart deploys the necessary resources and kube-prometheus-stack starts monitoring automatically. + +```yaml +scalardbCluster: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext configurations (default value is recommended) + +To set SecurityContext and PodSecurityContext for ScalarDB Cluster pods, you can use `scalardbCluster.securityContext` and `scalardbCluster.podSecurityContext`. + +You can configure SecurityContext and PodSecurityContext by using the same syntax as SecurityContext and PodSecurityContext in Kubernetes. For more details on the SecurityContext and PodSecurityContext configurations in Kubernetes, see [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/). + +```yaml +scalardbCluster: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### TLS configurations (optional based on your environment) + +You can enable TLS in: + +- The communications between the ScalarDB Cluster node and clients. +- The communications between all ScalarDB Cluster nodes (the cluster's internal communications). + +In addition, you have several options for certificate management. For more details, see [TLS configurations for Envoy](./configure-custom-values-envoy.mdx#tls-configurations-optional-based-on-your-environment). + +You should consider which method you use based on your security requirements. For guidance and related documentation for each method, refer to the following decision tree: + +```mermaid +flowchart TD + A[Do you want to use
cert-manager to manage your
private key and certificate
files automatically?] + A -->|Yes, I want to manage my
certificates automatically.| B + A -->|No, I want to manage my
certificates manually by myself.| C + B[Do you want to use a
self-signed CA or a trusted CA?] + C[Do you want to use a
self-signed CA or a trusted CA?] + B -->|I want to use a
self-signed CA.| D + B -->|I want to use a
trusted CA.| E + C -->|I want to use a
self-signed CA.| F + C -->|I want to use a
trusted CA.| G + D[See the Use a self-signed
CA with cert-manager to
manage your private key and
certificate files
section.] + E[See the Use a trusted
CA with cert-manager to
manage private key and
certificate files
section.] + F[See the Use your private
key and certificate files

section, and use the self-signed
certificate you generated.] + G[See the Use your private key
and certificate files
section,
and use the trusted certificate
generated by the third party.] +``` + +#### Enable TLS + +You can enable TLS in all ScalarDB Cluster connections by using the following configurations: + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + ...(omit)... + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/tls/scalardb-cluster/certs/ca.crt + scalar.db.cluster.node.tls.cert_chain_path=/tls/scalardb-cluster/certs/tls.crt + scalar.db.cluster.node.tls.private_key_path=/tls/scalardb-cluster/certs/tls.key + scalar.db.cluster.tls.override_authority= + tls: + enabled: true +``` + +##### Use your private key and certificate files + +You can set your private key and certificate files by using the following configurations: + +```yaml +scalardbCluster: + tls: + enabled: true + caRootCertSecret: "scalardb-cluster-tls-ca" + certChainSecret: "scalardb-cluster-tls-cert" + privateKeySecret: "scalardb-cluster-tls-key" +``` + +In this case, you have to create secret resources that include private key and certificate files for ScalarDB Cluster as follows, replacing the contents in the angle brackets as described: + +```console +kubectl create secret generic scalardb-cluster-tls-ca --from-file=ca.crt=/ -n +kubectl create secret generic scalardb-cluster-tls-cert --from-file=tls.crt=/ -n +kubectl create secret generic scalardb-cluster-tls-key --from-file=tls.key=/ -n +``` + +For more details on how to prepare private key and certificate files, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx). + +##### Use a trusted CA with cert-manager to manage your private key and certificate files + +You can manage your private key and certificate files with cert-manager by using the following configurations, replacing the content in the angle brackets as described: + +:::note + +* If you want to use cert-manager, you must deploy cert-manager and prepare the `Issuers` resource. For details, see the cert-manager documentation, [Installation](https://cert-manager.io/docs/installation/) and [Issuer Configuration](https://cert-manager.io/docs/configuration/). +* By default, Scalar Helm Chart creates a `Certificate` resource that satisfies the certificate requirements of Scalar products. The default certificate configuration is recommended, but if you use a custom certificate configuration, you must satisfy the certificate requirements of Scalar products. For details, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements). + +::: + +```yaml +scalardbCluster: + tls: + enabled: true + certManager: + enabled: true + issuerRef: + name: + dnsNames: + - cluster.scalardb.example.com +``` + +In this case, cert-manager issues your private key and certificate files by using your trusted issuer. You don't need to mount your private key and certificate files manually. + +##### Use a self-signed CA with cert-manager to manage your private key and certificate files + +You can manage your private key and self-signed certificate files with cert-manager by using the following configurations: + +:::note + +* If you want to use cert-manager, you must deploy cert-manager. For more details on how to deploy cert-manager, see the [Installation](https://cert-manager.io/docs/installation/) in the cert-manager official document. +* By default, Scalar Helm Chart creates a `Certificate` resource that satisfies the certificate requirements of Scalar products. We recommend the default certificate configuration, but if you custom certificate configuration, you must satisfy the certificate requirements of Scalar products. See [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements). + +::: + +```yaml +scalardbCluster: + tls: + enabled: true + certManager: + enabled: true + selfSigned: + enabled: true + dnsNames: + - cluster.scalardb.example.com +``` + +In this case, Scalar Helm Charts and cert-manager issue your private key and self-signed certificate files. You don't need to mount your private key and certificate files manually. + +##### Set custom authority for TLS communications + +You can set the custom authority for TLS communications by using `scalardbCluster.tls.overrideAuthority`. This value doesn't change what host is actually connected. This value is intended for testing but may safely be used outside of tests as an alternative to DNS overrides. For example, you can specify the hostname presented in the certificate chain file that you set by using `scalardbCluster.tls.certChainSecret`. This chart uses this value for `startupProbe` and `livenessProbe`. + +```yaml +scalardbCluster: + tls: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" +``` + +##### Set a root CA certificate for Prometheus Operator + +If you set `scalardbCluster.serviceMonitor.enabled=true` and `scalardbCluster.tls.enabled=true` (in other words, if you monitor ScalarDB Cluster with TLS configuration by using Prometheus Operator), you must set the secret name to `scalardbCluster.tls.caRootCertSecretForServiceMonitor`. + +```yaml +scalardbCluster: + tls: + enabled: true + caRootCertSecretForServiceMonitor: "scalardb-cluster-tls-ca-for-prometheus" +``` + +In this case, you have to create secret resources that include a root CA certificate for ScalarDB Cluster in the same namespace as Prometheus as follows: + +```console +kubectl create secret generic scalardb-cluster-tls-ca-for-prometheus --from-file=ca.crt=/path/to/your/ca/certificate/file -n +``` + +### Replica configurations (optional based on your environment) + +You can specify the number of ScalarDB Cluster replicas (pods) by using `scalardbCluster.replicaCount`. + +```yaml +scalardbCluster: + replicaCount: 3 +``` + +### Logging configurations (optional based on your environment) + +To change the ScalarDB Cluster log level, you can use `scalardbCluster.logLevel`. + +```yaml +scalardbCluster: + logLevel: INFO +``` + +### GraphQL configurations (optional based on your environment) + +To use the GraphQL feature in ScalarDB Cluster, you can set `scalardbCluster.graphql.enabled` to `true` to deploy some resources for the GraphQL feature. Note that you also need to set `scalar.db.graphql.enabled=true` in `scalardbCluster.scalardbClusterNodeProperties` when using the GraphQL feature. + +```yaml +scalardbCluster: + graphql: + enabled: true +``` + +Also, you can configure the `Service` resource that accepts GraphQL requests from clients. + +```yaml +scalardbCluster: + graphql: + service: + type: ClusterIP + annotations: {} + ports: + graphql: + port: 8080 + targetPort: 8080 + protocol: TCP +``` + +### SQL configurations (optional based on your environment) + +To use the SQL feature in ScalarDB Cluster, there is no configuration necessary for custom values files. You can use the feature by setting `scalar.db.sql.enabled=true` in `scalardbCluster.scalardbClusterNodeProperties`. + +### Scalar Envoy configurations (optional based on your environment) + +To use ScalarDB Cluster with `indirect` mode, you must enable Envoy as follows. + +```yaml +envoy: + enabled: true +``` + +Also, you must set the Scalar Envoy configurations in the custom values file for ScalarDB Cluster. This is because clients need to send requests to ScalarDB Cluster via Scalar Envoy as the load balancer of gRPC requests if you deploy ScalarDB Cluster in a Kubernetes environment with `indirect` mode. + +For more details on Scalar Envoy configurations, see [Configure a custom values file for Scalar Envoy](configure-custom-values-envoy.mdx). + +```yaml +envoy: + configurationsForScalarEnvoy: + ... + +scalardbCluster: + configurationsForScalarDbCluster: + ... +``` + +### Taint and toleration configurations (optional based on your environment) + +If you want to control pod deployment by using the taints and tolerations in Kubernetes, you can use `scalardbCluster.tolerations`. + +You can configure taints and tolerations by using the same syntax as the tolerations in Kubernetes. For details on configuring tolerations in Kubernetes, see the official Kubernetes documentation [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). + +```yaml +scalardbCluster: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb-cluster +``` + +### Encryption configurations (optional based on your environment) + +You can enable [encryption at rest](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/encrypt-data-at-rest/) to protect the data in the backend databases. When you use the encryption feature, you have the following two deployment options: + +1. Use HashiCorp Vault (HashiCorp Cloud Platform (HCP) Vault Dedicated) to manage and store the DEKs. +1. Use ScalarDB Cluster to manage the DEK, and store it in Kubernetes Secrets. + +#### Use HashiCorp Vault + +You can use HashiCorp Vault (HCP Vault Dedicated) to encrypt data as follows, replacing the contents in the angle brackets as described: + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + ...(omit)... + scalar.db.cluster.encryption.enabled=true + scalar.db.cluster.encryption.type=vault + scalar.db.cluster.encryption.vault.address=https://: + scalar.db.cluster.encryption.vault.token= + scalar.db.cluster.encryption.vault.transit_secrets_engine_path= + encryption: + enabled: true + type: "vault" +``` + +#### Use ScalarDB Cluster and Kubernetes Secrets + +You can use ScalarDB Cluster and Kubernetes Secrets to encrypt data as follows, replacing the contents in the angle brackets as described: + +```yaml +scalardbCluster: + scalardbClusterNodeProperties: | + ...(omit)... + scalar.db.cluster.encryption.enabled=true + scalar.db.cluster.encryption.type=self + scalar.db.cluster.encryption.self.kubernetes.secret.namespace_name=${env:SCALAR_DB_CLUSTER_ENCRYPTION_SELF_KUBERNETES_SECRET_NAMESPACE_NAME} + encryption: + enabled: true + type: "self" +``` + +In this case, you don't need to replace `${env:SCALAR_DB_CLUSTER_ENCRYPTION_SELF_KUBERNETES_SECRET_NAMESPACE_NAME}` since the Helm Chart for ScalarDB Cluster automatically sets the namespace information as an environment variable. Because of this, you can keep the value `${env:SCALAR_DB_CLUSTER_ENCRYPTION_SELF_KUBERNETES_SECRET_NAMESPACE_NAME}` as is. diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-graphql.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-graphql.mdx new file mode 100644 index 00000000..9bab7a7f --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb-graphql.mdx @@ -0,0 +1,224 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# [Deprecated] Configure a custom values file for ScalarDB GraphQL + +:::note + +ScalarDB GraphQL Server is now deprecated. Please use [ScalarDB Cluster](configure-custom-values-scalardb-cluster.mdx) instead. + +::: + +This document explains how to create your custom values file for the ScalarDB GraphQL chart. If you want to know the details of the parameters, please refer to the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardb-graphql/README.md) of the ScalarDB GraphQL chart. + +## Required configurations + +### Ingress configuration + +You must set `ingress` to listen the client requests. When you deploy multiple GraphQL servers, session affinity is required to handle transactions properly. This is because GraphQL servers keep the transactions in memory, so GraphQL queries that use continued transactions must be routed to the same server that started the transaction. + +For example, if you use NGINX Ingress Controller, you can set ingress configurations as follows. + +```yaml +ingress: + enabled: true + className: nginx + annotations: + nginx.ingress.kubernetes.io/session-cookie-path: / + nginx.ingress.kubernetes.io/affinity: cookie + nginx.ingress.kubernetes.io/session-cookie-name: INGRESSCOOKIE + nginx.ingress.kubernetes.io/session-cookie-hash: sha1 + nginx.ingress.kubernetes.io/session-cookie-max-age: "300" + hosts: + - host: "" + paths: + - path: /graphql + pathType: Exact +``` + +If you use ALB of AWS, you can set ingress configurations as follows. + +```yaml +ingress: + enabled: true + className: alb + annotations: + alb.ingress.kubernetes.io/scheme: internal + alb.ingress.kubernetes.io/target-group-attributes: stickiness.enabled=true,stickiness.lb_cookie.duration_seconds=60 + alb.ingress.kubernetes.io/target-type: ip + alb.ingress.kubernetes.io/healthcheck-path: /graphql?query=%7B__typename%7D + hosts: + - host: "" + paths: + - path: /graphql + pathType: Exact +``` + +### Image configurations + +You must set `image.repository`. Be sure to specify the ScalarDB GraphQL container image so that you can pull the image from the container repository. + +```yaml +image: + repository: +``` + +If you're using AWS or Azure, please refer to the following documents for more details: + +* [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) +* [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +### Database configurations + +You must set `scalarDbGraphQlConfiguration`. + +If you use ScalarDB Server with ScalarDB GraphQL (recommended), you must set the configuration to access the ScalarDB Server pods. + +```yaml +scalarDbGraphQlConfiguration: + contactPoints: + contactPort: 60051 + storage: "grpc" + transactionManager: "grpc" + namespaces: +``` + +## Optional configurations + +### Resource configurations (Recommended in the production environment) + +If you want to control pod resources using the requests and limits of Kubernetes, you can use `resources`. + +Note that the resources for one pod of Scalar products are limited to 2vCPU / 4GB memory from the perspective of the commercial license. Also, when you get the pay-as-you-go containers provided from AWS Marketplace, you cannot run those containers with more than 2vCPU / 4GB memory configuration in the `resources.limits`. When you exceed this limitation, pods are automatically stopped. + +You can configure them using the same syntax as the requests and limits of Kubernetes. So, please refer to the official document [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) for more details on the requests and limits of Kubernetes. + +```yaml +resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### Affinity configurations (Recommended in the production environment) + +If you want to control pod deployment using the affinity and anti-affinity of Kubernetes, you can use `affinity`. + +You can configure them using the same syntax as the affinity of Kubernetes. So, please refer to the official document [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) for more details on the affinity configuration of Kubernetes. + +```yaml +affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/app + operator: In + values: + - scalardb-graphql + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus/Grafana configurations (Recommended in the production environment) + +If you want to monitor ScalarDB GraphQL pods using [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack), you can deploy a ConfigMap, a ServiceMonitor, and a PrometheusRule resource for kube-prometheus-stack using `grafanaDashboard.enabled`, `serviceMonitor.enabled`, and `prometheusRule.enabled`. + +```yaml +grafanaDashboard: + enabled: true + namespace: monitoring +serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s +prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext configurations (Default value is recommended) + +If you want to set SecurityContext and PodSecurityContext for ScalarDB GraphQL pods, you can use `securityContext` and `podSecurityContext`. + +You can configure them using the same syntax as SecurityContext and PodSecurityContext of Kubernetes. So, please refer to the official document [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for more details on the SecurityContext and PodSecurityContext configurations of Kubernetes. + +```yaml +podSecurityContext: + seccompProfile: + type: RuntimeDefault + +securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### GraphQL Server configurations (Optional based on your environment) + +If you want to change the path to run the graphql queries, you can use `scalarDbGraphQlConfiguration.path`. By default, you can run the graphql queries using `http://:80/graphql`. + +You can also enable/disable [GraphiQL](https://github.com/graphql/graphiql/tree/main/packages/graphiql) using `scalarDbGraphQlConfiguration.graphiql`. + +```yaml +scalarDbGraphQlConfiguration: + path: /graphql + graphiql: "true" +``` + +### TLS configurations (Optional based on your environment) + +If you want to use TLS between the client and the ingress, you can use `ingress.tls`. + +You must create a Secret resource that includes a secret key and a certificate file. Please refer to the official document [Ingress - TLS](https://kubernetes.io/docs/concepts/services-networking/ingress/#tls) for more details on the Secret resource for Ingress. + +```yaml +ingress: + tls: + - hosts: + - foo.example.com + - bar.example.com + - bax.example.com + secretName: graphql-ingress-tls +``` + +### Replica configurations (Optional based on your environment) + +You can specify the number of replicas (pods) of ScalarDB GraphQL using `replicaCount`. + +```yaml +replicaCount: 3 +``` + +### Logging configurations (Optional based on your environment) + +If you want to change the log level of ScalarDB GraphQL, you can use `scalarDbGraphQlConfiguration.logLevel`. + +```yaml +scalarDbGraphQlConfiguration: + logLevel: INFO +``` + +### Taint and toleration configurations (Optional based on your environment) + +If you want to control pod deployment by using the taints and tolerations in Kubernetes, you can use `tolerations`. + +You can configure taints and tolerations by using the same syntax as the tolerations in Kubernetes. For details on configuring tolerations in Kubernetes, see the official Kubernetes documentation [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). + +```yaml +tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb +``` diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb.mdx new file mode 100644 index 00000000..86346ba7 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardb.mdx @@ -0,0 +1,202 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsEnglish +--- + +# [Deprecated] Configure a custom values file for ScalarDB Server + +:::note + +ScalarDB Server is now deprecated. Please use [ScalarDB Cluster](configure-custom-values-scalardb-cluster.mdx) instead. + +::: + +This document explains how to create your custom values file for the ScalarDB Server chart. If you want to know the details of the parameters, please refer to the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardb/README.md) of the ScalarDB Server chart. + +## Required configurations + +### Scalar Envoy configurations + +You must set the Scalar Envoy configurations in the custom values file for ScalarDB Server. This is because client requests are sent to ScalarDB Server via Scalar Envoy as the load balancer of gRPC requests if you deploy ScalarDB Server on a Kubernetes environment. + +Please refer to the document [Configure a custom values file for Scalar Envoy](configure-custom-values-envoy.mdx) for more details on the Scalar Envoy configurations. + +```yaml +envoy: + configurationsForScalarEnvoy: + ... + +scalardb: + configurationsForScalarDB: + ... +``` + +### Image configurations + +You must set `scalardb.image.repository`. Be sure to specify the ScalarDB Server container image so that you can pull the image from the container repository. + +```yaml +scalardb: + image: + repository: +``` + +If you're using AWS or Azure, please refer to the following documents for more details: + +* [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) +* [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +### Database configurations + +You must set `scalardb.databaseProperties`. Please set your `database.properties` to this parameter. Please refer to the [Configure ScalarDB Server](https://scalardb.scalar-labs.com/docs/latest/scalardb-server#configure-scalardb-server) for more details on the configuration of ScalarDB Server. + +```yaml +scalardb: + databaseProperties: | + scalar.db.server.port=60051 + scalar.db.server.prometheus_exporter_port=8080 + scalar.db.server.grpc.max_inbound_message_size= + scalar.db.server.grpc.max_inbound_metadata_size= + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + scalar.db.storage=cassandra + scalar.db.transaction_manager=consensus-commit + scalar.db.consensus_commit.isolation_level=SNAPSHOT + scalar.db.consensus_commit.serializable_strategy= + scalar.db.consensus_commit.include_metadata.enabled=false +``` + +## Optional configurations + +### Resource configurations (Recommended in the production environment) + +If you want to control pod resources using the requests and limits of Kubernetes, you can use `scalardb.resources`. + +Note that the resources for one pod of Scalar products are limited to 2vCPU / 4GB memory from the perspective of the commercial license. Also, when you get the pay-as-you-go containers provided from AWS Marketplace, you cannot run those containers with more than 2vCPU / 4GB memory configuration in the `resources.limits`. When you exceed this limitation, pods are automatically stopped. + +You can configure them using the same syntax as the requests and limits of Kubernetes. So, please refer to the official document [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) for more details on the requests and limits of Kubernetes. + +```yaml +scalardb: + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### Secret configurations (Recommended in the production environment) + +If you want to use environment variables to set some properties (e.g., credentials) in the `scalardb.databaseProperties`, you can use `scalardb.secretName` to specify the Secret resource that includes some credentials. + +For example, you can set credentials for a backend database (`scalar.db.username` and `scalar.db.password`) using environment variables, which makes your pods more secure. + +Please refer to the document [How to use Secret resources to pass the credentials as the environment variables into the properties file](use-secret-for-credentials.mdx) for more details on how to use a Secret resource. + +```yaml +scalardb: + secretName: "scalardb-credentials-secret" +``` + +### Affinity configurations (Recommended in the production environment) + +If you want to control pod deployment using the affinity and anti-affinity of Kubernetes, you can use `scalardb.affinity`. + +You can configure them using the same syntax as the affinity of Kubernetes. So, please refer to the official document [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) for more details on the affinity configuration of Kubernetes. + +```yaml +scalardb: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardb + - key: app.kubernetes.io/app + operator: In + values: + - scalardb + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus/Grafana configurations (Recommended in the production environment) + +If you want to monitor ScalarDB Server pods using [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack), you can deploy a ConfigMap, a ServiceMonitor, and a PrometheusRule resource for kube-prometheus-stack using `scalardb.grafanaDashboard.enabled`, `scalardb.serviceMonitor.enabled`, and `scalardb.prometheusRule.enabled`. + +```yaml +scalardb: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext configurations (Default value is recommended) + +If you want to set SecurityContext and PodSecurityContext for ScalarDB Server pods, you can use `scalardb.securityContext` and `scalardb.podSecurityContext`. + +You can configure them using the same syntax as SecurityContext and PodSecurityContext of Kubernetes. So, please refer to the official document [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for more details on the SecurityContext and PodSecurityContext configurations of Kubernetes. + +```yaml +scalardb: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### Replica configurations (Optional based on your environment) + +You can specify the number of replicas (pods) of ScalarDB Server using `scalardb.replicaCount`. + +```yaml +scalardb: + replicaCount: 3 +``` + +### Logging configurations (Optional based on your environment) + +If you want to change the log level of ScalarDB Server, you can use `scalardb.storageConfiguration.dbLogLevel`. + +```yaml +scalardb: + storageConfiguration: + dbLogLevel: INFO +``` + +### Taint and toleration configurations (Optional based on your environment) + +If you want to control pod deployment by using the taints and tolerations in Kubernetes, you can use `scalardb.tolerations`. + +You can configure taints and tolerations by using the same syntax as the tolerations in Kubernetes. For details on configuring tolerations in Kubernetes, see the official Kubernetes documentation [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). + +```yaml +scalardb: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb +``` diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-auditor.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-auditor.mdx new file mode 100644 index 00000000..223ec550 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-auditor.mdx @@ -0,0 +1,365 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Configure a custom values file for ScalarDL Auditor + +This document explains how to create your custom values file for the ScalarDL Auditor chart. If you want to know the details of the parameters, please refer to the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardl-audit/README.md) of the ScalarDL Auditor chart. + +## Required configurations + +### Scalar Envoy configurations + +You must set the Scalar Envoy configurations in the custom values file for ScalarDL Auditor. This is because client requests are sent to ScalarDL Auditor via Scalar Envoy as the load balancer of gRPC requests if you deploy ScalarDL Auditor on a Kubernetes environment. + +Please refer to the document [Configure a custom values file for Scalar Envoy](configure-custom-values-envoy.mdx) for more details on the Scalar Envoy configurations. + +```yaml +envoy: + configurationsForScalarEnvoy: + ... + +auditor: + configurationsForScalarDLAuditor: + ... +``` + +### Image configurations + +You must set `auditor.image.repository`. Be sure to specify the ScalarDL Auditor container image so that you can pull the image from the container repository. + +```yaml +auditor: + image: + repository: +``` + +For more details on the container repository for Scalar products, see [How to get the container images of Scalar products](../scalar-kubernetes/HowToGetContainerImages.mdx). + +### Auditor/Database configurations + +You must set `auditor.auditorProperties`. Please set your `auditor.properties` to this parameter. Please refer to the [auditor.properties](https://github.com/scalar-labs/scalar/blob/master/auditor/conf/auditor.properties) for more details on the configuration of ScalarDL Auditor. + +```yaml +auditor: + auditorProperties: | + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + scalar.db.storage=cassandra + scalar.dl.auditor.ledger.host= + scalar.dl.auditor.private_key_path=/keys/auditor-key-file + scalar.dl.auditor.cert_path=/keys/auditor-cert-file +``` + +### Key/Certificate configurations + +You must set a private key file to `scalar.dl.auditor.private_key_path` and a certificate file to `scalar.dl.auditor.cert_path`. + +You must also mount the private key file and the certificate file on the ScalarDL Auditor pod. + +For more details on how to mount the private key file and the certificate file, refer to [Mount key and certificate files on a pod in ScalarDL Helm Charts](mount-files-or-volumes-on-scalar-pods.mdx#mount-key-and-certificate-files-on-a-pod-in-scalardl-helm-charts). + +## Optional configurations + +### Resource configurations (Recommended in the production environment) + +If you want to control pod resources using the requests and limits of Kubernetes, you can use `auditor.resources`. + +Note that the resources for one pod of Scalar products are limited to 2vCPU / 4GB memory from the perspective of the commercial license. Also, when you get the pay-as-you-go containers provided from AWS Marketplace, you cannot run those containers with more than 2vCPU / 4GB memory configuration in the `resources.limits`. When you exceed this limitation, pods are automatically stopped. + +You can configure them using the same syntax as the requests and limits of Kubernetes. So, please refer to the official document [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) for more details on the requests and limits of Kubernetes. + +```yaml +auditor: + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### Secret configurations + +If you want to use environment variables to set some properties (e.g., credentials) in the `auditor.auditorProperties`, you can use `auditor.secretName` to specify the Secret resource that includes some credentials. + +For example, you can set credentials for a backend database (`scalar.db.username` and `scalar.db.password`) using environment variables, which makes your pods more secure. + +Please refer to the document [How to use Secret resources to pass the credentials as the environment variables into the properties file](use-secret-for-credentials.mdx) for more details on how to use a Secret resource. + +```yaml +auditor: + secretName: "auditor-credentials-secret" +``` + +### Affinity configurations (Recommended in the production environment) + +If you want to control pod deployment using the affinity and anti-affinity of Kubernetes, you can use `auditor.affinity`. + +You can configure them using the same syntax as the affinity of Kubernetes. So, please refer to the official document [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) for more details on the affinity configuration of Kubernetes. + +```yaml +auditor: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardl-audit + - key: app.kubernetes.io/app + operator: In + values: + - auditor + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus/Grafana configurations (Recommended in the production environment) + +If you want to monitor ScalarDL Auditor pods using [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack), you can deploy a ConfigMap, a ServiceMonitor, and a PrometheusRule resource for kube-prometheus-stack using `auditor.grafanaDashboard.enabled`, `auditor.serviceMonitor.enabled`, and `auditor.prometheusRule.enabled`. + +```yaml +auditor: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext configurations (Default value is recommended) + +If you want to set SecurityContext and PodSecurityContext for ScalarDL Auditor pods, you can use `auditor.securityContext` and `auditor.podSecurityContext`. + +You can configure them using the same syntax as SecurityContext and PodSecurityContext of Kubernetes. So, please refer to the official document [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for more details on the SecurityContext and PodSecurityContext configurations of Kubernetes. + +```yaml +auditor: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### TLS configurations (optional based on your environment) + +You can enable TLS in: + +- The communications between the ScalarDL Auditor and clients. +- The communications between the ScalarDL Ledger and ScalarDL Auditor. + +In addition, you have several options for certificate management. For more details, see [TLS configurations for Envoy](./configure-custom-values-envoy.mdx#tls-configurations-optional-based-on-your-environment). + +You should consider which method you use based on your security requirements. For guidance and related documentation for each method, refer to the following decision tree: + +```mermaid +flowchart TD + A[Do you want to use
cert-manager to manage your
private key and certificate
files automatically?] + A -->|Yes, I want to manage my
certificates automatically.| B + A -->|No, I want to manage my
certificates manually by myself.| C + B[Do you want to use a
self-signed CA or a trusted CA?] + C[Do you want to use a
self-signed CA or a trusted CA?] + B -->|I want to use a
self-signed CA.| D + B -->|I want to use a
trusted CA.| E + C -->|I want to use a
self-signed CA.| F + C -->|I want to use a
trusted CA.| G + D[See the Use a self-signed
CA with cert-manager to
manage your private key and
certificate files
section.] + E[See the Use a trusted
CA with cert-manager to
manage private key and
certificate files
section.] + F[See the Use your private
key and certificate files

section, and use the self-signed
certificate you generated.] + G[See the Use your private key
and certificate files
section,
and use the trusted certificate
generated by the third party.] +``` + +#### Enable TLS + +You can enable TLS in all ScalarDL Auditor connections by using the following configurations: + +```yaml +auditor: + auditorProperties: | + ...(omit)... + scalar.dl.auditor.server.tls.enabled=true + scalar.dl.auditor.server.tls.cert_chain_path=/tls/scalardl-auditor/certs/tls.crt + scalar.dl.auditor.server.tls.private_key_path=/tls/scalardl-auditor/certs/tls.key + scalar.dl.auditor.tls.enabled=true + scalar.dl.auditor.tls.ca_root_cert_path=/tls/scalardl-ledger/certs/ca.crt + scalar.dl.auditor.tls.override_authority=envoy.scalar.example.com + tls: + enabled: true +``` + +##### Use your private key and certificate files + +You can set your private key and certificate files by using the following configurations: + +```yaml +auditor: + tls: + enabled: true + caRootCertSecret: "scalardl-auditor-tls-ca" + certChainSecret: "scalardl-auditor-tls-cert" + privateKeySecret: "scalardl-auditor-tls-key" +``` + +In this case, you have to create secret resources that include private key and certificate files for ScalarDL Ledger and ScalarDL Auditor as follows, replacing the contents in the angle brackets as described: + +```console +kubectl create secret generic scalardl-auditor-tls-ca --from-file=ca.crt=/ -n +kubectl create secret generic scalardl-auditor-tls-cert --from-file=tls.crt=/ -n +kubectl create secret generic scalardl-auditor-tls-key --from-file=tls.key=/ -n +kubectl create secret generic scalardl-auditor-tls-ca-for-ledger --from-file=ca.crt=/ -n +``` + +For more details on how to prepare private key and certificate files, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx). + +##### Use a trusted CA with cert-manager to manage your private key and certificate files + +You can manage your private key and certificate files with cert-manager by using the following configurations, replacing the content in the angle brackets as described: + +:::note + +* If you want to use cert-manager, you must deploy cert-manager and prepare the `Issuers` resource. For details, see the cert-manager documentation, [Installation](https://cert-manager.io/docs/installation/) and [Issuer Configuration](https://cert-manager.io/docs/configuration/). +* By default, Scalar Helm Chart creates a `Certificate` resource that satisfies the certificate requirements of Scalar products. The default certificate configuration is recommended, but if you use a custom certificate configuration, you must satisfy the certificate requirements of Scalar products. For details, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements). + +::: + +```yaml +auditor: + tls: + enabled: true + certManager: + enabled: true + issuerRef: + name: + dnsNames: + - auditor.scalardl.example.com +``` + +In this case, cert-manager issues your private key and certificate files by using your trusted issuer. You don't need to mount private key and certificate files manually. + +##### Use a self-signed CA with cert-manager to manage your private key and certificate files + +You can manage your private key and self-signed certificate files with cert-manager by using the following configurations: + +:::note + +* If you want to use cert-manager, you must deploy cert-manager. For details, see the cert-manager documentation, [Installation](https://cert-manager.io/docs/installation/). +* By default, Scalar Helm Chart creates a `Certificate` resource that satisfies the certificate requirements of Scalar products. The default certificate configuration is recommended, but if you use a custom certificate configuration, you must satisfy the certificate requirements of Scalar products. For details, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements). + +::: + +```yaml +auditor: + tls: + enabled: true + certManager: + enabled: true + selfSigned: + enabled: true + dnsNames: + - auditor.scalardl.example.com +``` + +In this case, Scalar Helm Charts and cert-manager issue your private key and self-signed certificate files. You don't need to mount private key and certificate files manually. + +#### Set a root CA certificate for ScalarDL Ledger + +If you enable TLS on the ScalarDL Ledger side, you must set a root CA certificate file for Envoy in front of ScalarDL Ledger to access it from ScalarDL Auditor. To determine which approach you should take, refer to the following decision tree: + +```mermaid +flowchart TD + A[Are you using cert-manager?] + A -->|Yes| B + A -->|No| D + B[Are you using a self-signed CA with cert-manager?] + B -->|No| C[Are you using the same trusted CA for ScalarDL
Ledger and ScalarDL Auditor with cert-manager?] + C -->|No| D[You must set the root
CA certificate of Envoy for ScalarDL Ledger manually.] + C ---->|Yes| E[Scalar Helm Chart automatically sets the root CA certificate. You
don't need to set `auditor.tls.upstream.caRootCertSecret` explicitly.] +``` + +If you need to set the root CA certificate file of Envoy manually, you can set it by using the following configurations: + +```yaml +auditor: + tls: + enabled: true + caRootCertForLedgerSecret: "scalardl-auditor-tls-ca-for-ledger" +``` + +In this case, you have to create secret resources that include root CA certificate files as follows, replacing the contents in the angle brackets as described: + +```console +kubectl create secret generic scalardl-auditor-tls-ca-for-ledger --from-file=ca.crt=//scalardl-ledger -n +``` + +##### Set custom authority for TLS communications + +You can set the custom authority for TLS communications by using `auditor.tls.overrideAuthority`. This value doesn't change what host is actually connected. This value is intended for testing but may safely be used outside of tests as an alternative to DNS overrides. For example, you can specify the hostname presented in the certificate chain file that you set by using `auditor.tls.certChainSecret`. This chart uses this value for `startupProbe` and `livenessProbe`. + +##### Set a root CA certificate for Prometheus Operator + +If you set `auditor.serviceMonitor.enabled=true` and `auditor.tls.enabled=true` (in other words, if you monitor ScalarDL Auditor with TLS configuration by using Prometheus Operator), you must set the secret name to `auditor.tls.caRootCertSecretForServiceMonitor`. + +```yaml +auditor: + tls: + enabled: true + caRootCertSecretForServiceMonitor: "scalardl-auditor-tls-ca-for-prometheus" +``` + +In this case, you have to create secret resources that include a root CA certificate for ScalarDL Auditor in the same namespace as Prometheus as follows: + +```console +kubectl create secret generic scalardl-auditor-tls-ca-for-prometheus --from-file=ca.crt=/path/to/your/ca/certificate/file -n +``` + +### Replica configurations (Optional based on your environment) + +You can specify the number of replicas (pods) of ScalarDL Auditor using `auditor.replicaCount`. + +```yaml +auditor: + replicaCount: 3 +``` + +### Logging configurations (Optional based on your environment) + +If you want to change the log level of ScalarDL Auditor, you can use `auditor.scalarAuditorConfiguration.auditorLogLevel`. + +```yaml +auditor: + scalarAuditorConfiguration: + auditorLogLevel: INFO +``` + +### Taint and toleration configurations (Optional based on your environment) + +If you want to control pod deployment by using the taints and tolerations in Kubernetes, you can use `auditor.tolerations`. + +You can configure taints and tolerations by using the same syntax as the tolerations in Kubernetes. For details on configuring tolerations in Kubernetes, see the official Kubernetes documentation [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). + +```yaml +auditor: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardl-auditor +``` diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-ledger.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-ledger.mdx new file mode 100644 index 00000000..0e1671da --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-ledger.mdx @@ -0,0 +1,338 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Configure a custom values file for ScalarDL Ledger + +This document explains how to create your custom values file for the ScalarDL Ledger chart. If you want to know the details of the parameters, please refer to the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/scalardl/README.md) of the ScalarDL Ledger chart. + +## Required configurations + +### Scalar Envoy configurations + +You must set the Scalar Envoy configurations in the custom values file for ScalarDL Ledger. This is because client requests are sent to ScalarDL Ledger via Scalar Envoy as the load balancer of gRPC requests if you deploy ScalarDL Ledger on a Kubernetes environment. + +Please refer to the document [Configure a custom values file for Scalar Envoy](configure-custom-values-envoy.mdx) for more details on the Scalar Envoy configurations. + +```yaml +envoy: + configurationsForScalarEnvoy: + ... + +ledger: + configurationsForScalarDLLedger: + ... +``` + +### Image configurations + +You must set `ledger.image.repository`. Be sure to specify the ScalarDL Ledger container image so that you can pull the image from the container repository. + +```yaml +ledger: + image: + repository: +``` + +For more details on the container repository for Scalar products, see [How to get the container images of Scalar products](../scalar-kubernetes/HowToGetContainerImages.mdx). + +### Ledger/Database configurations + +You must set `ledger.ledgerProperties`. Please set your `ledger.properties` to this parameter. Please refer to the [ledger.properties](https://github.com/scalar-labs/scalar/blob/master/ledger/conf/ledger.properties) for more details on the configuration of ScalarDL Ledger. + +```yaml +ledger: + ledgerProperties: | + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + scalar.db.storage=cassandra + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/ledger-key-file +``` + +### Key/Certificate configurations + +If you set `scalar.dl.ledger.proof.enabled` to `true` (this configuration is required if you use ScalarDL Auditor), you must set a private key file to `scalar.dl.ledger.proof.private_key_path`. + +In this case, you must mount the private key file on the ScalarDL Ledger pod. + +For more details on how to mount the private key file, refer to [Mount key and certificate files on a pod in ScalarDL Helm Charts](mount-files-or-volumes-on-scalar-pods.mdx#mount-key-and-certificate-files-on-a-pod-in-scalardl-helm-charts). + +## Optional configurations + +### Resource configurations (Recommended in the production environment) + +If you want to control pod resources using the requests and limits of Kubernetes, you can use `ledger.resources`. + +Note that the resources for one pod of Scalar products are limited to 2vCPU / 4GB memory from the perspective of the commercial license. Also, when you get the pay-as-you-go containers provided from AWS Marketplace, you cannot run those containers with more than 2vCPU / 4GB memory configuration in the `resources.limits`. When you exceed this limitation, pods are automatically stopped. + +You can configure them using the same syntax as the requests and limits of Kubernetes. So, please refer to the official document [Resource Management for Pods and Containers](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) for more details on the requests and limits of Kubernetes. + +```yaml +ledger: + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 2000m + memory: 4Gi +``` + +### Secret configurations (Recommended in the production environment) + +If you want to use environment variables to set some properties (e.g., credentials) in the `ledger.ledgerProperties`, you can use `ledger.secretName` to specify the Secret resource that includes some credentials. + +For example, you can set credentials for a backend database (`scalar.db.username` and `scalar.db.password`) using environment variables, which makes your pods more secure. + +Please refer to the document [How to use Secret resources to pass the credentials as the environment variables into the properties file](use-secret-for-credentials.mdx) for more details on how to use a Secret resource. + +```yaml +ledger: + secretName: "ledger-credentials-secret" +``` + +### Affinity configurations (Recommended in the production environment) + +If you want to control pod deployment using the affinity and anti-affinity of Kubernetes, you can use `ledger.affinity`. + +You can configure them using the same syntax as the affinity of Kubernetes. So, please refer to the official document [Assigning Pods to Nodes](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) for more details on the affinity configuration of Kubernetes. + +```yaml +ledger: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchExpressions: + - key: app.kubernetes.io/name + operator: In + values: + - scalardl + - key: app.kubernetes.io/app + operator: In + values: + - ledger + topologyKey: kubernetes.io/hostname + weight: 50 +``` + +### Prometheus/Grafana configurations (Recommended in the production environment) + +If you want to monitor ScalarDL Ledger pods using [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack), you can deploy a ConfigMap, a ServiceMonitor, and a PrometheusRule resource for kube-prometheus-stack using `ledger.grafanaDashboard.enabled`, `ledger.serviceMonitor.enabled`, and `ledger.prometheusRule.enabled`. + +```yaml +ledger: + grafanaDashboard: + enabled: true + namespace: monitoring + serviceMonitor: + enabled: true + namespace: monitoring + interval: 15s + prometheusRule: + enabled: true + namespace: monitoring +``` + +### SecurityContext configurations (Default value is recommended) + +If you want to set SecurityContext and PodSecurityContext for ScalarDL Ledger pods, you can use `ledger.securityContext` and `ledger.podSecurityContext`. + +You can configure them using the same syntax as SecurityContext and PodSecurityContext of Kubernetes. So, please refer to the official document [Configure a Security Context for a Pod or Container](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for more details on the SecurityContext and PodSecurityContext configurations of Kubernetes. + +```yaml +ledger: + podSecurityContext: + seccompProfile: + type: RuntimeDefault + securityContext: + capabilities: + drop: + - ALL + runAsNonRoot: true + allowPrivilegeEscalation: false +``` + +### TLS configurations (optional based on your environment) + +You can enable TLS in: + +- The communications between the ScalarDL Ledger and clients. +- The communications between the ScalarDL Ledger and ScalarDL Auditor. + +Also, you have several options from the certificate management. See [TLS configurations on the Envoy document side](./configure-custom-values-envoy.mdx#tls-configurations-optional-based-on-your-environment) for more details. + +Please consider which you use based on your security requirements. According to your decision, you can see the related document as follows: + +```mermaid +flowchart TD + A[Do you want to use
cert-manager to manage your
private key and certificate
files automatically?] + A -->|Yes, I want to manage my
certificates automatically.| B + A -->|No, I want to manage my
certificates manually by myself.| C + B[Do you want to use a
self-signed CA or a trusted CA?] + C[Do you want to use a
self-signed CA or a trusted CA?] + B -->|I want to use a
self-signed CA.| D + B -->|I want to use a
trusted CA.| E + C -->|I want to use a
self-signed CA.| F + C -->|I want to use a
trusted CA.| G + D[See the Use a self-signed
CA with cert-manager to
manage your private key and
certificate files
section.] + E[See the Use a trusted
CA with cert-manager to
manage private key and
certificate files
section.] + F[See the Use your private
key and certificate files

section, and use the self-signed
certificate you generated.] + G[See the Use your private key
and certificate files
section,
and use the trusted certificate
generated by the third party.] +``` + +#### Enable TLS + +You can enable TLS in all ScalarDL Ledger connections by using the following configurations: + +```yaml +ledger: + ledgerProperties: | + ...(omit)... + scalar.dl.ledger.server.tls.enabled=true + scalar.dl.ledger.server.tls.cert_chain_path=/tls/scalardl-ledger/certs/tls.crt + scalar.dl.ledger.server.tls.private_key_path=/tls/scalardl-ledger/certs/tls.key + tls: + enabled: true +``` + +##### Use your private key and certificate files + +You can set your private key and certificate files by using the following configurations: + +```yaml +ledger: + tls: + enabled: true + caRootCertSecret: "scalardl-ledger-tls-ca" + certChainSecret: "scalardl-ledger-tls-cert" + privateKeySecret: "scalardl-ledger-tls-key" +``` + +In this case, you have to create secret resources that include private key and certificate files for ScalarDL Ledger as follows, replacing the contents in the angle brackets as described: + +```console +kubectl create secret generic scalardl-ledger-tls-ca --from-file=ca.crt=/ -n +kubectl create secret generic scalardl-ledger-tls-cert --from-file=tls.crt=/ -n +kubectl create secret generic scalardl-ledger-tls-key --from-file=tls.key=/ -n +``` + +For more details on how to prepare private key and certificate files, see [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx). + +##### Use a trusted CA with cert-manager to manage your private key and certificate files + +You can manage private key and certificate with cert-manager by using the following configurations: + +:::note + +* If you want to use cert-manager, you must deploy cert-manager and prepare the `Issuers` resource. For more details on cert-manager, see the [Installation](https://cert-manager.io/docs/installation/) and [Issuer Configuration](https://cert-manager.io/docs/configuration/) in the cert-manager official document. +* By default, Scalar Helm Chart creates a `Certificate` resource that satisfies the certificate requirements of Scalar products. We recommend the default certificate configuration, but if you custom certificate configuration, you must satisfy the certificate requirements of Scalar products. See [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements). + +::: + +```yaml +ledger: + tls: + enabled: true + certManager: + enabled: true + issuerRef: + name: your-trusted-ca + dnsNames: + - ledger.scalardl.example.com +``` + +In this case, cert-manager issues private key and certificate by using your trusted issuer. You don't need to mount private key and certificate files manually. + +##### Use a self-signed CA with cert-manager to manage your private key and certificate files + +You can manage private key and self-signed certificate with cert-manager by using the following configurations: + +:::note + +* If you want to use cert-manager, you must deploy cert-manager. For more details on how to deploy cert-manager, see the [Installation](https://cert-manager.io/docs/installation/) in the cert-manager official document. +* By default, Scalar Helm Chart creates a `Certificate` resource that satisfies the certificate requirements of Scalar products. We recommend the default certificate configuration, but if you custom certificate configuration, you must satisfy the certificate requirements of Scalar products. See [How to create private key and certificate files for Scalar products](../scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx#certificate-requirements). + +::: + +```yaml +ledger: + tls: + enabled: true + certManager: + enabled: true + selfSigned: + enabled: true + dnsNames: + - ledger.scalardl.example.com +``` + +In this case, Scalar Helm Charts and cert-manager issue private key and self-signed certificate. You don't need to mount private key and certificate files manually. + +##### Set custom authority for TLS communications + +You can set the custom authority for TLS communications by using `ledger.tls.overrideAuthority`. This value doesn't change what host is actually connected. This value is intended for testing but may safely be used outside of tests as an alternative to DNS overrides. For example, you can specify the hostname presented in the certificate chain file that you set by using `ledger.tls.certChainSecret`. This chart uses this value for `startupProbe` and `livenessProbe`. + +```yaml +ledger: + tls: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" +``` + +##### Set a root CA certificate for Prometheus Operator + +If you set `ledger.serviceMonitor.enabled=true` and `ledger.tls.enabled=true` (in other words, if you monitor ScalarDL Ledger with TLS configuration by using Prometheus Operator), you must set the secret name to `ledger.tls.caRootCertSecretForServiceMonitor`. + +```yaml +ledger: + tls: + enabled: true + caRootCertSecretForServiceMonitor: "scalardl-ledger-tls-ca-for-prometheus" +``` + +In this case, you have to create secret resources that include a root CA certificate for ScalarDL Ledger in the same namespace as Prometheus as follows: + +```console +kubectl create secret generic scalardl-ledger-tls-ca-for-prometheus --from-file=ca.crt=/path/to/your/ca/certificate/file -n +``` + +### Replica configurations (optional based on your environment) + +You can specify the number of replicas (pods) of ScalarDL Ledger using `ledger.replicaCount`. + +```yaml +ledger: + replicaCount: 3 +``` + +### Logging configurations (Optional based on your environment) + +If you want to change the log level of ScalarDL Ledger, you can use `ledger.scalarLedgerConfiguration.ledgerLogLevel`. + +```yaml +ledger: + scalarLedgerConfiguration: + ledgerLogLevel: INFO +``` + +### Taint and toleration configurations (Optional based on your environment) + +If you want to control pod deployment by using the taints and tolerations in Kubernetes, you can use `ledger.tolerations`. + +You can configure taints and tolerations by using the same syntax as the tolerations in Kubernetes. For details on configuring tolerations in Kubernetes, see the official Kubernetes documentation [Taints and Tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/). + +```yaml +ledger: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardl-ledger +``` diff --git a/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-schema-loader.mdx b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-schema-loader.mdx new file mode 100644 index 00000000..06716fc6 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/configure-custom-values-scalardl-schema-loader.mdx @@ -0,0 +1,90 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Configure a custom values file for ScalarDL Schema Loader + +This document explains how to create your custom values file for the ScalarDL Schema Loader chart. If you want to know the details of the parameters, please refer to the [README](https://github.com/scalar-labs/helm-charts/blob/main/charts/schema-loading/README.md) of the ScalarDL Schema Loader chart. + +## Required configurations + +### Database configurations + +You must set `schemaLoading.databaseProperties`. Please set your `database.properties` to access the backend database to this parameter. Please refer to the [Getting Started with ScalarDB](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb) for more details on the database configuration of ScalarDB. + +```yaml +schemaLoading: + databaseProperties: | + scalar.db.contact_points=cassandra + scalar.db.contact_port=9042 + scalar.db.username=cassandra + scalar.db.password=cassandra + scalar.db.storage=cassandra +``` + +### Schema type configurations + +You must set `schemaLoading.schemaType`. + +If you create the schema of ScalarDL Ledger, please set `ledger`. + +```yaml +schemaLoading: + schemaType: ledger +``` + +If you create the schema of ScalarDL Auditor, please set `auditor`. + +```yaml +schemaLoading: + schemaType: auditor +``` + +## Optional configurations + +### Secret configurations (Recommended in the production environment) + +If you want to use environment variables to set some properties (e.g., credentials) in the `schemaLoading.databaseProperties`, you can use `schemaLoading.secretName` to specify the Secret resource that includes some credentials. + +For example, you can set credentials for a backend database (`scalar.db.username` and `scalar.db.password`) using environment variables, which makes your pods more secure. + +Please refer to the document [How to use Secret resources to pass the credentials as the environment variables into the properties file](use-secret-for-credentials.mdx) for more details on how to use a Secret resource. + +```yaml +schemaLoading: + secretName: "schema-loader-credentials-secret" +``` + +### Image configurations (Default value is recommended) + +If you want to change the image repository, you can use `schemaLoading.image.repository` to specify which repository you want to use to pull the ScalarDL Schema Loader container image from. + +```yaml +schemaLoading: + image: + repository: +``` + +### Flags configurations (Optional based on your environment) + +You can specify several flags as an array. Please refer to the document [ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader) for more details on the flags. + +```yaml +schemaLoading: + commandArgs: + - "--alter" + - "--compaction-strategy" + - "" + - "--delete-all" + - "--no-backup" + - "--no-scaling" + - "--repair-all" + - "--replication-factor" + - "" + - "--replication-strategy" + - "" + - "--ru" + - "" +``` diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-logging.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-logging.mdx new file mode 100644 index 00000000..a2bb1b00 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-logging.mdx @@ -0,0 +1,97 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (Logging using Loki Stack) + +This document explains how to get started with log aggregation for Scalar products on Kubernetes using Grafana Loki (with Promtail). + +We assume that you have already read the [getting-started with monitoring](getting-started-monitoring.mdx) for Scalar products and installed kube-prometheus-stack. + +## What we create + +We will deploy the following components on a Kubernetes cluster as follows. + +``` ++--------------------------------------------------------------------------------------------------+ +| +------------------------------------+ | +| | loki-stack | | +| | | +-----------------+ | +| | +--------------+ +--------------+ | <-----------------(Log)-------------- | Scalar Products | | +| | | Loki | | Promtail | | | | | +| | +--------------+ +--------------+ | | +-----------+ | | +| +------------------------------------+ | | ScalarDB | | | +| | +-----------+ | | +| +------------------------------------------------------+ | | | +| | kube-prometheus-stack | | +-----------+ | | +| | | | | ScalarDL | | | +| | +--------------+ +--------------+ +--------------+ | -----(Monitor)----> | +-----------+ | | +| | | Prometheus | | Alertmanager | | Grafana | | +-----------------+ | +| | +-------+------+ +------+-------+ +------+-------+ | | +| | | | | | | +| | +----------------+-----------------+ | | +| | | | | +| +--------------------------+---------------------------+ | +| | | +| | Kubernetes | ++----------------------------+---------------------------------------------------------------------+ + | <- expose to localhost (127.0.0.1) or use load balancer etc to access + | + (Access Dashboard through HTTP) + | + +----+----+ + | Browser | + +---------+ +``` + +## Step 1. Prepare a custom values file + +1. Get the sample file [scalar-loki-stack-custom-values.yaml](conf/scalar-loki-stack-custom-values.yaml) for the `loki-stack` helm chart. + +## Step 2. Deploy `loki-stack` + +1. Add the `grafana` helm repository. + ```console + helm repo add grafana https://grafana.github.io/helm-charts + ``` + +1. Deploy the `loki-stack` helm chart. + ```console + helm install scalar-logging-loki grafana/loki-stack -n monitoring -f scalar-loki-stack-custom-values.yaml + ``` + +## Step 3. Add a Loki data source in the Grafana configuration + +1. Add a configuration of the Loki data source in the `scalar-prometheus-custom-values.yaml` file. + ```yaml + grafana: + additionalDataSources: + - name: Loki + type: loki + uid: loki + url: http://scalar-logging-loki:3100/ + access: proxy + editable: false + isDefault: false + ``` + +1. Apply the configuration (upgrade the deployment of `kube-prometheus-stack`). + ```console + helm upgrade scalar-monitoring prometheus-community/kube-prometheus-stack -n monitoring -f scalar-prometheus-custom-values.yaml + ``` + +## Step 4. Access the Grafana dashboard + +1. Add Loki as a data source + - Go to Grafana http://localhost:3000 (If you use minikube) + - Go to `Explore` to find the added Loki + - You can see the collected logs in the `Explore` page + +## Step 5. Delete the `loki-stack` helm chart + +1. Uninstall `loki-stack`. + ```console + helm uninstall scalar-logging-loki -n monitoring + ``` diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-monitoring.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-monitoring.mdx new file mode 100644 index 00000000..d42f8ed0 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-monitoring.mdx @@ -0,0 +1,267 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (Monitoring using Prometheus Operator) + +This document explains how to get started with Scalar products monitoring on Kubernetes using Prometheus Operator (kube-prometheus-stack). Here, we assume that you already have a Mac or Linux environment for testing. We use **Minikube** in this document, but the steps we will show should work in any Kubernetes cluster. + +## What we create + +We will deploy the following components on a Kubernetes cluster as follows. + +``` ++--------------------------------------------------------------------------------------------------+ +| +------------------------------------------------------+ +-----------------+ | +| | kube-prometheus-stack | | Scalar Products | | +| | | | | | +| | +--------------+ +--------------+ +--------------+ | -----(Monitor)----> | +-----------+ | | +| | | Prometheus | | Alertmanager | | Grafana | | | | ScalarDB | | | +| | +-------+------+ +------+-------+ +------+-------+ | | +-----------+ | | +| | | | | | | +-----------+ | | +| | +----------------+-----------------+ | | | ScalarDL | | | +| | | | | +-----------+ | | +| +--------------------------+---------------------------+ +-----------------+ | +| | | +| | Kubernetes | ++----------------------------+---------------------------------------------------------------------+ + | <- expose to localhost (127.0.0.1) or use load balancer etc to access + | + (Access Dashboard through HTTP) + | + +----+----+ + | Browser | + +---------+ +``` + +## Step 1. Start a Kubernetes cluster + +First, you need to prepare a Kubernetes cluster. If you use a **minikube** environment, please refer to the [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). If you have already started a Kubernetes cluster, you can skip this step. + +## Step 2. Prepare a custom values file + +1. Save the sample file [scalar-prometheus-custom-values.yaml](conf/scalar-prometheus-custom-values.yaml) for `kube-prometheus-stack`. + +1. Add custom values in the `scalar-prometheus-custom-values.yaml` as follows. + * settings + * `prometheus.service.type` to `LoadBalancer` + * `alertmanager.service.type` to `LoadBalancer` + * `grafana.service.type` to `LoadBalancer` + * `grafana.service.port` to `3000` + * Example + ```yaml + alertmanager: + + service: + type: LoadBalancer + + ... + + grafana: + + service: + type: LoadBalancer + port: 3000 + + ... + + prometheus: + + service: + type: LoadBalancer + + ... + ``` + * Note: + * If you want to customize the Prometheus Operator deployment by using Helm Charts, you'll need to set the following configurations to monitor Scalar products: + * Set `serviceMonitorSelectorNilUsesHelmValues` and `ruleSelectorNilUsesHelmValues` to `false` (`true` by default) so that Prometheus Operator can detect `ServiceMonitor` and `PrometheusRule` for Scalar products. + + * If you want to use Scalar Manager, you'll need to set the following configurations to enable Scalar Manager to collect CPU and memory resources: + * Set `kubeStateMetrics.enabled`, `nodeExporter.enabled`, and `kubelet.enabled` to `true`. + + * If you want to use Scalar Manager, you'll need to set the following configurations to enable Scalar Manager to embed Grafana: + * Set `grafana.ini.security.allow_embedding` and `grafana.ini.auth.anonymous.enabled` to `true`. + * Set `grafana.ini.auth.anonymous.org_name` to the organization you are using. If you're using the sample custom values, the value is `Main Org.`. + * Set `grafana.ini.auth.anonymous.org_role` to `Editor`. + +## Step 3. Deploy `kube-prometheus-stack` + +1. Add the `prometheus-community` helm repository. + ```console + helm repo add prometheus-community https://prometheus-community.github.io/helm-charts + ``` + +1. Create a namespace `monitoring` on the Kubernetes. + ```console + kubectl create namespace monitoring + ``` + +1. Deploy the `kube-prometheus-stack`. + ```console + helm install scalar-monitoring prometheus-community/kube-prometheus-stack -n monitoring -f scalar-prometheus-custom-values.yaml + ``` + +## Step 4. Deploy (or Upgrade) Scalar products using Helm Charts + +* Note: + * The following explains the minimum steps. If you want to know more details about the deployment of ScalarDB and ScalarDL, please refer to the following documents. + * [Getting Started with Helm Charts (ScalarDB Server)](getting-started-scalardb.mdx) + * [Getting Started with Helm Charts (ScalarDL Ledger / Ledger only)](getting-started-scalardl-ledger.mdx) + * [Getting Started with Helm Charts (ScalarDL Ledger and Auditor / Auditor mode)](getting-started-scalardl-auditor.mdx) + +1. To enable Prometheus monitoring of Scalar products, set `true` to the following configurations in the custom values file. + * Configurations + * `*.prometheusRule.enabled` + * `*.grafanaDashboard.enabled` + * `*.serviceMonitor.enabled` + * Sample configuration files + * ScalarDB (scalardb-custom-values.yaml) + ```yaml + envoy: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + + scalardb: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + ``` + * ScalarDL Ledger (scalardl-ledger-custom-values.yaml) + ```yaml + envoy: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + + ledger: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + ``` + * ScalarDL Auditor (scalardl-auditor-custom-values.yaml) + ```yaml + envoy: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + + auditor: + prometheusRule: + enabled: true + grafanaDashboard: + enabled: true + serviceMonitor: + enabled: true + ``` + +1. Deploy (or Upgrade) Scalar products using Helm Charts with the above custom values file. + * Examples + * ScalarDB + ```console + helm install scalardb scalar-labs/scalardb -f ./scalardb-custom-values.yaml + ``` + ```console + helm upgrade scalardb scalar-labs/scalardb -f ./scalardb-custom-values.yaml + ``` + * ScalarDL Ledger + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + ```console + helm upgrade scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + * ScalarDL Auditor + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + ```console + helm upgrade scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + +## Step 5. Access Dashboards + +### If you use minikube + +1. To expose each service resource as your `localhost (127.0.0.1)`, open another terminal, and run the `minikube tunnel` command. + ```console + minikube tunnel + ``` + + After running the `minikube tunnel` command, you can see the EXTERNAL-IP of each service resource as `127.0.0.1`. + ```console + kubectl get svc -n monitoring scalar-monitoring-kube-pro-prometheus scalar-monitoring-kube-pro-alertmanager scalar-monitoring-grafana + ``` + [Command execution result] + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + scalar-monitoring-kube-pro-prometheus LoadBalancer 10.98.11.12 127.0.0.1 9090:30550/TCP 26m + scalar-monitoring-kube-pro-alertmanager LoadBalancer 10.98.151.66 127.0.0.1 9093:31684/TCP 26m + scalar-monitoring-grafana LoadBalancer 10.103.19.4 127.0.0.1 3000:31948/TCP 26m + ``` + +1. Access each Dashboard. + * Prometheus + ```console + http://localhost:9090/ + ``` + * Alertmanager + ```console + http://localhost:9093/ + ``` + * Grafana + ```console + http://localhost:3000/ + ``` + * Note: + * You can see the user and password of Grafana as follows. + * user + ```console + kubectl get secrets scalar-monitoring-grafana -n monitoring -o jsonpath='{.data.admin-user}' | base64 -d + ``` + * password + ```console + kubectl get secrets scalar-monitoring-grafana -n monitoring -o jsonpath='{.data.admin-password}' | base64 -d + ``` + +### If you use other Kubernetes than minikube + +If you use a Kubernetes cluster other than minikube, you need to access the LoadBalancer service according to the manner of each Kubernetes cluster. For example, using a Load Balancer provided by cloud service or the `kubectl port-forward` command. + +## Step 6. Delete all resources + +After completing the Monitoring tests on the Kubernetes cluster, remove all resources. + +1. Terminate the `minikube tunnel` command. (If you use minikube) + ```console + Ctrl + C + ``` + +1. Uninstall `kube-prometheus-stack`. + ```console + helm uninstall scalar-monitoring -n monitoring + ``` + +1. Delete minikube. (Optional / If you use minikube) + ```console + minikube delete --all + ``` + * Note: + * If you deploy the ScalarDB or ScalarDL, you need to remove them before deleting minikube. diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalar-helm-charts.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalar-helm-charts.mdx new file mode 100644 index 00000000..d51d95db --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalar-helm-charts.mdx @@ -0,0 +1,82 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Scalar Helm Charts + +This document explains how to get started with Scalar Helm Chart on a Kubernetes cluster as a test environment. Here, we assume that you already have a Mac or Linux environment for testing. We use **Minikube** in this document, but the steps we will show should work in any Kubernetes cluster. + +## Tools + +We will use the following tools for testing. + +1. minikube (If you use other Kubernetes distributions, minikube is not necessary.) +1. kubectl +1. Helm +1. cfssl / cfssljson + +## Step 1. Install tools + +First, you need to install the following tools used in this guide. + +1. Install the `minikube` command according to the [minikube documentation](https://minikube.sigs.k8s.io/docs/start/) + +1. Install the `kubectl` command according to the [Kubernetes documentation](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/) + +1. Install the `helm` command according to the [Helm documentation](https://helm.sh/docs/intro/install/) + +1. Install the `cfssl` and `cfssljson` according to the [CFSSL documentation](https://github.com/cloudflare/cfssl) + +:::note + +You need to install the `cfssl` and `cfssljson` command when following these getting started guides: + +* [ScalarDB Cluster with TLS](getting-started-scalardb-cluster-tls.mdx) +* [ScalarDL Ledger and Auditor with TLS (Auditor mode)](getting-started-scalardl-auditor-tls.mdx) +* [ScalarDL Ledger (Ledger only)](getting-started-scalardl-ledger.mdx) +* [ScalarDL Ledger and Auditor (Auditor mode)](getting-started-scalardl-auditor.mdx) + +::: + +## Step 2. Start minikube with docker driver (Optional / If you use minikube) + +1. Start minikube. + ```console + minikube start + ``` + +1. Check the status of the minikube and pods. + ```console + kubectl get pod -A + ``` + [Command execution result] + ```console + NAMESPACE NAME READY STATUS RESTARTS AGE + kube-system coredns-64897985d-lbsfr 1/1 Running 1 (20h ago) 21h + kube-system etcd-minikube 1/1 Running 1 (20h ago) 21h + kube-system kube-apiserver-minikube 1/1 Running 1 (20h ago) 21h + kube-system kube-controller-manager-minikube 1/1 Running 1 (20h ago) 21h + kube-system kube-proxy-gsl6j 1/1 Running 1 (20h ago) 21h + kube-system kube-scheduler-minikube 1/1 Running 1 (20h ago) 21h + kube-system storage-provisioner 1/1 Running 2 (19s ago) 21h + ``` + If the minikube starts properly, you can see some pods are **Running** in the kube-system namespace. + +## Step 3. + +After the Kubernetes cluster starts, you can try each Scalar Helm Charts on it. Please refer to the following documents for more details. + +* [ScalarDB Cluster with TLS](getting-started-scalardb-cluster-tls.mdx) +* [ScalarDB Cluster with TLS by Using cert-manager](getting-started-scalardb-cluster-tls-cert-manager.mdx) +* [ScalarDB Analytics with PostgreSQL](getting-started-scalardb-analytics-postgresql.mdx) +* [ScalarDL Ledger and Auditor with TLS (Auditor mode)](getting-started-scalardl-auditor-tls.mdx) +* [ScalarDL Ledger and Auditor with TLS by Using cert-manager (Auditor mode)](getting-started-scalardl-auditor-tls-cert-manager.mdx) +* [ScalarDL Ledger (Ledger only)](getting-started-scalardl-ledger.mdx) +* [ScalarDL Ledger and Auditor (Auditor mode)](getting-started-scalardl-auditor.mdx) +* [Monitoring using Prometheus Operator](getting-started-monitoring.mdx) + * [Logging using Loki Stack](getting-started-logging.mdx) + * [Scalar Manager](getting-started-scalar-manager.mdx) +* [[Deprecated] ScalarDB Server](getting-started-scalardb.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalar-manager.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalar-manager.mdx new file mode 100644 index 00000000..0a58030a --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalar-manager.mdx @@ -0,0 +1,221 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# Deploy Scalar Manager + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +[Scalar Manager](../scalar-manager/overview.mdx) is a centralized management and monitoring solution for ScalarDB and ScalarDL in Kubernetes clusters. It enables you to: + +- Monitor the availability of ScalarDB and ScalarDL. +- Schedule and execute pausing jobs to create transactionally consistent periods in the databases used by ScalarDB and ScalarDL. +- Monitor ScalarDB and ScalarDL time-series metrics and logs through Grafana dashboards. + +This guide explains how to deploy and access Scalar Manager on a Kubernetes cluster using Scalar Helm Charts. + +## Prerequisites + +Before deploying Scalar Manager, you must do the following: + +- Install the tools mentioned in [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). +- Deploy `kube-prometheus-stack` as instructed in [Getting Started with Helm Charts (Monitoring using Prometheus Operator)](getting-started-monitoring.mdx). +- Deploy `loki-stack` as instructed in [Getting Started with Helm Charts (Logging using Loki Stack)](getting-started-logging.mdx). +- Have a running PostgreSQL database, either self-managed or from a cloud service provider. This database stores the data of Scalar Manager. For example, you can use the [Bitnami package for PostgreSQL](https://artifacthub.io/packages/helm/bitnami/postgresql) to deploy a PostgreSQL database in your Kubernetes cluster. + +## Deployment architecture diagram + +The following is an architecture diagram for the components deployed in a Kubernetes cluster. + +``` ++----------------------------------------------------------------------------------------------------------------------+ +| +----------------------------+ | +| | scalar-manager | | +| | | | +| | +------------------+ | ---------------------------------(Manage)--------------------------+ | +| +---+--->| Scalar Manager | | | | +| | | +---+--------------+ | | | +| | | | | | | +| | +--------+-------------------+ | | +| | | | | +| | +----+------------------------------------------+ | | +| | | | | | +| | +--------+------------------------------------------+---------+ | | +| | | | kube-prometheus-stack | | V | +| | | V V | +-----------------+ | +| | | +--------------+ +--------------+ +--------------+ | -----(Monitor)----> | Scalar Products | | +| | | | Prometheus | <---+ | Alertmanager | | Grafana | | | | | +| | | +------+-------+ | +--------------+ +------+-------+ | | +-----------+ | | +| | | | | | | | ScalarDB | | | +| | | +----------------------------+ | | +-----------+ | | +| | | | | | | | +| | +---------------------------------------------------+---------+ | +-----------+ | | +| | | | | ScalarDL | | | +| | +------------------------------------------+ +---------- | +-----------+ | | +| | | | +-----------------+ | +| | +--------+---------------------------+ | | +| | | | loki-stack | | | +| | | V | | | +| | | +--------------+ +--------------+ | <----------------(Log)-----------+ | +| | | | Loki | | Promtail | | | +| | | +--------------+ +--------------+ | | +| | +------------------------------------+ | +| | | +| | Kubernetes | ++----+-----------------------------------------------------------------------------------------------------------------+ + | + Expose the environment to localhost (127.0.0.1) or use a load balancer to access it + | + (Access the dashboard through HTTP) + | ++----+----+ +| Browser | ++---------+ + +``` + +## Step 1. Start minikube + +Open **Terminal**, and start minikube by running the following command: + +```console +minikube start +``` + +## Step 2. Upgrade `kube-prometheus-stack` to enable Grafana authentication with auth proxy + +To allow users to access Grafana after logging in to Scalar Manager, you must enable Grafana authentication with auth proxy. + +In your custom values file for `kube-prometheus-stack` (for example, `scalar-prometheus-custom-values.yaml`), add or revise the following configurations: + +```yaml +kubeStateMetrics: + enabled: true + +nodeExporter: + enabled: true + +kubelet: + enabled: true + +grafana: + grafana.ini: + users: + allow_sign_up: false + auto_assign_org: true + auto_assign_org_role: Editor + auth.proxy: + enabled: true + header_name: X-WEBAUTH-USER + header_property: username + auto_sign_up: true + server: + root_url: "%(protocol)s://%(domain)s:%(http_port)s/grafana" +``` + +Then, upgrade the Helm installation by running the following command: + +```console +helm upgrade scalar-monitoring prometheus-community/kube-prometheus-stack -n monitoring -f scalar-prometheus-custom-values.yaml +``` + +## Step 3. Set environment variables + +Set the following environment variables for Scalar Manager, replacing the contents in the angle brackets as described: + +```console +SCALAR_MANAGER_RELEASE_NAME= +SCALAR_MANAGER_NAMESPACE= +SCALAR_MANAGER_CUSTOM_VALUES_FILE= +SCALAR_MANAGER_CHART_VERSION= +``` + +## Step 4. Prepare a custom values file + +Prepare a custom values file for Scalar Manager: + +1. Create an empty file named `scalar-manager-custom-values.yaml`. +2. Follow the instructions in [Configure a custom values file for Scalar Manager](configure-custom-values-scalar-manager.mdx). + +## Step 5. Deploy + +Deploy the `scalar-manager` Helm Chart by running the following command: + +```console +helm install ${SCALAR_MANAGER_RELEASE_NAME} scalar-labs/scalar-manager -n ${SCALAR_MANAGER_NAMESPACE} -f ${SCALAR_MANAGER_CUSTOM_VALUES_FILE} --version ${SCALAR_MANAGER_CHART_VERSION} +``` + +## Step 6. Access Scalar Manager + +The method to access Scalar Manager depends on your Kubernetes cluster. + + + + To expose Scalar Manager on localhost (127.0.0.1), open another terminal and run the `minikube tunnel` command: + + ```console + minikube tunnel + ``` + + Then, access Scalar Manager at http://localhost:8000. + + + If you're using a Kubernetes cluster other than minikube, access the `LoadBalancer` service according to your cluster's instructions. For example, use a load balancer from your cloud service provider or use the `kubectl port-forward` command. + + + +## Additional details + +This section provides additional details related to configurations and resource discovery. + +### Upgrade Scalar Manager + +To upgrade Scalar Manager, run the following command: + +```console +helm upgrade ${SCALAR_MANAGER_RELEASE_NAME} scalar-labs/scalar-manager -n ${SCALAR_MANAGER_NAMESPACE} -f ${SCALAR_MANAGER_CUSTOM_VALUES_FILE} --version ${SCALAR_MANAGER_CHART_VERSION} +``` + +### Uninstall Scalar Manager + +To uninstall Scalar Manager, run the following command: + +```console +helm uninstall ${SCALAR_MANAGER_RELEASE_NAME} -n ${SCALAR_MANAGER_NAMESPACE} +``` + +### Optional Scalar Manager configurations + +For optional configurations that you can set for Scalar Manager, see [Optional configurations](./configure-custom-values-scalar-manager.mdx#optional-configurations) + +### Resource discovery + +Scalar Manager discovers the following Kubernetes resources in a cluster by using specific label selectors: + +- Dependencies + - Prometheus service +- Targets + - ScalarDB Cluster deployments + - ScalarDL Ledger deployments + - ScalarDL Auditor deployments + +The following sections explain how Scalar Manager discovers these resources. + +#### Dependencies + +Scalar Manager searches for the default labels and values set in the [kube-prometheus-stack](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) Helm Chart. For more information on the default labels and values that Scalar Manager uses to discover dependencies, see [Properties that you can set in `api.applicationProperties`](./configure-custom-values-scalar-manager.mdx#properties-that-you-can-set-in-apiapplicationProperties). + +Also, if you customized any values when installing `kube-prometheus-stack`, you will need to update the label selectors in the Scalar Manager custom value `api.applicationProperties`. + +#### Targets + +Scalar Manager searches for ScalarDB Cluster, ScalarDL Ledger, and ScalarDL Auditor deployments by using the following labels and values: + +- **ScalarDB Cluster:** `app.kubernetes.io/app=scalardb-cluster` +- **ScalarDL Ledger:** `app.kubernetes.io/app=ledger` +- **ScalarDL Auditor:** `app.kubernetes.io/app=auditor` + +Scalar Helm Charts use fixed labels and values for ScalarDB Cluster, ScalarDL Ledger, and ScalarDL Auditor deployments so that if you install ScalarDB and ScalarDL by using [Scalar Helm Charts](https://github.com/scalar-labs/helm-charts), Scalar Manager will automatically discover these deployments. diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-analytics-postgresql.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-analytics-postgresql.mdx new file mode 100644 index 00000000..1807de98 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-analytics-postgresql.mdx @@ -0,0 +1,511 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (ScalarDB Analytics with PostgreSQL) + +This guide explains how to get started with ScalarDB Analytics with PostgreSQL by using a Helm Chart in a Kubernetes cluster as a test environment. In addition, the contents of this guide assume that you already have a Mac or Linux environment set up for testing. Although **minikube** is mentioned, the steps described should work in any Kubernetes cluster. + +## What you will create + +You will deploy the following components in a Kubernetes cluster: + +``` ++-------------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes cluster] | +| | +| [Pod] [Pod] [Pod] | +| | +| +------------------------------------+ | +| +---> | ScalarDB Analytics with PostgreSQL | ---+ +-----------------------------+ | +| | +------------------------------------+ | +---> | MySQL ("customer" schema) | <---+ | +| | | | +-----------------------------+ | | +| +-------------+ +---------+ | +------------------------------------+ | | | | +| | OLAP client | ---> | Service | ---+---> | ScalarDB Analytics with PostgreSQL | ---+---+ +---+ | +| +-------------+ +---------+ | +------------------------------------+ | | | | | +| | | | +-----------------------------+ | | | +| | +------------------------------------+ | +---> | PostgreSQL ("order" schema) | <---+ | | +| +---> | ScalarDB Analytics with PostgreSQL | ---+ +-----------------------------+ | | +| +------------------------------------+ | | +| | | +| +-------------+ | | +| | OLTP client | ---(Load sample data with a test OLTP workload)-----------------------------------------------------------------------+ | +| +-------------+ | +| | ++-------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## Step 1. Start a Kubernetes cluster + +First, you need to prepare a Kubernetes cluster. If you're using a **minikube** environment, please refer to the [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). If you have already started a Kubernetes cluster, you can skip this step. + +## Step 2. Start MySQL and PostgreSQL pods + +ScalarDB including ScalarDB Analytics with PostgreSQL can use several types of database systems as a backend database. In this guide, you will use MySQL and PostgreSQL. + +You can deploy MySQL and PostgreSQL on the Kubernetes cluster as follows: + +1. Add the Bitnami helm repository. + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Update the helm repository. + + ```console + helm repo update bitnami + ``` + +1. Deploy MySQL. + + ```console + helm install mysql-scalardb bitnami/mysql \ + --set auth.rootPassword=mysql \ + --set primary.persistence.enabled=false + ``` + +1. Deploy PostgreSQL. + + ```console + helm install postgresql-scalardb bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. Check if the MySQL and PostgreSQL pods are running. + + ```console + kubectl get pod + ``` + + You should see the following output: + + ```console + NAME READY STATUS RESTARTS AGE + mysql-scalardb-0 1/1 Running 0 3m17s + postgresql-scalardb-0 1/1 Running 0 3m12s + ``` + +## Step 3. Create a working directory + +Since you'll be creating some configuration files locally, create a working directory for those files. + + ```console + mkdir -p ~/scalardb-analytics-postgresql-test/ + ``` + +## Step 4. Set the versions of ScalarDB, ScalarDB Analytics with PostgreSQL, and the chart + +Set the following three environment variables. If you want to use another version of ScalarDB and ScalarDB Analytics with PostgreSQL, be sure to set them to the versions that you want to use. + +:::note + +You must use the same minor versions (for example, 3.10.x) of ScalarDB Analytics with PostgreSQL as ScalarDB, but you don't need to make the patch versions match. For example, you can use ScalarDB 3.10.1 and ScalarDB Analytics with PostgreSQL 3.10.3 together. + +::: + +```console +SCALARDB_VERSION=3.10.1 +``` + +```console +SCALARDB_ANALYTICS_WITH_POSTGRESQL_VERSION=3.10.3 +``` + +```console +CHART_VERSION=$(helm search repo scalar-labs/scalardb-analytics-postgresql -l | grep -e ${SCALARDB_ANALYTICS_WITH_POSTGRESQL_VERSION} | awk '{print $2}' | sort --version-sort -r | head -n 1) +``` + +## Step 5. Run OLTP transactions to load sample data to MySQL and PostgreSQL + +Before deploying ScalarDB Analytics with PostgreSQL, run the OLTP transactions to create sample data. + +1. Start an OLTP client pod in the Kubernetes cluster. + + ```console + kubectl run oltp-client --image eclipse-temurin:8-jdk-jammy --env SCALARDB_VERSION=${SCALARDB_VERSION} -- sleep inf + ``` + +1. Check if the OLTP client pod is running. + + ```console + kubectl get pod oltp-client + ``` + + You should see the following output: + + ```console + NAME READY STATUS RESTARTS AGE + oltp-client 1/1 Running 0 17s + ``` + +1. Run bash in the OLTP client pod. + + ```console + kubectl exec -it oltp-client -- bash + ``` + + After this step, run each command in the OLTP client pod. + +1. Install the git and curl commands in the OLTP client pod. + + ```console + apt update && apt install -y curl git + ``` + +1. Clone the ScalarDB samples repository. + + ```console + git clone https://github.com/scalar-labs/scalardb-samples.git + ``` + +1. Go to the directory `scalardb-samples/multi-storage-transaction-sample/`. + + ```console + cd scalardb-samples/multi-storage-transaction-sample/ + ``` + + ```console + pwd + ``` + + You should see the following output: + + ```console + # pwd + /scalardb-samples/multi-storage-transaction-sample + ``` + +1. Create a configuration file (`database.properties`) to access MySQL and PostgreSQL in the Kubernetes cluster. + + ```console + cat << 'EOF' > database.properties + scalar.db.storage=multi-storage + scalar.db.multi_storage.storages=storage0,storage1 + + # Storage 0 + scalar.db.multi_storage.storages.storage0.storage=jdbc + scalar.db.multi_storage.storages.storage0.contact_points=jdbc:mysql://mysql-scalardb.default.svc.cluster.local:3306/ + scalar.db.multi_storage.storages.storage0.username=root + scalar.db.multi_storage.storages.storage0.password=mysql + + # Storage 1 + scalar.db.multi_storage.storages.storage1.storage=jdbc + scalar.db.multi_storage.storages.storage1.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.multi_storage.storages.storage1.username=postgres + scalar.db.multi_storage.storages.storage1.password=postgres + + scalar.db.multi_storage.namespace_mapping=customer:storage0,order:storage1 + scalar.db.multi_storage.default_storage=storage1 + EOF + ``` + +1. Download Schema Loader from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases). + + ```console + curl -OL https://github.com/scalar-labs/scalardb/releases/download/v${SCALARDB_VERSION}/scalardb-schema-loader-${SCALARDB_VERSION}.jar + ``` + +1. Run Schema Loader to create sample tables. + + ```console + java -jar scalardb-schema-loader-${SCALARDB_VERSION}.jar --config database.properties --schema-file schema.json --coordinator + ``` + +1. Load initial data for the sample workload. + + ```console + ./gradlew run --args="LoadInitialData" + ``` + +1. Run the sample workload of OLTP transactions. Running these commands will create several `order` entries as sample data. + + ```console + ./gradlew run --args="PlaceOrder 1 1:3,2:2" + ``` + + ```console + ./gradlew run --args="PlaceOrder 1 5:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 2 3:1,4:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 2 2:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 3 1:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 3 2:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 3 3:1" + ``` + + ```console + ./gradlew run --args="PlaceOrder 3 5:1" + ``` + + +1. Exit from OLTP client. + + ```console + exit + ``` + +## Step 6. Deploy ScalarDB Analytics with PostgreSQL + +After creating sample data via ScalarDB in the backend databases, deploy ScalarDB Analytics with PostgreSQL. + +1. Create a custom values file for ScalarDB Analytics with PostgreSQL (`scalardb-analytics-postgresql-custom-values.yaml`). + + ```console + cat << 'EOF' > ~/scalardb-analytics-postgresql-test/scalardb-analytics-postgresql-custom-values.yaml + scalardbAnalyticsPostgreSQL: + databaseProperties: | + scalar.db.storage=multi-storage + scalar.db.multi_storage.storages=storage0,storage1 + + # Storage 0 + scalar.db.multi_storage.storages.storage0.storage=jdbc + scalar.db.multi_storage.storages.storage0.contact_points=jdbc:mysql://mysql-scalardb.default.svc.cluster.local:3306/ + scalar.db.multi_storage.storages.storage0.username=root + scalar.db.multi_storage.storages.storage0.password=mysql + + # Storage 1 + scalar.db.multi_storage.storages.storage1.storage=jdbc + scalar.db.multi_storage.storages.storage1.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.multi_storage.storages.storage1.username=postgres + scalar.db.multi_storage.storages.storage1.password=postgres + + scalar.db.multi_storage.namespace_mapping=customer:storage0,order:storage1 + scalar.db.multi_storage.default_storage=storage1 + schemaImporter: + namespaces: + - customer + - order + EOF + ``` + +1. Create a secret resource to set a superuser password for PostgreSQL. + + ```console + kubectl create secret generic scalardb-analytics-postgresql-superuser-password --from-literal=superuser-password=scalardb-analytics + ``` + +1. Deploy ScalarDB Analytics with PostgreSQL. + + ```console + helm install scalardb-analytics-postgresql scalar-labs/scalardb-analytics-postgresql -n default -f ~/scalardb-analytics-postgresql-test/scalardb-analytics-postgresql-custom-values.yaml --version ${CHART_VERSION} + ``` + +## Step 7. Run an OLAP client pod + +To run some queries via ScalarDB Analytics with PostgreSQL, run an OLAP client pod. + +1. Start an OLAP client pod in the Kubernetes cluster. + + ```console + kubectl run olap-client --image postgres:latest -- sleep inf + ``` + +1. Check if the OLAP client pod is running. + + ```console + kubectl get pod olap-client + ``` + + You should see the following output: + + ```console + NAME READY STATUS RESTARTS AGE + olap-client 1/1 Running 0 10s + ``` + +## Step 8. Run sample queries via ScalarDB Analytics with PostgreSQL + +After running the OLAP client pod, you can run some queries via ScalarDB Analytics with PostgreSQL. + +1. Run bash in the OLAP client pod. + + ```console + kubectl exec -it olap-client -- bash + ``` + + After this step, run each command in the OLAP client pod. + +1. Run the psql command to access ScalarDB Analytics with PostgreSQL. + + ```console + psql -h scalardb-analytics-postgresql -p 5432 -U postgres -d scalardb + ``` + + The password is `scalardb-analytics`. + +1. Read sample data in the `customer.customers` table. + + ```sql + SELECT * FROM customer.customers; + ``` + + You should see the following output: + + ```sql + customer_id | name | credit_limit | credit_total + -------------+---------------+--------------+-------------- + 1 | Yamada Taro | 10000 | 10000 + 2 | Yamada Hanako | 10000 | 9500 + 3 | Suzuki Ichiro | 10000 | 8500 + (3 rows) + ``` + +1. Read sample data in the `order.orders` table. + + ```sql + SELECT * FROM "order".orders; + ``` + + You should see the following output: + + ```sql + scalardb=# SELECT * FROM "order".orders; + customer_id | timestamp | order_id + -------------+---------------+-------------------------------------- + 1 | 1700124015601 | 5ae2a41b-990d-4a16-9700-39355e29adf8 + 1 | 1700124021273 | f3f23d93-3862-48be-8a57-8368b7c8689e + 2 | 1700124028182 | 696a895a-8998-4c3b-b112-4d5763bfcfd8 + 2 | 1700124036158 | 9215d63a-a9a2-4471-a990-45897f091ca5 + 3 | 1700124043744 | 9be70cd4-4f93-4753-9d89-68e250b2ac51 + 3 | 1700124051162 | 4e8ce2d2-488c-40d6-aa52-d9ecabfc68a8 + 3 | 1700124058096 | 658b6682-2819-41f2-91ee-2802a1f02857 + 3 | 1700124071240 | 4e2f94f4-53ec-4570-af98-7c648d8ed80f + (8 rows) + ``` + +1. Read sample data in the `order.statements` table. + + ```sql + SELECT * FROM "order".statements; + ``` + + You should see the following output: + + ```sql + scalardb=# SELECT * FROM "order".statements; + order_id | item_id | count + --------------------------------------+---------+------- + 5ae2a41b-990d-4a16-9700-39355e29adf8 | 2 | 2 + 5ae2a41b-990d-4a16-9700-39355e29adf8 | 1 | 3 + f3f23d93-3862-48be-8a57-8368b7c8689e | 5 | 1 + 696a895a-8998-4c3b-b112-4d5763bfcfd8 | 4 | 1 + 696a895a-8998-4c3b-b112-4d5763bfcfd8 | 3 | 1 + 9215d63a-a9a2-4471-a990-45897f091ca5 | 2 | 1 + 9be70cd4-4f93-4753-9d89-68e250b2ac51 | 1 | 1 + 4e8ce2d2-488c-40d6-aa52-d9ecabfc68a8 | 2 | 1 + 658b6682-2819-41f2-91ee-2802a1f02857 | 3 | 1 + 4e2f94f4-53ec-4570-af98-7c648d8ed80f | 5 | 1 + (10 rows) + ``` + +1. Read sample data in the `order.items` table. + + ```sql + SELECT * FROM "order".items; + ``` + + You should see the following output: + + ```sql + scalardb=# SELECT * FROM "order".items; + item_id | name | price + ---------+--------+------- + 5 | Melon | 3000 + 2 | Orange | 2000 + 4 | Mango | 5000 + 1 | Apple | 1000 + 3 | Grape | 2500 + (5 rows) + ``` + +1. Run the `JOIN` query. For example, you can see the credit remaining information of each user as follows. + + ```sql + SELECT * FROM ( + SELECT c.name, c.credit_limit - c.credit_total AS remaining, array_agg(i.name) OVER (PARTITION BY c.name) AS items + FROM "order".orders o + JOIN customer.customers c ON o.customer_id = c.customer_id + JOIN "order".statements s ON o.order_id = s.order_id + JOIN "order".items i ON s.item_id = i.item_id + ) AS remaining_info GROUP BY name, remaining, items; + ``` + + You should see the following output: + + ```sql + scalardb=# SELECT * FROM ( + scalardb(# SELECT c.name, c.credit_limit - c.credit_total AS remaining, array_agg(i.name) OVER (PARTITION BY c.name) AS items + scalardb(# FROM "order".orders o + scalardb(# JOIN customer.customers c ON o.customer_id = c.customer_id + scalardb(# JOIN "order".statements s ON o.order_id = s.order_id + scalardb(# JOIN "order".items i ON s.item_id = i.item_id + scalardb(# ) AS remaining_info GROUP BY name, remaining, items; + name | remaining | items + ---------------+-----------+---------------------------- + Suzuki Ichiro | 1500 | {Grape,Orange,Apple,Melon} + Yamada Hanako | 500 | {Orange,Grape,Mango} + Yamada Taro | 0 | {Orange,Melon,Apple} + (3 rows) + ``` + +1. Exit from the psql command. + + ```console + \q + ``` + +1. Exit from the OLAP client pod. + + ```console + exit + ``` + +## Step 9. Delete all resources + +After completing the ScalarDB Analytics with PostgreSQL tests on the Kubernetes cluster, remove all resources. + +1. Uninstall MySQL, PostgreSQL, and ScalarDB Analytics with PostgreSQL. + + ```console + helm uninstall mysql-scalardb postgresql-scalardb scalardb-analytics-postgresql + ``` + +1. Remove the client pods. + + ```console + kubectl delete pod oltp-client olap-client --grace-period 0 + ``` + +1. Remove the secret resource. + + ```console + kubectl delete secrets scalardb-analytics-postgresql-superuser-password + ``` + +1. Remove the working directory and sample files. + + ```console + cd ~ + ``` + + ```console + rm -rf ~/scalardb-analytics-postgresql-test/ + ``` diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls-cert-manager.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls-cert-manager.mdx new file mode 100644 index 00000000..508bed4a --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls-cert-manager.mdx @@ -0,0 +1,597 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (ScalarDB Cluster with TLS by Using cert-manager) + +This tutorial explains how to get started with ScalarDB Cluster with TLS configurations by using Helm Charts and cert-manager on a Kubernetes cluster in a test environment. Before starting, you should already have a Mac or Linux environment for testing. In addition, although this tutorial mentions using **minikube**, the steps described should work in any Kubernetes cluster. + +## Requirements + +* You need to have a license key (trial license or commercial license) for ScalarDB Cluster. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). +* You need to use ScalarDB Cluster 3.12 or later, which supports TLS. + +## What you'll create + +In this tutorial, you'll deploy the following components on a Kubernetes cluster in the following way: + +``` ++----------------------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +------------------------+ | +| +---> | Envoy | ---+ +---> | ScalarDB Cluster node | ---+ | +| [Pod] | +-------+ | | +------------------------+ | | +| | | | | | +| +-----------+ +---------+ | +-------+ | +--------------------+ | +------------------------+ | +---------------+ | +| | Client | ---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | ScalarDB Cluster node | ---+---> | PostgreSQL | | +| | (SQL CLI) | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | +------------------------+ | | (For Ledger) | | +| +-----------+ +---------+ | | +--------------------+ | | +---------------+ | +| | +-------+ | | +------------------------+ | | +| +---> | Envoy | ---+ +---> | ScalarDB Cluster node | ---+ | +| +-------+ +------------------------+ | +| | +| +----------------------------------------------------------------------------------+ +---------------------+ | +| | cert-manager (create private key and certificate for Envoy and ScalarDB Cluster) | | Issuer (Private CA) | | +| +----------------------------------------------------------------------------------+ +---------------------+ | +| | ++----------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +cert-manager automatically creates the following private key and certificate files for TLS connections. + +``` + +----------------------+ + +---> | For Scalar Envoy | + | +----------------------+ + | | tls.key | + | | tls.crt | ++-------------------------+ | +----------------------+ +| Issuer (Self-signed CA) | ---(Sign certificates)---+ ++-------------------------+ | +----------------------+ +| tls.key | +---> | For ScalarDB Cluster | +| tls.crt | +----------------------+ +| ca.crt | | tls.key | ++-------------------------+ | tls.crt | + +----------------------+ +``` + +Scalar Helm Charts automatically mount each private key and certificate file for Envoy and ScalarDB Cluster as follows to enable TLS in each connection. You'll manually mount a root CA certificate file on the client. + +``` ++-------------------------------------+ +------------------------------------------------+ +--------------------------------+ +| Client | ---(CRUD/SQL requests)---> | Envoy for ScalarDB Cluster | ---> | ScalarDB Cluster nodes | ++-------------------------------------+ +------------------------------------------------+ +--------------------------------+ +| ca.crt (to verify tls.crt of Envoy) | | tls.key | | tls.key | ++-------------------------------------+ | tls.crt | | tls.crt | + | ca.crt (to verify tls.crt of ScalarDB Cluster) | | ca.crt (to check health) | + +------------------------------------------------+ +--------------------------------+ +``` + +The following connections exist amongst the ScalarDB Cluster–related components: + +* **`Client - Envoy for ScalarDB Cluster`:** When you execute a CRUD API or SQL API function, the client accesses Envoy for ScalarDB Cluster. +* **`Envoy for ScalarDB Cluster - ScalarDB Cluster`:** Envoy works as an L7 (gRPC) load balancer in front of ScalarDB Cluster. +* **`ScalarDB Cluster node - ScalarDB Cluster node`:** A ScalarDB Cluster node accesses other ScalarDB Cluster nodes. In other words, the cluster's internal communications exist amongst all ScalarDB Cluster nodes. + +## Step 1. Start a Kubernetes cluster and install tools + +You need to prepare a Kubernetes cluster and install some tools (`kubectl`, `helm`, `cfssl`, and `cfssljson`). For more details on how to install them, see [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). + +## Step 2. Start the PostgreSQL containers + +ScalarDB Cluster must use some type of database system as a backend database. In this tutorial, you'll use PostgreSQL. + +You can deploy PostgreSQL on the Kubernetes cluster as follows: + +1. Add the Bitnami helm repository. + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Deploy PostgreSQL for ScalarDB Cluster. + + ```console + helm install postgresql-scalardb-cluster bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. Check if the PostgreSQL containers are running. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 34s + ``` + +## Step 3. Create a working directory + +You'll create some configuration files locally. Be sure to create a working directory for those files. + +1. Create a working directory. + + ```console + mkdir -p ${HOME}/scalardb-cluster-test/ + ``` + + +## Step 4. Deploy cert-manager and issuer resource + +This tutorial uses cert-manager to issue and manage your private keys and certificates. You can deploy cert-manager on the Kubernetes cluster as follows: + +1. Add the Jetstack helm repository. + + ```console + helm repo add jetstack https://charts.jetstack.io + ``` + +1. Deploy cert-manager. + + ```console + helm install cert-manager jetstack/cert-manager \ + --create-namespace \ + --set installCRDs=true \ + -n cert-manager + ``` + +1. Check if the cert-manager containers are running. + + ```console + kubectl get pod -n cert-manager + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + cert-manager-6dc66985d4-6lvtt 1/1 Running 0 26s + cert-manager-cainjector-c7d4dbdd9-xlrpn 1/1 Running 0 26s + cert-manager-webhook-847d7676c9-ckcz2 1/1 Running 0 26s + ``` + +1. Change the working directory to `${HOME}/scalardb-cluster-test/`. + + ```console + cd ${HOME}/scalardb-cluster-test/ + ``` + +1. Create a custom values file for the private CA (`private-ca-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/private-ca-custom-values.yaml + apiVersion: cert-manager.io/v1 + kind: Issuer + metadata: + name: self-signed-issuer + spec: + selfSigned: {} + --- + apiVersion: cert-manager.io/v1 + kind: Certificate + metadata: + name: self-signed-ca-cert + spec: + isCA: true + commonName: self-signed-ca + secretName: self-signed-ca-cert-secret + privateKey: + algorithm: ECDSA + size: 256 + issuerRef: + name: self-signed-issuer + kind: Issuer + group: cert-manager.io + --- + apiVersion: cert-manager.io/v1 + kind: Issuer + metadata: + name: self-signed-ca + spec: + ca: + secretName: self-signed-ca-cert-secret + EOF + ``` + +1. Deploy a self-signed CA. + + ```console + kubectl apply -f ./private-ca-custom-values.yaml + ``` + +1. Check if the issuer resources are `True`. + + ```console + kubectl get issuer + ``` + + [Command execution result] + + ```console + NAME READY AGE + self-signed-ca True 6s + self-signed-issuer True 6s + ``` + +## Step 5. Deploy ScalarDB Cluster on the Kubernetes cluster by using Helm Charts + +1. Add the Scalar Helm Charts repository. + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. Set your license key and certificate as environment variables. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). For details about the value of ``, see [How to Configure a Product License Key](https://scalardb.scalar-labs.com/docs/latest/scalar-licensing/). + + ```console + SCALAR_DB_CLUSTER_LICENSE_KEY='' + SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM='' + ``` + +1. Create a custom values file for ScalarDB Cluster (`scalardb-cluster-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/scalardb-cluster-custom-values.yaml + envoy: + + enabled: true + + tls: + downstream: + enabled: true + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - envoy.scalar.example.com + upstream: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" + + scalardbCluster: + + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium" + + scalardbClusterNodeProperties: | + ### Necessary configurations for deployment on Kuberetes + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} + + ### Storage configurations + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb-cluster.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DB_CLUSTER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DB_CLUSTER_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + + ### SQL configurations + scalar.db.sql.enabled=true + + ### Auth configurations + scalar.db.cluster.auth.enabled=true + scalar.db.cross_partition_scan.enabled=true + + ### TLS configurations + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/tls/scalardb-cluster/certs/ca.crt + scalar.db.cluster.node.tls.cert_chain_path=/tls/scalardb-cluster/certs/tls.crt + scalar.db.cluster.node.tls.private_key_path=/tls/scalardb-cluster/certs/tls.key + scalar.db.cluster.tls.override_authority=cluster.scalardb.example.com + + ### License key configurations + scalar.db.cluster.node.licensing.license_key=${env:SCALAR_DB_CLUSTER_LICENSE_KEY} + scalar.db.cluster.node.licensing.license_check_cert_pem=${env:SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - cluster.scalardb.example.com + + secretName: "scalardb-credentials-secret" + EOF + ``` + +1. Create a secret resource named `scalardb-credentials-secret` that includes credentials and license keys. + + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DB_CLUSTER_LICENSE_KEY="${SCALAR_DB_CLUSTER_LICENSE_KEY}" \ + --from-file=SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. Set the chart version of ScalarDB Cluster. + + ```console + SCALAR_DB_CLUSTER_VERSION=3.12.2 + SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. Deploy ScalarDB Cluster. + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f ${HOME}/scalardb-cluster-test/scalardb-cluster-custom-values.yaml --version ${SCALAR_DB_CLUSTER_CHART_VERSION} -n default + ``` + +1. Check if the ScalarDB Cluster pods are deployed. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 4m30s + scalardb-cluster-envoy-7cc948dfb-4rb8l 1/1 Running 0 18s + scalardb-cluster-envoy-7cc948dfb-hwt96 1/1 Running 0 18s + scalardb-cluster-envoy-7cc948dfb-rzbrx 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-445kj 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-4z54q 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-vcv96 1/1 Running 0 18s + ``` + + If the ScalarDB Cluster pods are deployed properly, the `STATUS` column for those pods will be displayed as `Running`. + +1. Check if the ScalarDB Cluster services are deployed. + + ```console + kubectl get svc -n default + ``` + + [Command execution result] + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 7h34m + postgresql-scalardb-cluster ClusterIP 10.96.92.27 5432/TCP 4m52s + postgresql-scalardb-cluster-hl ClusterIP None 5432/TCP 4m52s + scalardb-cluster-envoy ClusterIP 10.96.250.175 60053/TCP 40s + scalardb-cluster-envoy-metrics ClusterIP 10.96.40.197 9001/TCP 40s + scalardb-cluster-headless ClusterIP None 60053/TCP 40s + scalardb-cluster-metrics ClusterIP 10.96.199.135 9080/TCP 40s + ``` + + If the ScalarDB Cluster services are deployed properly, you can see private IP addresses in the `CLUSTER-IP` column. + +:::note + +The `CLUSTER-IP` values for `postgresql-scalardb-cluster-hl` and `scalardb-cluster-headless` are `None` since they have no IP addresses. + +::: + +## Step 6. Start a client container + +You'll use the CA certificate file in a client container. Therefore, you'll need to create a secret resource and mount it to the client container. + +1. Create a secret resource named `client-ca-cert`. + + ```console + kubectl create secret generic client-ca-cert --from-file=ca.crt=<(kubectl get secret self-signed-ca-cert-secret -o "jsonpath={.data['ca\.crt']}" | base64 -d) -n default + ``` + +1. Create a manifest file for a client pod (`scalardb-cluster-client-pod.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml + apiVersion: v1 + kind: Pod + metadata: + name: "scalardb-cluster-client" + spec: + containers: + - name: scalardb-cluster-client + image: eclipse-temurin:8-jre-jammy + command: ['sleep'] + args: ['inf'] + env: + - name: SCALAR_DB_CLUSTER_VERSION + value: SCALAR_DB_CLUSTER_CLIENT_POD_SCALAR_DB_CLUSTER_VERSION + volumeMounts: + - name: "client-ca-cert" + mountPath: "/certs/" + readOnly: true + volumes: + - name: "client-ca-cert" + secret: + secretName: "client-ca-cert" + restartPolicy: Never + EOF + ``` + +1. Set the ScalarDB Cluster version in the manifest file. + + ```console + sed -i s/SCALAR_DB_CLUSTER_CLIENT_POD_SCALAR_DB_CLUSTER_VERSION/${SCALAR_DB_CLUSTER_VERSION}/ ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml + ``` + +1. Deploy the client pod. + + ```console + kubectl apply -f ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml -n default + ``` + +1. Check if the client container is running. + + ```console + kubectl get pod scalardb-cluster-client -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + scalardb-cluster-client 1/1 Running 0 26s + ``` + +## Step 7. Run the ScalarDB Cluster SQL CLI in the client container + +1. Run bash in the client container. + + ```console + kubectl exec -it scalardb-cluster-client -n default -- bash + ``` + + The commands in the following steps must be run in the client container. + +1. Download the ScalarDB Cluster SQL CLI from [Releases](https://github.com/scalar-labs/scalardb/releases). + + ```console + curl -OL https://github.com/scalar-labs/scalardb/releases/download/v${SCALAR_DB_CLUSTER_VERSION}/scalardb-cluster-sql-cli-${SCALAR_DB_CLUSTER_VERSION}-all.jar + ``` + +1. Create a `database.properties` file and add configurations. + + ```console + cat << 'EOF' > /database.properties + # ScalarDB Cluster configurations + scalar.db.sql.connection_mode=cluster + scalar.db.sql.cluster_mode.contact_points=indirect:scalardb-cluster-envoy.default.svc.cluster.local + + # Auth configurations + scalar.db.cluster.auth.enabled=true + scalar.db.sql.cluster_mode.username=admin + scalar.db.sql.cluster_mode.password=admin + + # TLS configurations + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/certs/ca.crt + scalar.db.cluster.tls.override_authority=envoy.scalar.example.com + EOF + ``` + +1. Run the ScalarDB Cluster SQL CLI. + + ```console + java -jar /scalardb-cluster-sql-cli-${SCALAR_DB_CLUSTER_VERSION}-all.jar --config /database.properties + ``` + +1. Create a sample namespace named `ns`. + + ```sql + CREATE NAMESPACE ns; + ``` + +1. Create a sample table named `tbl` under the namespace `ns`. + + ```sql + CREATE TABLE ns.tbl (a INT, b INT, c INT, PRIMARY KEY(a, b)); + ``` + +1. Insert sample records. + + ```sql + INSERT INTO ns.tbl VALUES (1,2,3), (4,5,6), (7,8,9); + ``` + +1. Select the sample records that you inserted. + + ```sql + SELECT * FROM ns.tbl; + ``` + + [Command execution result] + + ```sql + 0: scalardb> SELECT * FROM ns.tbl; + +---+---+---+ + | a | b | c | + +---+---+---+ + | 7 | 8 | 9 | + | 1 | 2 | 3 | + | 4 | 5 | 6 | + +---+---+---+ + 3 rows selected (0.059 seconds) + ``` + +1. Press `Ctrl + D` to exit from ScalarDB Cluster SQL CLI. + + ```console + ^D + ``` + +1. Exit from the client container. + + ```console + exit + ``` + +## Step 8. Delete all resources + +After completing the ScalarDB Cluster tests on the Kubernetes cluster, remove all resources. + +1. Uninstall ScalarDB Cluster and PostgreSQL. + + ```console + helm uninstall -n default scalardb-cluster postgresql-scalardb-cluster + ``` + +1. Remove the self-signed CA. + + ``` + kubectl delete -f ./private-ca-custom-values.yaml + ``` + +1. Uninstall cert-manager. + + ```console + helm uninstall -n cert-manager cert-manager + ``` + +1. Remove the client container. + + ``` + kubectl delete pod scalardb-cluster-client --grace-period 0 -n default + ``` + +1. Remove the secret resources. + + ``` + kubectl delete secrets scalardb-credentials-secret self-signed-ca-cert-secret scalardb-cluster-envoy-tls-cert scalardb-cluster-tls-cert client-ca-cert + ``` + +1. Remove the namespace `cert-manager`. + + ``` + kubectl delete ns cert-manager + ``` + +1. Remove the working directory and the sample configuration files. + + ```console + cd ${HOME} + ``` + + ```console + rm -rf ${HOME}/scalardb-cluster-test/ + ``` + +## Further reading + +You can see how to get started with monitoring or logging for Scalar products in the following tutorials: + +* [Getting Started with Helm Charts (Monitoring using Prometheus Operator)](getting-started-monitoring.mdx) +* [Getting Started with Helm Charts (Logging using Loki Stack)](getting-started-logging.mdx) +* [Getting Started with Helm Charts (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls.mdx new file mode 100644 index 00000000..0383321c --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalardb-cluster-tls.mdx @@ -0,0 +1,634 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (ScalarDB Cluster with TLS) + +This tutorial explains how to get started with ScalarDB Cluster with TLS configurations by using Helm Charts on a Kubernetes cluster in a test environment. Before starting, you should already have a Mac or Linux environment for testing. In addition, although this tutorial mentions using **minikube**, the steps described should work in any Kubernetes cluster. + +## Requirements + +* You need to have a license key (trial license or commercial license) for ScalarDB Cluster. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). +* You need to use ScalarDB Cluster 3.12 or later, which supports TLS. + +## What you'll create + +In this tutorial, you'll deploy the following components on a Kubernetes cluster in the following way: + +``` ++----------------------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +------------------------+ | +| +---> | Envoy | ---+ +---> | ScalarDB Cluster node | ---+ | +| [Pod] | +-------+ | | +------------------------+ | | +| | | | | | +| +-----------+ +---------+ | +-------+ | +--------------------+ | +------------------------+ | +---------------+ | +| | Client | ---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | ScalarDB Cluster node | ---+---> | PostgreSQL | | +| | (SQL CLI) | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | +------------------------+ | | (For Ledger) | | +| +-----------+ +---------+ | | +--------------------+ | | +---------------+ | +| | +-------+ | | +------------------------+ | | +| +---> | Envoy | ---+ +---> | ScalarDB Cluster node | ---+ | +| +-------+ +------------------------+ | +| | ++----------------------------------------------------------------------------------------------------------------------------------------------------+ +``` + +You'll also create the following private key and certificate files for TLS connections. + +``` + +-------------------------------+ + +---> | For Scalar Envoy | + | +-------------------------------+ + | | envoy-key.pem | + | | envoy.pem | ++----------------------+ | +-------------------------------+ +| Self-signed CA | ---(Sign certificates)---+ ++----------------------+ | +-------------------------------+ +| ca-key.pem | +---> | For ScalarDB Cluster | +| ca.pem | +-------------------------------+ ++----------------------+ | scalardb-cluster-key.pem | + | scalardb-cluster.pem | + +-------------------------------+ +``` + +You'll set each private key and certificate file as follows to enable TLS in each connection. + +``` ++--------------------------------+ +-----------------------------------------+ +-----------------------------------------+ +| Client | ---(CRUD/SQL requests)---> | Envoy for ScalarDB Cluster | ---> | ScalarDB Cluster nodes | ++--------------------------------+ +-----------------------------------------+ +-----------------------------------------+ +| ca.pem (to verify envoy.pem) | | envoy-key.pem | | scalardb-cluster-key.pem | ++--------------------------------+ | envoy.pem | | scalardb-cluster.pem | + | ca.pem (to verify scalardb-cluster.pem) | | ca.pem (used for health check) | + +-----------------------------------------+ +-----------------------------------------+ +``` + +The following connections exist amongst the ScalarDB Cluster–related components: + +* **`Client - Envoy for ScalarDB Cluster`:** When you execute a CRUD API or SQL API function, the client accesses Envoy for ScalarDB Cluster. +* **`Envoy for ScalarDB Cluster - ScalarDB Cluster`:** Envoy works as an L7 (gRPC) load balancer in front of ScalarDB Cluster. +* **`ScalarDB Cluster node - ScalarDB Cluster node`:** A ScalarDB Cluster node accesses other ScalarDB Cluster nodes. In other words, the cluster's internal communications exist amongst all ScalarDB Cluster nodes. + +## Step 1. Start a Kubernetes cluster and install tools + +You need to prepare a Kubernetes cluster and install some tools (`kubectl`, `helm`, `cfssl`, and `cfssljson`). For more details on how to install them, see [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). + +## Step 2. Start the PostgreSQL containers + +ScalarDB Cluster must use some type of database system as a backend database. In this tutorial, you'll use PostgreSQL. + +You can deploy PostgreSQL on the Kubernetes cluster as follows: + +1. Add the Bitnami helm repository. + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Deploy PostgreSQL for ScalarDB Cluster. + + ```console + helm install postgresql-scalardb-cluster bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. Check if the PostgreSQL containers are running. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 34s + ``` + +## Step 3. Create a working directory + +You'll create some configuration files and private key and certificate files locally. Be sure to create a working directory for those files. + +1. Create a working directory. + + ```console + mkdir -p ${HOME}/scalardb-cluster-test/certs/ + ``` + +## Step 4. Create private key and certificate files + +You'll create private key and a certificate files. + +1. Change the working directory to `${HOME}/scalardb-cluster-test/certs/`. + + ```console + cd ${HOME}/scalardb-cluster-test/certs/ + ``` + +1. Create a JSON file that includes CA information. + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/certs/ca.json + { + "CN": "scalar-test-ca", + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Test CA" + } + ] + } + EOF + ``` + +1. Create the CA private key and certificate files. + + ```console + cfssl gencert -initca ca.json | cfssljson -bare ca + ``` + +1. Create a JSON file that includes CA configurations. + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/certs/ca-config.json + { + "signing": { + "default": { + "expiry": "87600h" + }, + "profiles": { + "scalar-test-ca": { + "expiry": "87600h", + "usages": [ + "signing", + "key encipherment", + "server auth" + ] + } + } + } + } + EOF + ``` + +1. Create a JSON file that includes Envoy information. + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/certs/envoy.json + { + "CN": "scalar-envoy", + "hosts": [ + "envoy.scalar.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Envoy Test" + } + ] + } + EOF + ``` + +1. Create a JSON file that includes ScalarDB Cluster information. + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/certs/scalardb-cluster.json + { + "CN": "scalardb-cluster", + "hosts": [ + "cluster.scalardb.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "ScalarDB Cluster Test" + } + ] + } + EOF + ``` + +1. Create private key and certificate files for Envoy. + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca envoy.json | cfssljson -bare envoy + ``` + +1. Create private key and certificate files for ScalarDB Cluster. + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca scalardb-cluster.json | cfssljson -bare scalardb-cluster + ``` + +1. Confirm that the private key and certificate files were created. + + ```console + ls -1 + ``` + + [Command execution result] + + ```console + ca-config.json + ca-key.pem + ca.csr + ca.json + ca.pem + envoy-key.pem + envoy.csr + envoy.json + envoy.pem + scalardb-cluster-key.pem + scalardb-cluster.csr + scalardb-cluster.json + scalardb-cluster.pem + ``` + +## Step 5. Deploy ScalarDB Cluster on the Kubernetes cluster by using Helm Charts + +1. Add the Scalar Helm Charts repository. + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. Set your license key and certificate as environment variables. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). For details about the value of ``, see [How to Configure a Product License Key](https://scalardb.scalar-labs.com/docs/latest/scalar-licensing/). + + ```console + SCALAR_DB_CLUSTER_LICENSE_KEY='' + SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM='' + ``` + +1. Create a custom values file for ScalarDB Cluster (`scalardb-cluster-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/scalardb-cluster-custom-values.yaml + envoy: + + enabled: true + + tls: + downstream: + enabled: true + certChainSecret: "envoy-tls-cert" + privateKeySecret: "envoy-tls-key" + upstream: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" + caRootCertSecret: "scalardb-cluster-tls-ca" + + scalardbCluster: + + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium" + + scalardbClusterNodeProperties: | + ### Necessary configurations for deployment on Kuberetes + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} + + ### Storage configurations + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb-cluster.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DB_CLUSTER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DB_CLUSTER_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + + ### SQL configurations + scalar.db.sql.enabled=true + + ### Auth configurations + scalar.db.cluster.auth.enabled=true + scalar.db.cross_partition_scan.enabled=true + + ### TLS configurations + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/tls/scalardb-cluster/certs/ca.crt + scalar.db.cluster.node.tls.cert_chain_path=/tls/scalardb-cluster/certs/tls.crt + scalar.db.cluster.node.tls.private_key_path=/tls/scalardb-cluster/certs/tls.key + scalar.db.cluster.tls.override_authority=cluster.scalardb.example.com + + ### License key configurations + scalar.db.cluster.node.licensing.license_key=${env:SCALAR_DB_CLUSTER_LICENSE_KEY} + scalar.db.cluster.node.licensing.license_check_cert_pem=${env:SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "cluster.scalardb.example.com" + caRootCertSecret: "scalardb-cluster-tls-ca" + certChainSecret: "scalardb-cluster-tls-cert" + privateKeySecret: "scalardb-cluster-tls-key" + + secretName: "scalardb-credentials-secret" + EOF + ``` + +1. Create a secret resource named `scalardb-credentials-secret` that includes credentials and license keys. + + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DB_CLUSTER_LICENSE_KEY="${SCALAR_DB_CLUSTER_LICENSE_KEY}" \ + --from-file=SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. Create secret resources that include the private key and certificate files for Envoy. + + ```console + kubectl create secret generic envoy-tls-cert --from-file=tls.crt=${HOME}/scalardb-cluster-test/certs/envoy.pem -n default + kubectl create secret generic envoy-tls-key --from-file=tls.key=${HOME}/scalardb-cluster-test/certs/envoy-key.pem -n default + ``` + +1. Create secret resources that include the key, certificate, and CA certificate files for ScalarDB Cluster. + + ```console + kubectl create secret generic scalardb-cluster-tls-ca --from-file=ca.crt=${HOME}/scalardb-cluster-test/certs/ca.pem -n default + kubectl create secret generic scalardb-cluster-tls-cert --from-file=tls.crt=${HOME}/scalardb-cluster-test/certs/scalardb-cluster.pem -n default + kubectl create secret generic scalardb-cluster-tls-key --from-file=tls.key=${HOME}/scalardb-cluster-test/certs/scalardb-cluster-key.pem -n default + ``` + +1. Set the chart version of ScalarDB Cluster. + + ```console + SCALAR_DB_CLUSTER_VERSION=3.12.2 + SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. Deploy ScalarDB Cluster. + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f ${HOME}/scalardb-cluster-test/scalardb-cluster-custom-values.yaml --version ${SCALAR_DB_CLUSTER_CHART_VERSION} -n default + ``` + +1. Check if the ScalarDB Cluster pods are deployed. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 4m30s + scalardb-cluster-envoy-7cc948dfb-4rb8l 1/1 Running 0 18s + scalardb-cluster-envoy-7cc948dfb-hwt96 1/1 Running 0 18s + scalardb-cluster-envoy-7cc948dfb-rzbrx 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-445kj 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-4z54q 1/1 Running 0 18s + scalardb-cluster-node-7c6959c79d-vcv96 1/1 Running 0 18s + ``` + If the ScalarDB Cluster pods are deployed properly, the `STATUS` column for those pods will be displayed as `Running`. + +1. Check if the ScalarDB Cluster services are deployed. + + ```console + kubectl get svc -n default + ``` + + [Command execution result] + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 7h34m + postgresql-scalardb-cluster ClusterIP 10.96.92.27 5432/TCP 4m52s + postgresql-scalardb-cluster-hl ClusterIP None 5432/TCP 4m52s + scalardb-cluster-envoy ClusterIP 10.96.250.175 60053/TCP 40s + scalardb-cluster-envoy-metrics ClusterIP 10.96.40.197 9001/TCP 40s + scalardb-cluster-headless ClusterIP None 60053/TCP 40s + scalardb-cluster-metrics ClusterIP 10.96.199.135 9080/TCP 40s + ``` + + If the ScalarDB Cluster services are deployed properly, you can see private IP addresses in the `CLUSTER-IP` column. + +:::note + +The `CLUSTER-IP` values for `postgresql-scalardb-cluster-hl` and `scalardb-cluster-headless` are `None` since they have no IP addresses. + +::: + +## Step 6. Start a client container + +You'll use the CA certificate file in a client container. Therefore, you'll need to create a secret resource and mount it to the client container. + +1. Create a secret resource named `client-ca-cert`. + + ```console + kubectl create secret generic client-ca-cert --from-file=ca.crt=${HOME}/scalardb-cluster-test/certs/ca.pem -n default + ``` + +1. Create a manifest file for a client pod (`scalardb-cluster-client-pod.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml + apiVersion: v1 + kind: Pod + metadata: + name: "scalardb-cluster-client" + spec: + containers: + - name: scalardb-cluster-client + image: eclipse-temurin:8-jre-jammy + command: ['sleep'] + args: ['inf'] + env: + - name: SCALAR_DB_CLUSTER_VERSION + value: SCALAR_DB_CLUSTER_CLIENT_POD_SCALAR_DB_CLUSTER_VERSION + volumeMounts: + - name: "client-ca-cert" + mountPath: "/certs/" + readOnly: true + volumes: + - name: "client-ca-cert" + secret: + secretName: "client-ca-cert" + restartPolicy: Never + EOF + ``` + +1. Set the ScalarDB Cluster version in the manifest file. + + ```console + sed -i s/SCALAR_DB_CLUSTER_CLIENT_POD_SCALAR_DB_CLUSTER_VERSION/${SCALAR_DB_CLUSTER_VERSION}/ ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml + ``` + +1. Deploy the client pod. + + ```console + kubectl apply -f ${HOME}/scalardb-cluster-test/scalardb-cluster-client-pod.yaml -n default + ``` + +1. Check if the client container is running. + + ```console + kubectl get pod scalardb-cluster-client -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + scalardb-cluster-client 1/1 Running 0 26s + ``` + +## Step 7. Run the ScalarDB Cluster SQL CLI in the client container + +1. Run bash in the client container. + + ```console + kubectl exec -it scalardb-cluster-client -n default -- bash + ``` + The commands in the following steps must be run in the client container. + +1. Download the ScalarDB Cluster SQL CLI from [Releases](https://github.com/scalar-labs/scalardb/releases). + + ```console + curl -OL https://github.com/scalar-labs/scalardb/releases/download/v${SCALAR_DB_CLUSTER_VERSION}/scalardb-cluster-sql-cli-${SCALAR_DB_CLUSTER_VERSION}-all.jar + ``` + +1. Create a `database.properties` file and add configurations. + + ```console + cat << 'EOF' > /database.properties + # ScalarDB Cluster configurations + scalar.db.sql.connection_mode=cluster + scalar.db.sql.cluster_mode.contact_points=indirect:scalardb-cluster-envoy.default.svc.cluster.local + + # Auth configurations + scalar.db.cluster.auth.enabled=true + scalar.db.sql.cluster_mode.username=admin + scalar.db.sql.cluster_mode.password=admin + + # TLS configurations + scalar.db.cluster.tls.enabled=true + scalar.db.cluster.tls.ca_root_cert_path=/certs/ca.crt + scalar.db.cluster.tls.override_authority=envoy.scalar.example.com + EOF + ``` + +1. Run the ScalarDB Cluster SQL CLI. + + ```console + java -jar /scalardb-cluster-sql-cli-${SCALAR_DB_CLUSTER_VERSION}-all.jar --config /database.properties + ``` + +1. Create a sample namespace named `ns`. + + ```sql + CREATE NAMESPACE ns; + ``` + +1. Create a sample table named `tbl` under the namespace `ns`. + + ```sql + CREATE TABLE ns.tbl (a INT, b INT, c INT, PRIMARY KEY(a, b)); + ``` + +1. Insert sample records. + + ```sql + INSERT INTO ns.tbl VALUES (1,2,3), (4,5,6), (7,8,9); + ``` + +1. Select the sample records that you inserted. + + ```sql + SELECT * FROM ns.tbl; + ``` + + [Command execution result] + + ```sql + 0: scalardb> SELECT * FROM ns.tbl; + +---+---+---+ + | a | b | c | + +---+---+---+ + | 7 | 8 | 9 | + | 1 | 2 | 3 | + | 4 | 5 | 6 | + +---+---+---+ + 3 rows selected (0.059 seconds) + ``` + +1. Press `Ctrl + D` to exit from ScalarDB Cluster SQL CLI. + + ```console + ^D + ``` + +1. Exit from the client container. + + ```console + exit + ``` + +## Step 8. Delete all resources + +After completing the ScalarDB Cluster tests on the Kubernetes cluster, remove all resources. + +1. Uninstall ScalarDB Cluster and PostgreSQL. + + ```console + helm uninstall -n default scalardb-cluster postgresql-scalardb-cluster + ``` + +1. Remove the client container. + + ``` + kubectl delete pod scalardb-cluster-client --grace-period 0 -n default + ``` + +1. Remove the secret resources. + + ``` + kubectl delete secrets scalardb-credentials-secret scalardb-cluster-tls-key scalardb-cluster-tls-cert scalardb-cluster-tls-ca envoy-tls-key envoy-tls-cert client-ca-cert + ``` + +1. Remove the working directory and sample files (configuration file, private key, and certificate). + + ```console + cd ${HOME} + ``` + + ```console + rm -rf ${HOME}/scalardb-cluster-test/ + ``` + +## Further reading + +You can see how to get started with monitoring or logging for Scalar products in the following tutorials: + +* [Getting Started with Helm Charts (Monitoring using Prometheus Operator)](getting-started-monitoring.mdx) +* [Getting Started with Helm Charts (Logging using Loki Stack)](getting-started-logging.mdx) +* [Getting Started with Helm Charts (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalardb.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalardb.mdx new file mode 100644 index 00000000..858c9f41 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalardb.mdx @@ -0,0 +1,383 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsEnglish +--- + +# [Deprecated] Getting Started with Helm Charts (ScalarDB Server) + +:::note + +ScalarDB Server is now deprecated. Please use [ScalarDB Cluster](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart) instead. + +::: + +This document explains how to get started with ScalarDB Server using Helm Chart on a Kubernetes cluster as a test environment. Here, we assume that you already have a Mac or Linux environment for testing. We use **Minikube** in this document, but the steps we will show should work in any Kubernetes cluster. + +## Requirement + +* You need to subscribe to ScalarDB in the [AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-rzbuhxgvqf4d2) or [Azure Marketplace](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) to get container images (`scalardb-server` and `scalardb-envoy`). Please refer to the following documents for more details. + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +## What we create + +We will deploy the following components on a Kubernetes cluster as follows. + +``` ++--------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| | +| [Pod] [Pod] [Pod] [Pod] | +| | +| +-------+ +-----------------+ | +| +---> | Envoy | ---+ +---> | ScalarDB Server | ---+ | +| | +-------+ | | +-----------------+ | | +| | | | | | +| +--------+ +---------+ | +-------+ | +-------------------+ | +-----------------+ | +------------+ | +| | Client | ---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | ScalarDB Server | ---+---> | PostgreSQL | | +| +--------+ | (Envoy) | | +-------+ | | (ScalarDB Server) | | +-----------------+ | +------------+ | +| +---------+ | | +-------------------+ | | | +| | +-------+ | | +-----------------+ | | +| +---> | Envoy | ---+ +---> | ScalarDB Server | ---+ | +| +-------+ +-----------------+ | +| | ++--------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## Step 1. Start a Kubernetes cluster + +First, you need to prepare a Kubernetes cluster. If you use a **minikube** environment, please refer to the [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). If you have already started a Kubernetes cluster, you can skip this step. + +## Step 2. Start a PostgreSQL container + +ScalarDB uses some kind of database system as a backend database. In this document, we use PostgreSQL. + +You can deploy PostgreSQL on the Kubernetes cluster as follows. + +1. Add the Bitnami helm repository. + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Deploy PostgreSQL. + ```console + helm install postgresql-scalardb bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. Check if the PostgreSQL container is running. + ```console + kubectl get pod + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-0 1/1 Running 0 2m42s + ``` + +## Step 3. Deploy ScalarDB Server on the Kubernetes cluster using Helm Charts + +1. Add the Scalar helm repository. + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. Create a secret resource to pull the ScalarDB container images from AWS/Azure Marketplace. + * AWS Marketplace + ```console + kubectl create secret docker-registry reg-ecr-mp-secrets \ + --docker-server=709825985650.dkr.ecr.us-east-1.amazonaws.com \ + --docker-username=AWS \ + --docker-password=$(aws ecr get-login-password --region us-east-1) + ``` + * Azure Marketplace + ```console + kubectl create secret docker-registry reg-acr-secrets \ + --docker-server= \ + --docker-username= \ + --docker-password= + ``` + + Please refer to the following documents for more details. + + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +1. Create a custom values file for ScalarDB Server (scalardb-custom-values.yaml). + * AWS Marketplace + + ```console + cat << 'EOF' > scalardb-custom-values.yaml + envoy: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + + scalardb: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-server" + tag: "3.7.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + databaseProperties: | + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DB_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_POSTGRES_PASSWORD "" }} + secretName: "scalardb-credentials-secret" + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > scalardb-custom-values.yaml + envoy: + image: + repository: "/scalarinc/scalardb-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-acr-secrets" + + scalardb: + image: + repository: "/scalarinc/scalardb-server" + tag: "3.7.0" + imagePullSecrets: + - name: "reg-acr-secrets" + databaseProperties: | + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DB_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_POSTGRES_PASSWORD "" }} + secretName: "scalardb-credentials-secret" + EOF + ``` + +1. Create a Secret resource that includes a username and password for PostgreSQL. + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DB_POSTGRES_PASSWORD=postgres + ``` + +1. Deploy ScalarDB Server. + ```console + helm install scalardb scalar-labs/scalardb -f ./scalardb-custom-values.yaml + ``` + +1. Check if the ScalarDB Server pods are deployed. + ```console + kubectl get pod + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-0 1/1 Running 0 9m48s + scalardb-765598848b-75csp 1/1 Running 0 6s + scalardb-765598848b-w864f 1/1 Running 0 6s + scalardb-765598848b-x8rqj 1/1 Running 0 6s + scalardb-envoy-84c475f77b-kpz2p 1/1 Running 0 6s + scalardb-envoy-84c475f77b-n74tk 1/1 Running 0 6s + scalardb-envoy-84c475f77b-zbrwz 1/1 Running 0 6s + ``` + If the ScalarDB Server Pods are deployed properly, you can see the STATUS are **Running**. + +1. Check if the ScalarDB Server services are deployed. + ```console + kubectl get svc + ``` + [Command execution result] + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-scalardb ClusterIP 10.109.118.122 5432/TCP 10m + postgresql-scalardb-hl ClusterIP None 5432/TCP 10m + scalardb-envoy ClusterIP 10.110.110.250 60051/TCP 41s + scalardb-envoy-metrics ClusterIP 10.107.98.227 9001/TCP 41s + scalardb-headless ClusterIP None 60051/TCP 41s + scalardb-metrics ClusterIP 10.108.188.10 8080/TCP 41s + ``` + If the ScalarDB Server services are deployed properly, you can see private IP addresses in the CLUSTER-IP column. (Note: `scalardb-headless` has no CLUSTER-IP.) + +## Step 4. Start a Client container + +1. Start a Client container on the Kubernetes cluster. + ```console + kubectl run scalardb-client --image eclipse-temurin:8-jdk --command sleep inf + ``` + +1. Check if the Client container is running. + ```console + kubectl get pod scalardb-client + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + scalardb-client 1/1 Running 0 23s + ``` + +## Step 5. Run ScalarDB sample applications in the Client container + +The following explains the minimum steps. If you want to know more details about ScalarDB, please refer to the [Getting Started with ScalarDB](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb). + +1. Run bash in the Client container. + ```console + kubectl exec -it scalardb-client -- bash + ``` + After this step, run each command in the Client container. + +1. Install the git and curl commands in the Client container. + ```console + apt update && apt install -y git curl + ``` + +1. Clone ScalarDB git repository. + ```console + git clone https://github.com/scalar-labs/scalardb.git + ``` + +1. Change the directory to `scalardb/`. + ```console + cd scalardb/ + ``` + ```console + pwd + ``` + [Command execution result] + ```console + /scalardb + ``` + +1. Change branch to arbitrary version. + ```console + git checkout -b v3.7.0 refs/tags/v3.7.0 + ``` + ```console + git branch + ``` + [Command execution result] + + ```console + master + * v3.7.0 + ``` + + If you want to use another version, please specify the version (tag) you want to use. + +1. Change the directory to `docs/getting-started/`. + ```console + cd docs/getting-started/ + ``` + ```console + pwd + ``` + [Command execution result] + ```console + /scalardb/docs/getting-started + ``` + +1. Download Schema Loader from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases). + ```console + curl -OL https://github.com/scalar-labs/scalardb/releases/download/v3.7.0/scalardb-schema-loader-3.7.0.jar + ``` + You need to use the same version of ScalarDB and Schema Loader. + +1. Create a configuration file (scalardb.properties) to access ScalarDB Server on the Kubernetes cluster. + ```console + cat << 'EOF' > scalardb.properties + scalar.db.contact_points=scalardb-envoy.default.svc.cluster.local + scalar.db.contact_port=60051 + scalar.db.storage=grpc + scalar.db.transaction_manager=grpc + EOF + ``` + +1. Create a JSON file (emoney-transaction.json) that defines DB Schema for the sample applications. + ```console + cat << 'EOF' > emoney-transaction.json + { + "emoney.account": { + "transaction": true, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } + } + EOF + ``` + +1. Run Schema Loader (Create sample TABLE). + ```console + java -jar ./scalardb-schema-loader-3.7.0.jar --config ./scalardb.properties -f emoney-transaction.json --coordinator + ``` + +1. Run the sample applications. + * Charge `1000` to `user1`: + ```console + ./gradlew run --args="-action charge -amount 1000 -to user1" + ``` + * Charge `0` to `merchant1` (Just create an account for `merchant1`): + ```console + ./gradlew run --args="-action charge -amount 0 -to merchant1" + ``` + * Pay `100` from `user1` to `merchant1`: + ```console + ./gradlew run --args="-action pay -amount 100 -from user1 -to merchant1" + ``` + * Get the balance of `user1`: + ```console + ./gradlew run --args="-action getBalance -id user1" + ``` + * Get the balance of `merchant1`: + ```console + ./gradlew run --args="-action getBalance -id merchant1" + ``` + +1. (Optional) You can see the inserted and modified (INSERT/UPDATE) data through the sample applications using the following command. (This command needs to run on your localhost, not on the Client container.) + ```console + kubectl exec -it postgresql-scalardb-0 -- bash -c 'export PGPASSWORD=postgres && psql -U postgres -d postgres -c "SELECT * FROM emoney.account"' + ``` + [Command execution result] + ```sql + id | balance | tx_id | tx_state | tx_version | tx_prepared_at | tx_committed_at | before_tx_id | before_tx_state | before_tx_version | before_tx_prepared_at | before_tx_committed_at | before_balance + -----------+---------+--------------------------------------+----------+------------+----------------+-----------------+--------------------------------------+-----------------+-------------------+-----------------------+------------------------+---------------- + merchant1 | 100 | 65a90225-0846-4e97-b729-151f76f6ca2f | 3 | 2 | 1667361909634 |1667361909679 | 3633df99-a8ed-4301-a8b9-db1344807d7b | 3 | 1 | 1667361902466 | 1667361902485 | 0 + user1 | 900 | 65a90225-0846-4e97-b729-151f76f6ca2f | 3 | 2 | 1667361909634 |1667361909679 | 5520cba4-625a-4886-b81f-6089bf846d18 | 3 | 1 | 1667361897283 | 1667361897317 | 1000 + (2 rows) + ``` + * Note: + * Usually, you need to access data (records) through ScalarDB. The above command is used to explain and confirm the working of the sample applications. + +## Step 6. Delete all resources + +After completing the ScalarDB Server tests on the Kubernetes cluster, remove all resources. + +1. Uninstall ScalarDB Server and PostgreSQL. + ```console + helm uninstall scalardb postgresql-scalardb + ``` + +1. Remove the Client container. + ``` + kubectl delete pod scalardb-client --force --grace-period 0 + ``` + +## Further reading + +You can see how to get started with monitoring or logging for Scalar products in the following documents. + +* [Getting Started with Helm Charts (Monitoring using Prometheus Operator)](getting-started-monitoring.mdx) +* [Getting Started with Helm Charts (Logging using Loki Stack)](getting-started-logging.mdx) +* [Getting Started with Helm Charts (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls-cert-manager.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls-cert-manager.mdx new file mode 100644 index 00000000..5d940a43 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls-cert-manager.mdx @@ -0,0 +1,951 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (ScalarDL Ledger and Auditor with TLS by Using cert-manager / Auditor Mode) + +This tutorial explains how to get started with ScalarDL Ledger and ScalarDL Auditor with TLS configurations by using Helm Charts and cert-manager on a Kubernetes cluster as a test environment. Before starting, you should already have a Mac or Linux environment for testing. In addition, although this tutorial mentions using **minikube**, the steps described should work in any Kubernetes cluster. + +## Requirements + +* You need to have a license key (trial license or commercial license) for ScalarDL. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). +* You need to use ScalarDL 3.9 or later, which supports TLS. + +:::note + +To make Byzantine-fault detection with auditing work properly, ScalarDL Ledger and ScalarDL Auditor should be deployed and managed in different administrative domains. However, in this tutorial, we will deploy ScalarDL Ledger and ScalarDL Auditor in the same Kubernetes cluster to make the test easier. + +::: + +## What you'll create + +In this tutorial, you'll deploy the following components on a Kubernetes cluster in the following way: + +``` ++-----------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +---------+ | +| +---> | Envoy | ---+ +---> | Ledger | ---+ | +| | +-------+ | | +---------+ | | +| | | | | | +| +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Ledger | ---+---> | PostgreSQL | | +| | | (Envoy) | | +-------+ | | (Ledger) | | +---------+ | | (For Ledger) | | +| | +---------+ | | +-----------+ | | +---------------+ | +| [Pod] | | +-------+ | | +---------+ | | +| | +---> | Envoy | ---+ +---> | Ledger | ---+ | +| +--------+ | +-------+ +---------+ | +| | Client | ---+ | +| +--------+ | +-------+ +---------+ | +| | +---> | Envoy | ---+ +---> | Auditor | ---+ | +| | | +-------+ | | +---------+ | | +| | | | | | | +| | +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Auditor | ---+---> | PostgreSQL | | +| | (Envoy) | | +-------+ | | (Auditor) | | +---------+ | | (For Auditor) | | +| +---------+ | | +-----------+ | | +---------------+ | +| | +-------+ | | +---------+ | | +| +---> | Envoy | ---+ +---> | Auditor | ---+ | +| +-------+ +---------+ | +| | +| +--------------------------------------------------------------------------+ +---------------------+ | +| | cert-manager (create private key and certificate for Envoy and ScalarDL) | | Issuer (Private CA) | | +| +--------------------------------------------------------------------------+ +---------------------+ | +| | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +cert-manager automatically creates the following private key and certificate files for TLS connections. + +``` + +----------------------+ + +---> | For Scalar Envoy | + | +----------------------+ + | | tls.key | + | | tls.crt | + | +----------------------+ + | ++-------------------------+ | +----------------------+ +| Issuer (Self-signed CA) | ---(Sign certificates)---+---> | For ScalarDL Ledger | ++-------------------------+ | +----------------------+ +| tls.key | | | tls.key | +| tls.crt | | | tls.crt | +| ca.crt | | +----------------------+ ++-------------------------+ | + | +----------------------+ + +---> | For ScalarDL Auditor | + +----------------------+ + | tls.key | + | tls.crt | + +----------------------+ +``` + +Scalar Helm Charts automatically mount each private key and certificate file for Envoy and ScalarDL as follows to enable TLS in each connection. You'll manually mount a root CA certificate file on the client. + +``` + +------------------------------------------------+ +--------------------------------------+ + +-------(Normal request)-----> | Envoy for ScalarDL Ledger | ---> | ScalarDL Ledger | + | +------------------------------------------------+ +--------------------------------------+ + | +---(Recovery request)---> | tls.key | ---> | tls.key | + | | | tls.crt | | tls.crt | + | | | ca.crt (to verify tls.crt of ScalarDL Ledger) | | ca.crt (to check health) | + | | +------------------------------------------------+ +--------------------------------------+ ++---------------------------------------+ | | +| Client | ---+ | ++---------------------------------------+ | +------------------------------------------------------------------------------------------------------------------------------+ +| ca.crt (to verify tls.crt of Envoy) | | | ++---------------------------------------+ | | + | +------------------------------------------------+ +--------------------------------------+ | + +-------(Normal request)-----> | Envoy for ScalarDL Auditor | ---> | ScalarDL Auditor | ---+ + +------------------------------------------------+ +--------------------------------------+ + | tls.key | | tls.key | + | tls.crt | | tls.crt | + | ca.crt (to verify tls.crt of ScalarDL Auditor) | | ca.crt (to check health) | + +------------------------------------------------+ | ca.crt (to verify tls.crt of Envoy) | + +--------------------------------------+ +``` + +The following connections exist amongst the ScalarDL-related components: + +* **`Client - Envoy for ScalarDL Ledger`:** When you execute a ScalarDL API function, the client accesses Envoy for ScalarDL Ledger. +* **`Client - Envoy for ScalarDL Auditor`:** When you execute a ScalarDL API function, the client accesses Envoy for ScalarDL Auditor. +* **`Envoy for ScalarDL Ledger - ScalarDL Ledger`:** Envoy works as an L7 (gRPC) load balancer in front of ScalarDL Ledger. +* **`Envoy for ScalarDL Auditor - ScalarDL Auditor`:** Envoy works as an L7 (gRPC) load balancer in front of ScalarDL Auditor. +* **`ScalarDL Auditor - Envoy for ScalarDL Ledger (ScalarDL Ledger)`:** When ScalarDL needs to run the recovery process to keep data consistent, ScalarDL Auditor runs the request against ScalarDL Ledger via Envoy. + +## Step 1. Start a Kubernetes cluster and install tools + +You need to prepare a Kubernetes cluster and install some tools (`kubectl`, `helm`, `cfssl`, and `cfssljson`). For more details on how to install them, see [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). + +## Step 2. Start the PostgreSQL containers + +ScalarDL Ledger and ScalarDL Auditor must use some type of database system as a backend database. In this tutorial, you'll use PostgreSQL. + +You can deploy PostgreSQL on the Kubernetes cluster as follows: + +1. Add the Bitnami helm repository. + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Deploy PostgreSQL for Ledger. + + ```console + helm install postgresql-ledger bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. Deploy PostgreSQL for Auditor. + + ```console + helm install postgresql-auditor bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. Check if the PostgreSQL containers are running. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 11s + postgresql-ledger-0 1/1 Running 0 16s + ``` + +## Step 3. Create a working directory + +You'll create some configuration files and private key and certificate files locally. Be sure to create a working directory for those files. + +1. Create a working directory. + + ```console + mkdir -p ${HOME}/scalardl-test/ + ``` + +## Step 4. Deploy cert-manager and issuer resource + +This tutorial uses cert-manager to issue and manage private keys and certificates. You can deploy cert-manager on the Kubernetes cluster as follows: + +1. Add the Jetstack helm repository. + + ```console + helm repo add jetstack https://charts.jetstack.io + ``` + +1. Deploy cert-manager. + + ```console + helm install cert-manager jetstack/cert-manager \ + --create-namespace \ + --set installCRDs=true \ + -n cert-manager + ``` + +1. Check if the cert-manager containers are running. + + ```console + kubectl get pod -n cert-manager + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + cert-manager-6dc66985d4-6lvtt 1/1 Running 0 26s + cert-manager-cainjector-c7d4dbdd9-xlrpn 1/1 Running 0 26s + cert-manager-webhook-847d7676c9-ckcz2 1/1 Running 0 26s + ``` + +1. Change the working directory to `${HOME}/scalardl-test/`. + + ```console + cd ${HOME}/scalardl-test/ + ``` + +1. Create a custom values file for private CA (`private-ca-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/private-ca-custom-values.yaml + apiVersion: cert-manager.io/v1 + kind: Issuer + metadata: + name: self-signed-issuer + spec: + selfSigned: {} + --- + apiVersion: cert-manager.io/v1 + kind: Certificate + metadata: + name: self-signed-ca-cert + spec: + isCA: true + commonName: self-signed-ca + secretName: self-signed-ca-cert-secret + privateKey: + algorithm: ECDSA + size: 256 + issuerRef: + name: self-signed-issuer + kind: Issuer + group: cert-manager.io + --- + apiVersion: cert-manager.io/v1 + kind: Issuer + metadata: + name: self-signed-ca + spec: + ca: + secretName: self-signed-ca-cert-secret + EOF + ``` + +1. Deploy self-signed CA. + + ```console + kubectl apply -f ./private-ca-custom-values.yaml + ``` + +1. Check if the issuer resources are `True`. + + ```console + kubectl get issuer + ``` + + [Command execution result] + + ```console + NAME READY AGE + self-signed-ca True 6s + self-signed-issuer True 6s + ``` + +## Step 5. Create database schemas for ScalarDL Ledger and ScalarDL Auditor by using Helm Charts + +You'll deploy two ScalarDL Schema Loader pods on the Kubernetes cluster by using Helm Charts. The ScalarDL Schema Loader will create the database schemas for ScalarDL Ledger and Auditor in PostgreSQL. + +1. Add the Scalar Helm Charts repository. + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. Create a custom values file for ScalarDL Schema Loader for Ledger (`schema-loader-ledger-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_LEDGER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_LEDGER_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + secretName: "schema-ledger-credentials-secret" + EOF + ``` + +1. Create a custom values file for ScalarDL Schema Loader for Auditor (`schema-loader-auditor-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/schema-loader-auditor-custom-values.yaml + schemaLoading: + schemaType: "auditor" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_AUDITOR_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_AUDITOR_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + secretName: "schema-auditor-credentials-secret" + EOF + ``` + +1. Create a secret resource named `schema-ledger-credentials-secret` that includes a username and password for PostgreSQL for ScalarDL Ledger. + + ```console + kubectl create secret generic schema-ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres \ + -n default + ``` + +1. Create a secret resource named `schema-auditor-credentials-secret` that includes a username and password for PostgreSQL for ScalarDL Auditor. + + ```console + kubectl create secret generic schema-auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres \ + -n default + ``` + +1. Set the chart version of ScalarDL Schema Loader. + + ```console + SCALAR_DL_VERSION=3.9.1 + SCALAR_DL_SCHEMA_LOADER_CHART_VERSION=$(helm search repo scalar-labs/schema-loading -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. Deploy ScalarDL Schema Loader for ScalarDL Ledger. + + ```console + helm install schema-loader-ledger scalar-labs/schema-loading -f ${HOME}/scalardl-test/schema-loader-ledger-custom-values.yaml --version ${SCALAR_DL_SCHEMA_LOADER_CHART_VERSION} -n default + ``` + +1. Deploy ScalarDL Schema Loader for ScalarDL Auditor. + + ```console + helm install schema-loader-auditor scalar-labs/schema-loading -f ${HOME}/scalardl-test/schema-loader-auditor-custom-values.yaml --version ${SCALAR_DL_SCHEMA_LOADER_CHART_VERSION} -n default + ``` + +1. Check if the ScalarDL Schema Loader pods are deployed with the status `Completed`. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 2m56s + postgresql-ledger-0 1/1 Running 0 3m1s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 6s + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 10s + ``` + + If the status of the ScalarDL Schema Loader pods are **ContainerCreating** or **Running**, wait for the `STATUS` column for those pods to show as `Completed`. + +## Step 6. Deploy ScalarDL Ledger and ScalarDL Auditor on the Kubernetes cluster by using Helm Charts + +1. Set your license key and certificate as environment variables. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). For details about the value of `` and ``, see [How to Configure a Product License Key](https://scalardl.scalar-labs.com/docs/latest/scalar-licensing/). + + ```console + SCALAR_DL_LEDGER_LICENSE_KEY='' + SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM='' + SCALAR_DL_AUDITOR_LICENSE_KEY='' + SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM='' + ``` + +1. Create a custom values file for ScalarDL Ledger (`scalardl-ledger-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + + tls: + downstream: + enabled: true + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - envoy.scalar.example.com + upstream: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" + + ledger: + + image: + repository: "ghcr.io/scalar-labs/scalardl-ledger-byol" + + ledgerProperties: | + ### Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_LEDGER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_LEDGER_POSTGRES_PASSWORD} + + ### Ledger configurations + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.authentication.method=hmac + scalar.dl.ledger.authentication.hmac.cipher_key=${env:SCALAR_DL_LEDGER_HMAC_CIPHER_KEY} + scalar.dl.ledger.servers.authentication.hmac.secret_key=${env:SCALAR_DL_LEDGER_HMAC_SECRET_KEY} + + ### TLS configurations + scalar.dl.ledger.server.tls.enabled=true + scalar.dl.ledger.server.tls.cert_chain_path=/tls/scalardl-ledger/certs/tls.crt + scalar.dl.ledger.server.tls.private_key_path=/tls/scalardl-ledger/certs/tls.key + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DL_LEDGER_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - ledger.scalardl.example.com + + secretName: "ledger-credentials-secret" + EOF + ``` + +1. Create a custom values file for ScalarDL Auditor (`scalardl-auditor-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-auditor-custom-values.yaml + envoy: + + tls: + downstream: + enabled: true + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - envoy.scalar.example.com + upstream: + enabled: true + overrideAuthority: "auditor.scalardl.example.com" + + + auditor: + + image: + repository: "ghcr.io/scalar-labs/scalardl-auditor-byol" + + auditorProperties: | + ### Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_AUDITOR_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_AUDITOR_POSTGRES_PASSWORD} + + ### Auditor configurations + scalar.dl.auditor.ledger.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.auditor.authentication.method=hmac + scalar.dl.auditor.authentication.hmac.cipher_key=${env:SCALAR_DL_AUDITOR_HMAC_CIPHER_KEY} + scalar.dl.auditor.servers.authentication.hmac.secret_key=${env:SCALAR_DL_AUDITOR_HMAC_SECRET_KEY} + + ### TLS configurations + scalar.dl.auditor.server.tls.enabled=true + scalar.dl.auditor.server.tls.cert_chain_path=/tls/scalardl-auditor/certs/tls.crt + scalar.dl.auditor.server.tls.private_key_path=/tls/scalardl-auditor/certs/tls.key + scalar.dl.auditor.tls.enabled=true + scalar.dl.auditor.tls.ca_root_cert_path=/tls/scalardl-ledger/certs/ca.crt + scalar.dl.auditor.tls.override_authority=envoy.scalar.example.com + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DL_AUDITOR_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "auditor.scalardl.example.com" + certManager: + enabled: true + issuerRef: + name: self-signed-ca + dnsNames: + - auditor.scalardl.example.com + + secretName: "auditor-credentials-secret" + EOF + ``` + +1. Create a secret resource named `ledger-credentials-secret` that includes credentials and a license key. + + ```console + kubectl create secret generic ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DL_LEDGER_HMAC_CIPHER_KEY=ledger-hmac-cipher-key \ + --from-literal=SCALAR_DL_LEDGER_HMAC_SECRET_KEY=scalardl-hmac-secret-key \ + --from-literal=SCALAR_DL_LEDGER_LICENSE_KEY="${SCALAR_DL_LEDGER_LICENSE_KEY}" \ + --from-file=SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. Create a secret resource named `auditor-credentials-secret` that includes credentials and a license key. + + ```console + kubectl create secret generic auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DL_AUDITOR_HMAC_CIPHER_KEY=auditor-hmac-cipher-key \ + --from-literal=SCALAR_DL_AUDITOR_HMAC_SECRET_KEY=scalardl-hmac-secret-key \ + --from-literal=SCALAR_DL_AUDITOR_LICENSE_KEY="${SCALAR_DL_AUDITOR_LICENSE_KEY}" \ + --from-file=SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. Create a secret resource named `auditor-keys` to disable the `digital-signature` authentication method. In this tutorial, you'll use the `hmac` authentication method instead of `digital-signature`. + + ```console + kubectl create secret generic auditor-keys \ + --from-literal=tls.key=dummy-data-to-disable-digital-signature-method \ + --from-literal=certificate=dummy-data-to-disable-digital-signature-method \ + -n default + ``` + + Note: If you use `hmac` as an authentication method, you have to create a dummy secret `auditor-key` to disable `digital-signature` on the Helm Chart side. + +1. Set the chart version of ScalarDL Ledger and ScalarDL Auditor. + + ```console + SCALAR_DL_LEDGER_CHART_VERSION=$(helm search repo scalar-labs/scalardl -l | grep -v -e "scalar-labs/scalardl-audit" | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + SCALAR_DL_AUDITOR_CHART_VERSION=$(helm search repo scalar-labs/scalardl-audit -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. Deploy ScalarDL Ledger. + + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ${HOME}/scalardl-test/scalardl-ledger-custom-values.yaml --version ${SCALAR_DL_LEDGER_CHART_VERSION} -n default + ``` + +1. Deploy ScalarDL Auditor. + + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ${HOME}/scalardl-test/scalardl-auditor-custom-values.yaml --version ${SCALAR_DL_AUDITOR_CHART_VERSION} -n default + ``` + +1. Check if the ScalarDL Ledger and ScalarDL Auditor pods are deployed. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 14m + postgresql-ledger-0 1/1 Running 0 14m + scalardl-auditor-auditor-5b885ff4c8-fwkpf 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-g69cb 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-nsmnq 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-5mn6v 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-fpq8j 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-lsz2t 1/1 Running 0 18s + scalardl-ledger-envoy-547bbf7546-n7p5x 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-p8nwp 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-pskpb 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-5zsbj 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-vnmrw 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-wpjvs 1/1 Running 0 26s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 11m + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 11m + ``` + + If the ScalarDL Ledger and ScalarDL Auditor pods are deployed properly, the `STATUS` column for those pods will be displayed as `Running`. + +1. Check if the ScalarDL Ledger and ScalarDL Auditor services are deployed. + + ```console + kubectl get svc -n default + ``` + + [Command execution result] + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-auditor ClusterIP 10.107.9.78 5432/TCP 15m + postgresql-auditor-hl ClusterIP None 5432/TCP 15m + postgresql-ledger ClusterIP 10.108.241.181 5432/TCP 15m + postgresql-ledger-hl ClusterIP None 5432/TCP 15m + scalardl-auditor-envoy ClusterIP 10.100.61.202 40051/TCP,40052/TCP 55s + scalardl-auditor-envoy-metrics ClusterIP 10.99.6.227 9001/TCP 55s + scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 55s + scalardl-auditor-metrics ClusterIP 10.108.1.147 8080/TCP 55s + scalardl-ledger-envoy ClusterIP 10.101.191.116 50051/TCP,50052/TCP 61s + scalardl-ledger-envoy-metrics ClusterIP 10.106.52.103 9001/TCP 61s + scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 61s + scalardl-ledger-metrics ClusterIP 10.99.122.106 8080/TCP 61s + ``` + + If the ScalarDL Ledger and ScalarDL Auditor services are deployed properly, you can see private IP addresses in the `CLUSTER-IP` column. + +:::note + +The `CLUSTER-IP` values for `scalardl-ledger-headless`, `scalardl-auditor-headless`, `postgresql-ledger-hl`, and `postgresql-auditor-hl` are `None` since they have no IP addresses. + +::: + +## Step 7. Start a client container + +You'll use the CA certificate file in a client container. Therefore, you'll need to create a secret resource and mount it to the client container. + +1. Create a secret resource named `client-ca-cert`. + + ```console + kubectl create secret generic client-ca-cert --from-file=ca.crt=<(kubectl get secret self-signed-ca-cert-secret -o "jsonpath={.data['ca\.crt']}" | base64 -d) -n default + ``` + +1. Create a manifest file for a client pod (`scalardl-client-pod.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-client-pod.yaml + apiVersion: v1 + kind: Pod + metadata: + name: "scalardl-client" + spec: + containers: + - name: scalardl-client + image: eclipse-temurin:8-jdk + command: ['sleep'] + args: ['inf'] + env: + - name: SCALAR_DL_VERSION + value: SCALAR_DL_CLIENT_POD_SCALAR_DL_VERSION + volumeMounts: + - name: "client-ca-cert" + mountPath: "/certs/" + readOnly: true + volumes: + - name: "client-ca-cert" + secret: + secretName: "client-ca-cert" + restartPolicy: Never + EOF + ``` + +1. Set the ScalarDL version in the manifest file. + + ```console + sed -i s/SCALAR_DL_CLIENT_POD_SCALAR_DL_VERSION/${SCALAR_DL_VERSION}/ ${HOME}/scalardl-test/scalardl-client-pod.yaml + ``` + +1. Deploy the client pod. + + ```console + kubectl apply -f ${HOME}/scalardl-test/scalardl-client-pod.yaml -n default + ``` + +1. Check if the client container is running. + + ```console + kubectl get pod scalardl-client -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + scalardl-client 1/1 Running 0 4s + ``` + +## Step 8. Run ScalarDL sample contracts in the client container + +The following explains the minimum steps needed to run sample contracts. For more details about ScalarDL Ledger and ScalarDL Auditor, see the following: + +* [Getting Started with ScalarDL](https://scalardl.scalar-labs.com/docs/latest/getting-started/) +* [Getting Started with ScalarDL Auditor](https://scalardl.scalar-labs.com/docs/latest/getting-started-auditor/) + +1. Run bash in the client container. + + ```console + kubectl exec -it scalardl-client -n default -- bash + ``` + + The commands in the following steps must be run in the client container. + +1. Install the git, curl, and unzip commands in the client container. + + ```console + apt update && apt install -y git curl unzip + ``` + +1. Clone the ScalarDL Java Client SDK git repository. + + ```console + git clone https://github.com/scalar-labs/scalardl-java-client-sdk.git + ``` + +1. Change the working directory to `scalardl-java-client-sdk/`. + + ```console + cd scalardl-java-client-sdk/ + ``` + + ```console + pwd + ``` + + [Command execution result] + + ```console + /scalardl-java-client-sdk + ``` + +1. Change the branch to the version you're using. + + ```console + git checkout -b v${SCALAR_DL_VERSION} refs/tags/v${SCALAR_DL_VERSION} + ``` + +1. Build the sample contracts. + + ```console + ./gradlew assemble + ``` + +1. Download the CLI tools for ScalarDL from [ScalarDL Java Client SDK Releases](https://github.com/scalar-labs/scalardl-java-client-sdk/releases). + + ```console + curl -OL https://github.com/scalar-labs/scalardl-java-client-sdk/releases/download/v${SCALAR_DL_VERSION}/scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip + ``` + +1. Unzip the `scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip` file. + + ```console + unzip ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip + ``` + +1. Create a configuration file named `client.properties` to access ScalarDL Ledger and ScalarDL Auditor on the Kubernetes cluster. + + ```console + cat << 'EOF' > client.properties + # Ledger configuration + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.client.tls.enabled=true + scalar.dl.client.tls.ca_root_cert_path=/certs/ca.crt + scalar.dl.client.tls.override_authority=envoy.scalar.example.com + + # Auditor configuration + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + scalar.dl.client.auditor.tls.enabled=true + scalar.dl.client.auditor.tls.ca_root_cert_path=/certs/ca.crt + scalar.dl.client.auditor.tls.override_authority=envoy.scalar.example.com + + # Client configuration + scalar.dl.client.authentication_method=hmac + scalar.dl.client.entity.id=client + scalar.dl.client.entity.identity.hmac.secret_key=scalardl-hmac-client-secert-key + EOF + ``` + +1. Register the client secret. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-secret --config ./client.properties + ``` + +1. Register the sample contract `StateUpdater`. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id StateUpdater --contract-binary-name com.org1.contract.StateUpdater --contract-class-file ./build/classes/java/main/com/org1/contract/StateUpdater.class + ``` + +1. Register the sample contract `StateReader`. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id StateReader --contract-binary-name com.org1.contract.StateReader --contract-class-file ./build/classes/java/main/com/org1/contract/StateReader.class + ``` + +1. Register the contract `ValidateLedger` to execute a validate request. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id validate-ledger --contract-binary-name com.scalar.dl.client.contract.ValidateLedger --contract-class-file ./build/classes/java/main/com/scalar/dl/client/contract/ValidateLedger.class + ``` + +1. Execute the contract `StateUpdater`. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl execute-contract --config ./client.properties --contract-id StateUpdater --contract-argument '{"asset_id": "test_asset", "state": 3}' + ``` + + This sample contract updates the `state` (value) of the asset named `test_asset` to `3`. + +1. Execute the contract `StateReader`. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl execute-contract --config ./client.properties --contract-id StateReader --contract-argument '{"asset_id": "test_asset"}' + ``` + + [Command execution result] + + ```console + Contract result: + { + "id" : "test_asset", + "age" : 0, + "output" : { + "state" : 3 + } + } + ``` + + ### Reference + + * If the asset data is not tampered with, running the `execute-contract` command to request contract execution will return `OK` as a result. + * If the asset data is tampered with (for example, if the `state` value in the database is tampered with), running the `execute-contract` command to request contract execution will return a value other than `OK` (for example, `INCONSISTENT_STATES`) as a result. See the following as an example for how ScalarDL detects data tampering. + + [Command execution result (if the asset data is tampered with)] + + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + +1. Execute a validation request for the asset. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl validate-ledger --config ./client.properties --asset-id "test_asset" + ``` + + [Command execution result] + + ```console + { + "status_code" : "OK", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEYCIQDiiXqzw6K+Ml4uvn8rK43o5wHWESU3hoXnZPi6/OeKVwIhAM+tFBcapl6zg47Uq0Uc8nVNGWNHZLBDBGve3F0xkzTR" + }, + "Auditor" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEUCIQDLsfUR2PmxSvfpL3YvHJUkz00RDpjCdctkroZKXE8d5QIgH73FQH2e11jfnynD00Pp9DrIG1vYizxDsvxUsMPo9IU=" + } + } + ``` + + ### Reference + + * If the asset data is not tampered with, running the `validate-ledger` command to request validation will return `OK` as the result. + * If the asset data is tampered with (for example, if the `state` value in the database is tampered with), running the `validate-ledger` command to request validation will return a value other than `OK` (for example, `INVALID_OUTPUT`) as a result. See the following as an example for how ScalarDL detects data tampering. + + [Command execution result (if the asset data is tampered with)] + + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + +1. Exit from the client container. + + ```console + exit + ``` + +## Step 9. Delete all resources + +After completing the ScalarDL Ledger and ScalarDL Auditor tests on the Kubernetes cluster, remove all resources. + +1. Uninstall ScalarDL Ledger, ScalarDL Auditor, ScalarDL Schema Loader, and PostgreSQL. + + ```console + helm uninstall -n default scalardl-ledger schema-loader-ledger postgresql-ledger scalardl-auditor schema-loader-auditor postgresql-auditor + ``` + +1. Remove the self-signed CA. + + ``` + kubectl delete -f ./private-ca-custom-values.yaml + ``` + +1. Uninstall cert-manager. + + ```console + helm uninstall -n cert-manager cert-manager + ``` + +1. Remove the client container. + + ``` + kubectl delete pod scalardl-client --grace-period 0 -n default + ``` + +1. Remove the secret resources. + + ``` + kubectl delete secrets self-signed-ca-cert-secret schema-ledger-credentials-secret schema-auditor-credentials-secret scalardl-ledger-tls-cert scalardl-ledger-envoy-tls-cert scalardl-auditor-tls-cert scalardl-auditor-envoy-tls-cert ledger-credentials-secret auditor-credentials-secret client-ca-cert auditor-keys + ``` + +1. Remove the namespace `cert-manager`. + + ``` + kubectl delete ns cert-manager + ``` + +1. Remove the working directory and sample files (configuration files). + + ```console + cd ${HOME} + ``` + + ```console + rm -rf ${HOME}/scalardl-test/ + ``` + +## Further reading + +You can see how to get started with monitoring or logging for Scalar products in the following tutorials: + +* [Getting Started with Helm Charts (Monitoring using Prometheus Operator)](getting-started-monitoring.mdx) +* [Getting Started with Helm Charts (Logging using Loki Stack)](getting-started-logging.mdx) +* [Getting Started with Helm Charts (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls.mdx new file mode 100644 index 00000000..03c14708 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor-tls.mdx @@ -0,0 +1,1033 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (ScalarDL Ledger and Auditor with TLS / Auditor Mode) + +This tutorial explains how to get started with ScalarDL Ledger and ScalarDL Auditor with TLS configurations by using Helm Charts on a Kubernetes cluster as a test environment. Before starting, you should already have a Mac or Linux environment for testing. In addition, although this tutorial mentions using **minikube**, the steps described should work in any Kubernetes cluster. + +## Requirements + +* You need to have a license key (trial license or commercial license) for ScalarDL. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). +* You need to use ScalarDL 3.9 or later, which supports TLS. + +:::note + +To make Byzantine fault detection with auditing work properly, ScalarDL Ledger and ScalarDL Auditor should be deployed and managed in different administrative domains. However, in this tutorial, we will deploy ScalarDL Ledger and ScalarDL Auditor in the same Kubernetes cluster to make the test easier. + +::: + +## What you'll create + +In this tutorial, you'll deploy the following components on a Kubernetes cluster in the following way: + +``` ++-----------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +---------+ | +| +---> | Envoy | ---+ +---> | Ledger | ---+ | +| | +-------+ | | +---------+ | | +| | | | | | +| +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Ledger | ---+---> | PostgreSQL | | +| | | (Envoy) | | +-------+ | | (Ledger) | | +---------+ | | (For Ledger) | | +| | +---------+ | | +-----------+ | | +---------------+ | +| [Pod] | | +-------+ | | +---------+ | | +| | +---> | Envoy | ---+ +---> | Ledger | ---+ | +| +--------+ | +-------+ +---------+ | +| | Client | ---+ | +| +--------+ | +-------+ +---------+ | +| | +---> | Envoy | ---+ +---> | Auditor | ---+ | +| | | +-------+ | | +---------+ | | +| | | | | | | +| | +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Auditor | ---+---> | PostgreSQL | | +| | (Envoy) | | +-------+ | | (Auditor) | | +---------+ | | (For Auditor) | | +| +---------+ | | +-----------+ | | +---------------+ | +| | +-------+ | | +---------+ | | +| +---> | Envoy | ---+ +---> | Auditor | ---+ | +| +-------+ +---------+ | +| | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +You'll also create the following private key and certificate files for TLS connections. + +``` + +----------------------+ + +---> | For Scalar Envoy | + | +----------------------+ + | | envoy-key.pem | + | | envoy.pem | + | +----------------------+ + | ++----------------------+ | +----------------------+ +| Self-signed CA | ---(Sign certificates)---+---> | For ScalarDL Ledger | ++----------------------+ | +----------------------+ +| ca-key.pem | | | ledger-key.pem | +| ca.pem | | | ledger.pem | ++----------------------+ | +----------------------+ + | + | +----------------------+ + +---> | For ScalarDL Auditor | + +----------------------+ + | auditor-key.pem | + | auditor.pem | + +----------------------+ +``` + +You'll set each private key and certificate file as follows to enable TLS in each connection. + +``` + +--------------------------------+ +--------------------------------+ + +-------(Normal request)-----> | Envoy for ScalarDL Ledger | ---> | ScalarDL Ledger | + | +--------------------------------+ +--------------------------------+ + | +---(Recovery request)---> | envoy-key.pem | ---> | ledger-key.pem | + | | | envoy.pem | | ledger.pem | + | | | ca.pem (to verify ledger.pem) | | ca.pem (used for health check) | + | | +--------------------------------+ +--------------------------------+ ++--------------------------------+ | | +| Client | ---+ | ++--------------------------------+ | +--------------------------------------------------------------------------------------------------------+ +| ca.pem (to verify envoy.pem) | | | ++--------------------------------+ | | + | +--------------------------------+ +--------------------------------+ | + +-------(Normal request)-----> | Envoy for ScalarDL Auditor | ---> | ScalarDL Auditor | ---+ + +--------------------------------+ +--------------------------------+ + | envoy-key.pem | | auditor-key.pem | + | envoy.pem | | auditor.pem | + | ca.pem (to verify auditor.pem) | | ca.pem (used for health check) | + +--------------------------------+ | ca.pem (to verify ledger.pem) | + +--------------------------------+ +``` + +The following connections exist amongst the ScalarDL-related components: + +* **`Client - Envoy for ScalarDL Ledger`:** When you execute a ScalarDL API function, the client accesses Envoy for ScalarDL Ledger. +* **`Client - Envoy for ScalarDL Auditor`:** When you execute a ScalarDL API function, the client accesses Envoy for ScalarDL Auditor. +* **`Envoy for ScalarDL Ledger - ScalarDL Ledger`:** Envoy works as an L7 (gRPC) load balancer in front of ScalarDL Ledger. +* **`Envoy for ScalarDL Auditor - ScalarDL Auditor`:** Envoy works as an L7 (gRPC) load balancer in front of ScalarDL Auditor. +* **`ScalarDL Auditor - Envoy for ScalarDL Ledger (ScalarDL Ledger)`:** When ScalarDL needs to run the recovery process to keep data consistent, ScalarDL Auditor runs the request against ScalarDL Ledger via Envoy. + +## Step 1. Start a Kubernetes cluster and install tools + +You need to prepare a Kubernetes cluster and install some tools (`kubectl`, `helm`, `cfssl`, and `cfssljson`). For more details on how to install them, see [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). + +## Step 2. Start the PostgreSQL containers + +ScalarDL Ledger and ScalarDL Auditor must use some type of database system as a backend database. In this tutorial, you'll use PostgreSQL. + +You can deploy PostgreSQL on the Kubernetes cluster as follows: + +1. Add the Bitnami helm repository. + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Deploy PostgreSQL for Ledger. + + ```console + helm install postgresql-ledger bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. Deploy PostgreSQL for Auditor. + + ```console + helm install postgresql-auditor bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false \ + -n default + ``` + +1. Check if the PostgreSQL containers are running. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 11s + postgresql-ledger-0 1/1 Running 0 16s + ``` + +## Step 3. Create a working directory + +You'll create some configuration files and private key and certificate files locally. Be sure to create a working directory for those files. + +1. Create a working directory. + + ```console + mkdir -p ${HOME}/scalardl-test/certs/ + ``` + +## Step 4. Create private key and certificate files + +You'll create private key and a certificate files. + +1. Change the working directory to `${HOME}/scalardl-test/certs/`. + + ```console + cd ${HOME}/scalardl-test/certs/ + ``` + +1. Create a JSON file that includes CA information. + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/ca.json + { + "CN": "scalar-test-ca", + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Test CA" + } + ] + } + EOF + ``` + +1. Create the CA private key and certificate files. + + ```console + cfssl gencert -initca ca.json | cfssljson -bare ca + ``` + +1. Create a JSON file that includes CA configurations. + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/ca-config.json + { + "signing": { + "default": { + "expiry": "87600h" + }, + "profiles": { + "scalar-test-ca": { + "expiry": "87600h", + "usages": [ + "signing", + "key encipherment", + "server auth" + ] + } + } + } + } + EOF + ``` + +1. Create a JSON file that includes Envoy information. + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/envoy.json + { + "CN": "scalar-envoy", + "hosts": [ + "envoy.scalar.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Envoy Test" + } + ] + } + EOF + ``` + +1. Create a JSON file that includes ScalarDL Ledger information. + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/ledger.json + { + "CN": "scalardl-ledger", + "hosts": [ + "ledger.scalardl.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "ScalarDL Ledger Test" + } + ] + } + EOF + ``` + +1. Create a JSON file that includes ScalarDL Auditor information. + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/certs/auditor.json + { + "CN": "scalardl-auditor", + "hosts": [ + "auditor.scalardl.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "ScalarDL Auditor Test" + } + ] + } + EOF + ``` + +1. Create private key and certificate files for Envoy. + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca envoy.json | cfssljson -bare envoy + ``` + +1. Create private key and certificate files for ScalarDL Ledger. + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca ledger.json | cfssljson -bare ledger + ``` + +1. Create private key and certificate files for ScalarDL Auditor. + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-test-ca auditor.json | cfssljson -bare auditor + ``` + +1. Confirm that the private key and certificate files were created. + + ```console + ls -1 + ``` + + [Command execution result] + + ```console + auditor-key.pem + auditor.csr + auditor.json + auditor.pem + ca-config.json + ca-key.pem + ca.csr + ca.json + ca.pem + envoy-key.pem + envoy.csr + envoy.json + envoy.pem + ledger-key.pem + ledger.csr + ledger.json + ledger.pem + ``` + +## Step 5. Create database schemas for ScalarDL Ledger and ScalarDL Auditor by using Helm Charts + +You'll deploy two ScalarDL Schema Loader pods on the Kubernetes cluster by using Helm Charts. The ScalarDL Schema Loader will create the database schemas for ScalarDL Ledger and Auditor in PostgreSQL. + +1. Change the working directory to `${HOME}/scalardl-test/`. + + ```console + cd ${HOME}/scalardl-test/ + ``` + +1. Add the Scalar Helm Charts repository. + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. Create a custom values file for ScalarDL Schema Loader for Ledger (`schema-loader-ledger-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_LEDGER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_LEDGER_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + secretName: "schema-ledger-credentials-secret" + EOF + ``` + +1. Create a custom values file for ScalarDL Schema Loader for Auditor (`schema-loader-auditor-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/schema-loader-auditor-custom-values.yaml + schemaLoading: + schemaType: "auditor" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_AUDITOR_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_AUDITOR_POSTGRES_PASSWORD} + scalar.db.storage=jdbc + secretName: "schema-auditor-credentials-secret" + EOF + ``` + +1. Create a secret resource named `schema-ledger-credentials-secret` that includes a username and password for PostgreSQL for ScalarDL Ledger. + + ```console + kubectl create secret generic schema-ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres \ + -n default + ``` + +1. Create a secret resource named `schema-auditor-credentials-secret` that includes a username and password for PostgreSQL for ScalarDL Auditor. + + ```console + kubectl create secret generic schema-auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres \ + -n default + ``` + +1. Set the chart version of ScalarDL Schema Loader. + + ```console + SCALAR_DL_VERSION=3.9.1 + SCALAR_DL_SCHEMA_LOADER_CHART_VERSION=$(helm search repo scalar-labs/schema-loading -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. Deploy ScalarDL Schema Loader for ScalarDL Ledger. + + ```console + helm install schema-loader-ledger scalar-labs/schema-loading -f ${HOME}/scalardl-test/schema-loader-ledger-custom-values.yaml --version ${SCALAR_DL_SCHEMA_LOADER_CHART_VERSION} -n default + ``` + +1. Deploy ScalarDL Schema Loader for ScalarDL Auditor. + + ```console + helm install schema-loader-auditor scalar-labs/schema-loading -f ${HOME}/scalardl-test/schema-loader-auditor-custom-values.yaml --version ${SCALAR_DL_SCHEMA_LOADER_CHART_VERSION} -n default + ``` + +1. Check if the ScalarDL Schema Loader pods are deployed with the status `Completed`. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 2m56s + postgresql-ledger-0 1/1 Running 0 3m1s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 6s + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 10s + ``` + + If the status of the ScalarDL Schema Loader pods are **ContainerCreating** or **Running**, wait for the `STATUS` column for those pods to show as `Completed`. + +## Step 6. Deploy ScalarDL Ledger and ScalarDL Auditor on the Kubernetes cluster by using Helm Charts + +1. Set your license key and certificate as environment variables. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). Also, you can see the value of `` and `` in [our document](https://scalardb.scalar-labs.com/docs/latest/scalar-licensing/README/). + + ```console + SCALAR_DL_LEDGER_LICENSE_KEY='' + SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM='' + SCALAR_DL_AUDITOR_LICENSE_KEY='' + SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM='' + ``` + +1. Create a custom values file for ScalarDL Ledger (`scalardl-ledger-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + + tls: + downstream: + enabled: true + certChainSecret: "envoy-tls-cert" + privateKeySecret: "envoy-tls-key" + upstream: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" + caRootCertSecret: "scalardl-ledger-tls-ca" + + ledger: + + image: + repository: "ghcr.io/scalar-labs/scalardl-ledger-byol" + + ledgerProperties: | + ### Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_LEDGER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_LEDGER_POSTGRES_PASSWORD} + + ### Ledger configurations + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.authentication.method=hmac + scalar.dl.ledger.authentication.hmac.cipher_key=${env:SCALAR_DL_LEDGER_HMAC_CIPHER_KEY} + scalar.dl.ledger.servers.authentication.hmac.secret_key=${env:SCALAR_DL_LEDGER_HMAC_SECRET_KEY} + + ### TLS configurations + scalar.dl.ledger.server.tls.enabled=true + scalar.dl.ledger.server.tls.cert_chain_path=/tls/scalardl-ledger/certs/tls.crt + scalar.dl.ledger.server.tls.private_key_path=/tls/scalardl-ledger/certs/tls.key + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DL_LEDGER_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "ledger.scalardl.example.com" + caRootCertSecret: "scalardl-ledger-tls-ca" + certChainSecret: "scalardl-ledger-tls-cert" + privateKeySecret: "scalardl-ledger-tls-key" + + secretName: "ledger-credentials-secret" + EOF + ``` + +1. Create a custom values file for ScalarDL Auditor (`scalardl-auditor-custom-values.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-auditor-custom-values.yaml + envoy: + + tls: + downstream: + enabled: true + certChainSecret: "envoy-tls-cert" + privateKeySecret: "envoy-tls-key" + upstream: + enabled: true + overrideAuthority: "auditor.scalardl.example.com" + caRootCertSecret: "scalardl-auditor-tls-ca" + + auditor: + image: + repository: "ghcr.io/scalar-labs/scalardl-auditor-byol" + + auditorProperties: | + ### Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DL_AUDITOR_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DL_AUDITOR_POSTGRES_PASSWORD} + + ### Auditor configurations + scalar.dl.auditor.ledger.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.auditor.authentication.method=hmac + scalar.dl.auditor.authentication.hmac.cipher_key=${env:SCALAR_DL_AUDITOR_HMAC_CIPHER_KEY} + scalar.dl.auditor.servers.authentication.hmac.secret_key=${env:SCALAR_DL_AUDITOR_HMAC_SECRET_KEY} + + ### TLS configurations + scalar.dl.auditor.server.tls.enabled=true + scalar.dl.auditor.server.tls.cert_chain_path=/tls/scalardl-auditor/certs/tls.crt + scalar.dl.auditor.server.tls.private_key_path=/tls/scalardl-auditor/certs/tls.key + scalar.dl.auditor.tls.enabled=true + scalar.dl.auditor.tls.ca_root_cert_path=/tls/scalardl-ledger/certs/ca.crt + scalar.dl.auditor.tls.override_authority=envoy.scalar.example.com + + ### License key configurations + scalar.dl.licensing.license_key=${env:SCALAR_DL_AUDITOR_LICENSE_KEY} + scalar.dl.licensing.license_check_cert_pem=${env:SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM} + + tls: + enabled: true + overrideAuthority: "auditor.scalardl.example.com" + caRootCertSecret: "scalardl-auditor-tls-ca" + certChainSecret: "scalardl-auditor-tls-cert" + privateKeySecret: "scalardl-auditor-tls-key" + caRootCertForLedgerSecret: "scalardl-auditor-tls-ca-for-ledger" + + secretName: "auditor-credentials-secret" + EOF + ``` + +1. Create a secret resource named `ledger-credentials-secret` that includes credentials and a license key. + + ```console + kubectl create secret generic ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DL_LEDGER_HMAC_CIPHER_KEY=ledger-hmac-cipher-key \ + --from-literal=SCALAR_DL_LEDGER_HMAC_SECRET_KEY=scalardl-hmac-secret-key \ + --from-literal=SCALAR_DL_LEDGER_LICENSE_KEY="${SCALAR_DL_LEDGER_LICENSE_KEY}" \ + --from-file=SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DL_LEDGER_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. Create a secret resource named `auditor-credentials-secret` that includes credentials and a license key. + + ```console + kubectl create secret generic auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DL_AUDITOR_HMAC_CIPHER_KEY=auditor-hmac-cipher-key \ + --from-literal=SCALAR_DL_AUDITOR_HMAC_SECRET_KEY=scalardl-hmac-secret-key \ + --from-literal=SCALAR_DL_AUDITOR_LICENSE_KEY="${SCALAR_DL_AUDITOR_LICENSE_KEY}" \ + --from-file=SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DL_AUDITOR_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +1. Create secret resources that include the private key and certificate files for Envoy. + + ```console + kubectl create secret generic envoy-tls-cert --from-file=tls.crt=${HOME}/scalardl-test/certs/envoy.pem -n default + kubectl create secret generic envoy-tls-key --from-file=tls.key=${HOME}/scalardl-test/certs/envoy-key.pem -n default + ``` + +1. Create secret resources that include the private key, certificate, and CA certificate files for ScalarDL Ledger. + + ```console + kubectl create secret generic scalardl-ledger-tls-ca --from-file=ca.crt=${HOME}/scalardl-test/certs/ca.pem -n default + kubectl create secret generic scalardl-ledger-tls-cert --from-file=tls.crt=${HOME}/scalardl-test/certs/ledger.pem -n default + kubectl create secret generic scalardl-ledger-tls-key --from-file=tls.key=${HOME}/scalardl-test/certs/ledger-key.pem -n default + ``` + +1. Create secret resources that include the private key, certificate, and CA certificate files for ScalarDL Auditor. + + ```console + kubectl create secret generic scalardl-auditor-tls-ca --from-file=ca.crt=${HOME}/scalardl-test/certs/ca.pem -n default + kubectl create secret generic scalardl-auditor-tls-cert --from-file=tls.crt=${HOME}/scalardl-test/certs/auditor.pem -n default + kubectl create secret generic scalardl-auditor-tls-key --from-file=tls.key=${HOME}/scalardl-test/certs/auditor-key.pem -n default + kubectl create secret generic scalardl-auditor-tls-ca-for-ledger --from-file=ca.crt=${HOME}/scalardl-test/certs/ca.pem -n default + ``` + +1. Create a secret resource named `auditor-keys` to disable the `digital-signature` authentication method. In this tutorial, you'll use the `hmac` authentication method instead of `digital-signature`. + + ```console + kubectl create secret generic auditor-keys \ + --from-literal=tls.key=dummy-data-to-disable-digital-signature-method \ + --from-literal=certificate=dummy-data-to-disable-digital-signature-method \ + -n default + ``` + Note: If you use `hmac` as an authentication method, you have to create a dummy secret `auditor-key` to disable `digital-signature` on the helm chart side. + +1. Set the chart version of ScalarDL Ledger and ScalarDL Auditor. + + ```console + SCALAR_DL_LEDGER_CHART_VERSION=$(helm search repo scalar-labs/scalardl -l | grep -v -e "scalar-labs/scalardl-audit" | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + SCALAR_DL_AUDITOR_CHART_VERSION=$(helm search repo scalar-labs/scalardl-audit -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +1. Deploy ScalarDL Ledger. + + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ${HOME}/scalardl-test/scalardl-ledger-custom-values.yaml --version ${SCALAR_DL_LEDGER_CHART_VERSION} -n default + ``` + +1. Deploy ScalarDL Auditor. + + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ${HOME}/scalardl-test/scalardl-auditor-custom-values.yaml --version ${SCALAR_DL_AUDITOR_CHART_VERSION} -n default + ``` + +1. Check if the ScalarDL Ledger and ScalarDL Auditor pods are deployed. + + ```console + kubectl get pod -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 14m + postgresql-ledger-0 1/1 Running 0 14m + scalardl-auditor-auditor-5b885ff4c8-fwkpf 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-g69cb 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-nsmnq 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-5mn6v 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-fpq8j 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-lsz2t 1/1 Running 0 18s + scalardl-ledger-envoy-547bbf7546-n7p5x 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-p8nwp 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-pskpb 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-5zsbj 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-vnmrw 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-wpjvs 1/1 Running 0 26s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 11m + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 11m + ``` + + If the ScalarDL Ledger and ScalarDL Auditor pods are deployed properly, the `STATUS` column for those pods will be displayed as `Running`. + +1. Check if the ScalarDL Ledger and ScalarDL Auditor services are deployed. + + ```console + kubectl get svc -n default + ``` + + [Command execution result] + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-auditor ClusterIP 10.107.9.78 5432/TCP 15m + postgresql-auditor-hl ClusterIP None 5432/TCP 15m + postgresql-ledger ClusterIP 10.108.241.181 5432/TCP 15m + postgresql-ledger-hl ClusterIP None 5432/TCP 15m + scalardl-auditor-envoy ClusterIP 10.100.61.202 40051/TCP,40052/TCP 55s + scalardl-auditor-envoy-metrics ClusterIP 10.99.6.227 9001/TCP 55s + scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 55s + scalardl-auditor-metrics ClusterIP 10.108.1.147 8080/TCP 55s + scalardl-ledger-envoy ClusterIP 10.101.191.116 50051/TCP,50052/TCP 61s + scalardl-ledger-envoy-metrics ClusterIP 10.106.52.103 9001/TCP 61s + scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 61s + scalardl-ledger-metrics ClusterIP 10.99.122.106 8080/TCP 61s + ``` + + If the ScalarDL Ledger and ScalarDL Auditor services are deployed properly, you can see private IP addresses in the `CLUSTER-IP` column. + +:::note + +The `CLUSTER-IP` values for `scalardl-ledger-headless`, `scalardl-auditor-headless`, `postgresql-ledger-hl`, and `postgresql-auditor-hl` are `None` since they have no IP addresses. + +::: + +## Step 7. Start a client container + +You'll use the CA certificate file in a client container. Therefore, you'll need to create a secret resource and mount it to the client container. + +1. Create a secret resource named `client-ca-cert`. + + ```console + kubectl create secret generic client-ca-cert --from-file=ca.crt=${HOME}/scalardl-test/certs/ca.pem -n default + ``` + +1. Create a manifest file for a client pod (`scalardl-client-pod.yaml`). + + ```console + cat << 'EOF' > ${HOME}/scalardl-test/scalardl-client-pod.yaml + apiVersion: v1 + kind: Pod + metadata: + name: "scalardl-client" + spec: + containers: + - name: scalardl-client + image: eclipse-temurin:8-jdk + command: ['sleep'] + args: ['inf'] + env: + - name: SCALAR_DL_VERSION + value: SCALAR_DL_CLIENT_POD_SCALAR_DL_VERSION + volumeMounts: + - name: "client-ca-cert" + mountPath: "/certs/" + readOnly: true + volumes: + - name: "client-ca-cert" + secret: + secretName: "client-ca-cert" + restartPolicy: Never + EOF + ``` + +1. Set the ScalarDL version in the manifest file. + + ```console + sed -i s/SCALAR_DL_CLIENT_POD_SCALAR_DL_VERSION/${SCALAR_DL_VERSION}/ ${HOME}/scalardl-test/scalardl-client-pod.yaml + ``` + +1. Deploy the client pod. + + ```console + kubectl apply -f ${HOME}/scalardl-test/scalardl-client-pod.yaml -n default + ``` + +1. Check if the client container is running. + + ```console + kubectl get pod scalardl-client -n default + ``` + + [Command execution result] + + ```console + NAME READY STATUS RESTARTS AGE + scalardl-client 1/1 Running 0 4s + ``` + +## Step 8. Run ScalarDL sample contracts in the client container + +The following explains the minimum steps needed to run sample contracts. For more details about ScalarDL Ledger and ScalarDL Auditor, see the following: + +* [Getting Started with ScalarDL](https://scalardl.scalar-labs.com/docs/latest/getting-started/) +* [Getting Started with ScalarDL Auditor](https://scalardl.scalar-labs.com/docs/latest/getting-started-auditor/) + +1. Run bash in the client container. + + ```console + kubectl exec -it scalardl-client -n default -- bash + ``` + The commands in the following steps must be run in the client container. + +1. Install the git, curl, and unzip commands in the client container. + + ```console + apt update && apt install -y git curl unzip + ``` + +1. Clone the ScalarDL Java Client SDK git repository. + + ```console + git clone https://github.com/scalar-labs/scalardl-java-client-sdk.git + ``` + +1. Change the working directory to `scalardl-java-client-sdk/`. + + ```console + cd scalardl-java-client-sdk/ + ``` + + ```console + pwd + ``` + + [Command execution result] + + ```console + /scalardl-java-client-sdk + ``` + +1. Change the branch to the version you're using. + + ```console + git checkout -b v${SCALAR_DL_VERSION} refs/tags/v${SCALAR_DL_VERSION} + ``` + +1. Build the sample contracts. + + ```console + ./gradlew assemble + ``` + +1. Download the CLI tools for ScalarDL from [ScalarDL Java Client SDK Releases](https://github.com/scalar-labs/scalardl-java-client-sdk/releases). + + ```console + curl -OL https://github.com/scalar-labs/scalardl-java-client-sdk/releases/download/v${SCALAR_DL_VERSION}/scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip + ``` + You need to use the same version of CLI tools and ScalarDL Ledger. + +1. Unzip the `scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip` file. + + ```console + unzip ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}.zip + ``` + +1. Create a configuration file named `client.properties` to access ScalarDL Ledger and ScalarDL Auditor on the Kubernetes cluster. + + ```console + cat << 'EOF' > client.properties + # Ledger configuration + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.client.tls.enabled=true + scalar.dl.client.tls.ca_root_cert_path=/certs/ca.crt + scalar.dl.client.tls.override_authority=envoy.scalar.example.com + + # Auditor configuration + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + scalar.dl.client.auditor.tls.enabled=true + scalar.dl.client.auditor.tls.ca_root_cert_path=/certs/ca.crt + scalar.dl.client.auditor.tls.override_authority=envoy.scalar.example.com + + # Client configuration + scalar.dl.client.authentication_method=hmac + scalar.dl.client.entity.id=client + scalar.dl.client.entity.identity.hmac.secret_key=scalardl-hmac-client-secert-key + EOF + ``` + +1. Register the client secret. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-secret --config ./client.properties + ``` + +1. Register the sample contract `StateUpdater`. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id StateUpdater --contract-binary-name com.org1.contract.StateUpdater --contract-class-file ./build/classes/java/main/com/org1/contract/StateUpdater.class + ``` + +1. Register the sample contract `StateReader`. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id StateReader --contract-binary-name com.org1.contract.StateReader --contract-class-file ./build/classes/java/main/com/org1/contract/StateReader.class + ``` + +1. Register the contract `ValidateLedger` to execute a validate request. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl register-contract --config ./client.properties --contract-id validate-ledger --contract-binary-name com.scalar.dl.client.contract.ValidateLedger --contract-class-file ./build/classes/java/main/com/scalar/dl/client/contract/ValidateLedger.class + ``` + +1. Execute the contract `StateUpdater`. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl execute-contract --config ./client.properties --contract-id StateUpdater --contract-argument '{"asset_id": "test_asset", "state": 3}' + ``` + This sample contract updates the `state` (value) of the asset named `test_asset` to `3`. + +1. Execute the contract `StateReader`. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl execute-contract --config ./client.properties --contract-id StateReader --contract-argument '{"asset_id": "test_asset"}' + ``` + + [Command execution result] + + ```console + Contract result: + { + "id" : "test_asset", + "age" : 0, + "output" : { + "state" : 3 + } + } + ``` + + ### Reference + + * If the asset data is not tampered with, running the `execute-contract` command to request contract execution will return `OK` as a result. + * If the asset data is tampered with (for example, if the `state` value in the database is tampered with), running the `execute-contract` command to request contract execution will return a value other than `OK` (for example, `INCONSISTENT_STATES`) as a result. See the following as an example for how ScalarDL detects data tampering. + + [Command execution result (if the asset data is tampered with)] + + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + +1. Execute a validation request for the asset. + + ```console + ./scalardl-java-client-sdk-${SCALAR_DL_VERSION}/bin/scalardl validate-ledger --config ./client.properties --asset-id "test_asset" + ``` + + [Command execution result] + + ```console + { + "status_code" : "OK", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEYCIQDiiXqzw6K+Ml4uvn8rK43o5wHWESU3hoXnZPi6/OeKVwIhAM+tFBcapl6zg47Uq0Uc8nVNGWNHZLBDBGve3F0xkzTR" + }, + "Auditor" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEUCIQDLsfUR2PmxSvfpL3YvHJUkz00RDpjCdctkroZKXE8d5QIgH73FQH2e11jfnynD00Pp9DrIG1vYizxDsvxUsMPo9IU=" + } + } + ``` + + ### Reference + + * If the asset data is not tampered with, running the `validate-ledger` command to request validation will return `OK` as the result. + * If the asset data is tampered with (for example, if the `state` value in the database is tampered with), running the `validate-ledger` command to request validation will return a value other than `OK` (for example, `INVALID_OUTPUT`) as a result. See the following as an example for how ScalarDL detects data tampering. + + [Command execution result (if the asset data is tampered with)] + + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + +1. Exit from the client container. + + ```console + exit + ``` + +## Step 9. Delete all resources + +After completing the ScalarDL Ledger and ScalarDL Auditor tests on the Kubernetes cluster, remove all resources. + +1. Uninstall ScalarDL Ledger, ScalarDL Auditor, ScalarDL Schema Loader, and PostgreSQL. + + ```console + helm uninstall -n default scalardl-ledger schema-loader-ledger postgresql-ledger scalardl-auditor schema-loader-auditor postgresql-auditor + ``` + +1. Remove the client container. + + ``` + kubectl delete pod scalardl-client --grace-period 0 -n default + ``` + +1. Remove the secret resources. + + ``` + kubectl delete secrets envoy-tls-key envoy-tls-cert schema-ledger-credentials-secret schema-auditor-credentials-secret ledger-credentials-secret scalardl-ledger-tls-ca scalardl-ledger-tls-cert scalardl-ledger-tls-key auditor-credentials-secret auditor-keys scalardl-auditor-tls-ca scalardl-auditor-tls-cert scalardl-auditor-tls-key scalardl-auditor-tls-ca-for-ledger client-ca-cert + ``` + +1. Remove the working directory and sample files (configuration file, private key, and certificate). + + ```console + cd ${HOME} + ``` + + ```console + rm -rf ${HOME}/scalardl-test/ + ``` + +## Further reading + +You can see how to get started with monitoring or logging for Scalar products in the following tutorials: + +* [Getting Started with Helm Charts (Monitoring using Prometheus Operator)](getting-started-monitoring.mdx) +* [Getting Started with Helm Charts (Logging using Loki Stack)](getting-started-logging.mdx) +* [Getting Started with Helm Charts (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor.mdx new file mode 100644 index 00000000..f888c9bd --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-auditor.mdx @@ -0,0 +1,909 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (ScalarDL Ledger and Auditor / Auditor mode) + +This document explains how to get started with ScalarDL Ledger and Auditor using Helm Chart on a Kubernetes cluster as a test environment. Here, we assume that you already have a Mac or Linux environment for testing. We use **Minikube** in this document, but the steps we will show should work in any Kubernetes cluster. + +## Requirement + +You need to subscribe to ScalarDL Ledger and ScalarDL Auditor in the [AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-rzbuhxgvqf4d2) or [Azure Marketplace](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) to get the following container images. + * AWS Marketplace + * scalar-ledger + * scalar-ledger-envoy + * scalardl-schema-loader-ledger + * scalar-auditor + * scalar-auditor-envoy + * scalardl-schema-loader-auditor + * Azure Marketplace + * scalar-ledger + * scalar-auditor + * scalardl-envoy + * scalardl-schema-loader + +Please refer to the following documents for more details. + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +## Note +To make Byzantine fault detection with auditing work properly, Ledger and Auditor should be deployed and managed in different administrative domains. However, in this guide, we will deploy Ledger and Auditor in the same Kubernetes cluster to make the test easier. + +## What we create + +We will deploy the following components on a Kubernetes cluster as follows. + +``` ++-----------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| [Pod] [Pod] [Pod] | +| | +| +-------+ +---------+ | +| +---> | Envoy | ---+ +---> | Ledger | ---+ | +| | +-------+ | | +---------+ | | +| | | | | | +| +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Ledger | ---+---> | PostgreSQL | | +| | | (Envoy) | | +-------+ | | (Ledger) | | +---------+ | | (For Ledger) | | +| | +---------+ | | +-----------+ | | +---------------+ | +| | | +-------+ | | +---------+ | | +| | +---> | Envoy | ---+ +---> | Ledger | ---+ | +| +--------+ | +-------+ +---------+ | +| | Client | ---+ | +| +--------+ | +-------+ +---------+ | +| | +---> | Envoy | ---+ +---> | Auditor | ---+ | +| | | +-------+ | | +---------+ | | +| | | | | | | +| | +---------+ | +-------+ | +-----------+ | +---------+ | +---------------+ | +| +---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | Auditor | ---+---> | PostgreSQL | | +| | (Envoy) | | +-------+ | | (Auditor) | | +---------+ | | (For Auditor) | | +| +---------+ | | +-----------+ | | +---------------+ | +| | +-------+ | | +---------+ | | +| +---> | Envoy | ---+ +---> | Auditor | ---+ | +| +-------+ +---------+ | +| | ++-----------------------------------------------------------------------------------------------------------------------------+ +``` + +## Step 1. Start a Kubernetes cluster + +First, you need to prepare a Kubernetes cluster. If you use a **minikube** environment, please refer to the [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). If you have already started a Kubernetes cluster, you can skip this step. + +## Step 2. Start PostgreSQL containers + +ScalarDL Ledger and Auditor use some kind of database system as a backend database. In this document, we use PostgreSQL. + +You can deploy PostgreSQL on the Kubernetes cluster as follows. + +1. Add the Bitnami helm repository. + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Deploy PostgreSQL for Ledger. + ```console + helm install postgresql-ledger bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. Deploy PostgreSQL for Auditor. + ```console + helm install postgresql-auditor bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. Check if the PostgreSQL containers are running. + ```console + kubectl get pod + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 11s + postgresql-ledger-0 1/1 Running 0 16s + ``` + +## Step 3. Create a working directory + +We will create some configuration files and key/certificate files locally. So, create a working directory for them. + +1. Create a working directory. + ```console + mkdir -p ~/scalardl-test/certs/ + ``` + +## Step 4. Create key/certificate files + +Note: In this guide, we will use self-sign certificates for the test. However, it is strongly recommended that these certificates NOT be used in production. + +1. Change the working directory to `~/scalardl-test/certs/` directory. + ```console + cd ~/scalardl-test/certs/ + ``` + +1. Create a JSON file that includes Ledger information. + ```console + cat << 'EOF' > ~/scalardl-test/certs/ledger.json + { + "CN": "ledger", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "ledger", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. Create a JSON file that includes Auditor information. + ```console + cat << 'EOF' > ~/scalardl-test/certs/auditor.json + { + "CN": "auditor", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "auditor", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. Create a JSON file that includes Client information. + ```console + cat << 'EOF' > ~/scalardl-test/certs/client.json + { + "CN": "client", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "client", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. Create key/certificate files for the Ledger. + ```console + cfssl selfsign "" ./ledger.json | cfssljson -bare ledger + ``` + +1. Create key/certificate files for the Auditor. + ```console + cfssl selfsign "" ./auditor.json | cfssljson -bare auditor + ``` + +1. Create key/certificate files for the Client. + ```console + cfssl selfsign "" ./client.json | cfssljson -bare client + ``` + +1. Confirm key/certificate files are created. + ```console + ls -1 + ``` + [Command execution result] + ```console + auditor-key.pem + auditor.csr + auditor.json + auditor.pem + client-key.pem + client.csr + client.json + client.pem + ledger-key.pem + ledger.csr + ledger.json + ledger.pem + ``` + +## Step 5. Create DB schemas for ScalarDL Ledger and ScalarDL Auditor using Helm Charts + +We will deploy two ScalarDL Schema Loader pods on the Kubernetes cluster using Helm Charts. +The ScalarDL Schema Loader will create the DB schemas for ScalarDL Ledger and Auditor in PostgreSQL. + +1. Change the working directory to `~/scalardl-test/`. + ```console + cd ~/scalardl-test/ + ``` + +1. Add the Scalar helm repository. + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. Create a secret resource to pull the ScalarDL container images from AWS/Azure Marketplace. + * AWS Marketplace + ```console + kubectl create secret docker-registry reg-ecr-mp-secrets \ + --docker-server=709825985650.dkr.ecr.us-east-1.amazonaws.com \ + --docker-username=AWS \ + --docker-password=$(aws ecr get-login-password --region us-east-1) + ``` + * Azure Marketplace + ```console + kubectl create secret docker-registry reg-acr-secrets \ + --docker-server= \ + --docker-username= \ + --docker-password= + ``` + + Please refer to the following documents for more details. + + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +1. Create a custom values file for ScalarDL Schema Loader for Ledger (schema-loader-ledger-custom-values.yaml). + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-schema-loader-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "ledger-credentials-secret" + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + image: + repository: "/scalarinc/scalardl-schema-loader" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "ledger-credentials-secret" + EOF + ``` + +1. Create a custom values file for ScalarDL Schema Loader for Auditor (schema-loader-auditor-custom-values.yaml). + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-auditor-custom-values.yaml + schemaLoading: + schemaType: "auditor" + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-schema-loader-auditor" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "auditor-credentials-secret" + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-auditor-custom-values.yaml + schemaLoading: + schemaType: "auditor" + image: + repository: "/scalarinc/scalardl-schema-loader" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "auditor-credentials-secret" + EOF + ``` + +1. Create a secret resource that includes a username and password for PostgreSQL for Ledger. + ```console + kubectl create secret generic ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres + ``` + +1. Create a secret resource that includes a username and password for PostgreSQL for Auditor. + ```console + kubectl create secret generic auditor-credentials-secret \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_AUDITOR_POSTGRES_PASSWORD=postgres + ``` + +1. Deploy the ScalarDL Schema Loader for Ledger. + ```console + helm install schema-loader-ledger scalar-labs/schema-loading -f ./schema-loader-ledger-custom-values.yaml + ``` + +1. Deploy the ScalarDL Schema Loader for Auditor. + ```console + helm install schema-loader-auditor scalar-labs/schema-loading -f ./schema-loader-auditor-custom-values.yaml + ``` + +1. Check if the ScalarDL Schema Loader pods are deployed and completed. + ```console + kubectl get pod + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 2m56s + postgresql-ledger-0 1/1 Running 0 3m1s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 6s + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 10s + ``` + If the ScalarDL Schema Loader pods are **ContainerCreating** or **Running**, wait for the process will be completed (The STATUS will be **Completed**). + +## Step 6. Deploy ScalarDL Ledger and Auditor on the Kubernetes cluster using Helm Charts + +1. Create a custom values file for ScalarDL Ledger (scalardl-ledger-custom-values.yaml). + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ledgerProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + secretName: "ledger-credentials-secret" + extraVolumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + extraVolumeMounts: + - name: "ledger-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + image: + repository: "/scalarinc/scalardl-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-acr-secrets" + + ledger: + image: + repository: "/scalarinc/scalar-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + ledgerProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + secretName: "ledger-credentials-secret" + extraVolumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + extraVolumeMounts: + - name: "ledger-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + +1. Create a custom values file for ScalarDL Auditor (scalardl-auditor-custom-values.yaml). + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-auditor-custom-values.yaml + envoy: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-auditor-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + + auditor: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-auditor" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + auditorProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.auditor.ledger.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.auditor.cert_path=/keys/certificate + scalar.dl.auditor.private_key_path=/keys/private-key + secretName: "auditor-credentials-secret" + extraVolumes: + - name: "auditor-keys" + secret: + secretName: "auditor-keys" + extraVolumeMounts: + - name: "auditor-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-auditor-custom-values.yaml + envoy: + image: + repository: "/scalarinc/scalardl-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-acr-secrets" + + auditor: + image: + repository: "/scalarinc/scalar-auditor" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + auditorProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-auditor.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_AUDITOR_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.auditor.ledger.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.auditor.cert_path=/keys/certificate + scalar.dl.auditor.private_key_path=/keys/private-key + secretName: "auditor-credentials-secret" + extraVolumes: + - name: "auditor-keys" + secret: + secretName: "auditor-keys" + extraVolumeMounts: + - name: "auditor-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + +1. Create secret resource `ledger-keys`. + ```console + kubectl create secret generic ledger-keys --from-file=certificate=./certs/ledger.pem --from-file=private-key=./certs/ledger-key.pem + ``` + +1. Create secret resource `auditor-keys`. + ```console + kubectl create secret generic auditor-keys --from-file=certificate=./certs/auditor.pem --from-file=private-key=./certs/auditor-key.pem + ``` + +1. Deploy the ScalarDL Ledger. + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + +1. Deploy the ScalarDL Auditor. + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + +1. Check if the ScalarDL Ledger and Auditor pods are deployed. + ```console + kubectl get pod + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + postgresql-auditor-0 1/1 Running 0 14m + postgresql-ledger-0 1/1 Running 0 14m + scalardl-auditor-auditor-5b885ff4c8-fwkpf 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-g69cb 1/1 Running 0 18s + scalardl-auditor-auditor-5b885ff4c8-nsmnq 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-5mn6v 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-fpq8j 1/1 Running 0 18s + scalardl-auditor-envoy-689bcbdf65-lsz2t 1/1 Running 0 18s + scalardl-ledger-envoy-547bbf7546-n7p5x 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-p8nwp 1/1 Running 0 26s + scalardl-ledger-envoy-547bbf7546-pskpb 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-5zsbj 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-vnmrw 1/1 Running 0 26s + scalardl-ledger-ledger-6db5dc8774-wpjvs 1/1 Running 0 26s + schema-loader-auditor-schema-loading-dvc5r 0/1 Completed 0 11m + schema-loader-ledger-schema-loading-mtllb 0/1 Completed 0 11m + ``` + If the ScalarDL Ledger and Auditor pods are deployed properly, you can see the STATUS are **Running**. + +1. Check if the ScalarDL Ledger and Auditor services are deployed. + ```console + kubectl get svc + ``` + [Command execution result] + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-auditor ClusterIP 10.107.9.78 5432/TCP 15m + postgresql-auditor-hl ClusterIP None 5432/TCP 15m + postgresql-ledger ClusterIP 10.108.241.181 5432/TCP 15m + postgresql-ledger-hl ClusterIP None 5432/TCP 15m + scalardl-auditor-envoy ClusterIP 10.100.61.202 40051/TCP,40052/TCP 55s + scalardl-auditor-envoy-metrics ClusterIP 10.99.6.227 9001/TCP 55s + scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 55s + scalardl-auditor-metrics ClusterIP 10.108.1.147 8080/TCP 55s + scalardl-ledger-envoy ClusterIP 10.101.191.116 50051/TCP,50052/TCP 61s + scalardl-ledger-envoy-metrics ClusterIP 10.106.52.103 9001/TCP 61s + scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 61s + scalardl-ledger-metrics ClusterIP 10.99.122.106 8080/TCP 61s + ``` + If the ScalarDL Ledger and Auditor services are deployed properly, you can see private IP addresses in the CLUSTER-IP column. (Note: `scalardl-ledger-headless` and `scalardl-auditor-headless` have no CLUSTER-IP.) + +## Step 7. Start a Client container + +We will use certificate files in a Client container. So, we create a secret resource and mount it to a Client container. + +1. Create secret resource `client-keys`. + ``` + kubectl create secret generic client-keys --from-file=certificate=./certs/client.pem --from-file=private-key=./certs/client-key.pem + ``` + +1. Start a Client container on the Kubernetes cluster. + ```console + cat << 'EOF' | kubectl apply -f - + apiVersion: v1 + kind: Pod + metadata: + name: "scalardl-client" + spec: + containers: + - name: scalardl-client + image: eclipse-temurin:8-jdk + command: ['sleep'] + args: ['inf'] + volumeMounts: + - name: "ledger-keys" + mountPath: "/keys/ledger" + readOnly: true + - name: "auditor-keys" + mountPath: "/keys/auditor" + readOnly: true + - name: "client-keys" + mountPath: "/keys/client" + readOnly: true + volumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + - name: "auditor-keys" + secret: + secretName: "auditor-keys" + - name: "client-keys" + secret: + secretName: "client-keys" + restartPolicy: Never + EOF + ``` + +1. Check if the Client container is running. + ```console + kubectl get pod scalardl-client + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + scalardl-client 1/1 Running 0 4s + ``` + +## Step 8. Run ScalarDL sample contracts in the Client container + +The following explains the minimum steps. If you want to know more details about ScalarDL Ledger and Auditor, please refer to the following documents. + * [Getting Started with ScalarDL](https://scalardl.scalar-labs.com/docs/latest/getting-started) + * [Getting Started with ScalarDL Auditor](https://scalardl.scalar-labs.com/docs/latest/getting-started-auditor) + +When you use Auditor, you need to register the certificate for the Ledger and Auditor before starting the client application. Ledger needs to register its certificate to Auditor, and Auditor needs to register its certificate to Ledger. + +1. Run bash in the Client container. + ```console + kubectl exec -it scalardl-client -- bash + ``` + After this step, run each command in the Client container. + +1. Install the git, curl and unzip commands in the Client container. + ```console + apt update && apt install -y git curl unzip + ``` + +1. Clone ScalarDL Java Client SDK git repository. + ```console + git clone https://github.com/scalar-labs/scalardl-java-client-sdk.git + ``` + +1. Change the directory to `scalardl-java-client-sdk/`. + ```console + cd scalardl-java-client-sdk/ + ``` + ```console + pwd + ``` + [Command execution result] + ```console + + /scalardl-java-client-sdk + ``` + +1. Change branch to arbitrary version. + ```console + git checkout -b v3.6.0 refs/tags/v3.6.0 + ``` + ```console + git branch + ``` + [Command execution result] + ```console + master + * v3.6.0 + ``` + If you want to use another version, please specify the version (tag) you want to use. You need to use the same version of ScalarDL Ledger and ScalarDL Java Client SDK. + +1. Build the sample contracts. + ```console + ./gradlew assemble + ``` + +1. Download CLI tools of ScalarDL from [ScalarDL Java Client SDK Releases](https://github.com/scalar-labs/scalardl-java-client-sdk/releases). + ```console + curl -OL https://github.com/scalar-labs/scalardl-java-client-sdk/releases/download/v3.6.0/scalardl-java-client-sdk-3.6.0.zip + ``` + You need to use the same version of CLI tools and ScalarDL Ledger. + +1. Unzip the `scalardl-java-client-sdk-3.6.0.zip` file. + ```console + unzip ./scalardl-java-client-sdk-3.6.0.zip + ``` + +1. Create a configuration file (ledger.as.client.properties) to register the certificate of Ledger to Auditor. + ```console + cat << 'EOF' > ledger.as.client.properties + # Ledger + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + + # Certificate + scalar.dl.client.cert_holder_id=ledger + scalar.dl.client.cert_path=/keys/ledger/certificate + scalar.dl.client.private_key_path=/keys/ledger/private-key + EOF + ``` + +1. Create a configuration file (auditor.as.client.properties) to register the certificate of Auditor to Ledger. + ```console + cat << 'EOF' > auditor.as.client.properties + # Ledger + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + + # Certificate + scalar.dl.client.cert_holder_id=auditor + scalar.dl.client.cert_path=/keys/auditor/certificate + scalar.dl.client.private_key_path=/keys/auditor/private-key + EOF + ``` + +1. Create a configuration file (client.properties) to access ScalarDL Ledger on the Kubernetes cluster. + ```console + cat << 'EOF' > client.properties + # Ledger + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=scalardl-auditor-envoy.default.svc.cluster.local + + # Certificate + scalar.dl.client.cert_holder_id=client + scalar.dl.client.cert_path=/keys/client/certificate + scalar.dl.client.private_key_path=/keys/client/private-key + EOF + ``` + +1. Register the certificate file of Ledger. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-cert --properties ./ledger.as.client.properties + ``` + +1. Register the certificate file of Auditor. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-cert --properties ./auditor.as.client.properties + ``` + +1. Register the certificate file of client. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-cert --properties ./client.properties + ``` + +1. Register the sample contract `StateUpdater`. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id StateUpdater --contract-binary-name com.org1.contract.StateUpdater --contract-class-file ./build/classes/java/main/com/org1/contract/StateUpdater.class + ``` + +1. Register the sample contract `StateReader`. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id StateReader --contract-binary-name com.org1.contract.StateReader --contract-class-file ./build/classes/java/main/com/org1/contract/StateReader.class + ``` + +1. Register the contract `ValdateLedger` to execute a validate request. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id validate-ledger --contract-binary-name com.scalar.dl.client.contract.ValidateLedger --contract-class-file ./build/classes/java/main/com/scalar/dl/client/contract/ValidateLedger.class + ``` + +1. Execute the contract `StateUpdater`. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/execute-contract --properties ./client.properties --contract-id StateUpdater --contract-argument '{"asset_id": "test_asset", "state": 3}' + ``` + This sample contract updates the `state` (value) of the asset named `test_asset` to `3`. + +1. Execute the contract `StateReader`. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/execute-contract --properties ./client.properties --contract-id StateReader --contract-argument '{"asset_id": "test_asset"}' + ``` + [Command execution result] + ```console + Contract result: + { + "id" : "test_asset", + "age" : 0, + "output" : { + "state" : 3 + } + } + ``` + * Reference information + * If the asset data is not tampered with, the contract execution request (execute-contract command) returns `OK` as a result. + * If the asset data is tampered with (e.g. the `state` value in the DB is tampered with), the contract execution request (execute-contract command) returns a value other than `OK` (e.g. `INCONSISTENT_STATES`) as a result, like the following. + [Command execution result (If the asset data is tampered with)] + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + * In this way, the ScalarDL can detect data tampering. + +1. Execute a validation request for the asset. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/validate-ledger --properties ./client.properties --asset-id "test_asset" + ``` + [Command execution result] + ```console + { + "status_code" : "OK", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEYCIQDiiXqzw6K+Ml4uvn8rK43o5wHWESU3hoXnZPi6/OeKVwIhAM+tFBcapl6zg47Uq0Uc8nVNGWNHZLBDBGve3F0xkzTR" + }, + "Auditor" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "3533427d-03cf-41d1-bf95-4d31eb0cb24d", + "hash" : "FiquvtPMKLlxKf4VGoccSAGsi9ptn4ozYVVTwdSzEQ0=", + "signature" : "MEUCIQDLsfUR2PmxSvfpL3YvHJUkz00RDpjCdctkroZKXE8d5QIgH73FQH2e11jfnynD00Pp9DrIG1vYizxDsvxUsMPo9IU=" + } + } + ``` + * Reference information + * If the asset data is not tampered with, the validation request (validate-ledger command) returns `OK` as a result. + * If the asset data is tampered with (e.g. the `state` value in the DB is tampered with), the validation request (validate-ledger command) returns a value other than `OK` (e.g. `INVALID_OUTPUT`) as a result, like the following. + [Command execution result (If the asset data is tampered with)] + ```console + { + "status_code" : "INCONSISTENT_STATES", + "error_message" : "The results from Ledger and Auditor don't match" + } + ``` + * In this way, the ScalarDL Ledger can detect data tampering. + +## Step 9. Delete all resources + +After completing the ScalarDL Ledger tests on the Kubernetes cluster, remove all resources. + +1. Uninstall ScalarDL Ledger, ScalarDL Schema Loader, and PostgreSQL. + ```console + helm uninstall scalardl-ledger schema-loader-ledger postgresql-ledger scalardl-auditor schema-loader-auditor postgresql-auditor + ``` + +1. Remove the Client container. + ``` + kubectl delete pod scalardl-client --force --grace-period 0 + ``` + +1. Remove the working directory and sample files (configuration file, key, and certificate). + ```console + cd ~ + ``` + ```console + rm -rf ~/scalardl-test/ + ``` + +## Further reading + +You can see how to get started with monitoring or logging for Scalar products in the following documents. + +* [Getting Started with Helm Charts (Monitoring using Prometheus Operator)](getting-started-monitoring.mdx) +* [Getting Started with Helm Charts (Logging using Loki Stack)](getting-started-logging.mdx) +* [Getting Started with Helm Charts (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-ledger.mdx b/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-ledger.mdx new file mode 100644 index 00000000..76d4d88e --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/getting-started-scalardl-ledger.mdx @@ -0,0 +1,614 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Getting Started with Helm Charts (ScalarDL Ledger / Ledger only) + +This document explains how to get started with ScalarDL Ledger using Helm Chart on a Kubernetes cluster as a test environment. Here, we assume that you already have a Mac or Linux environment for testing. We use **Minikube** in this document, but the steps we will show should work in any Kubernetes cluster. + +## Requirement + +You need to subscribe to ScalarDL Ledger in the [AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-rzbuhxgvqf4d2) or [Azure Marketplace](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) to get the following container images. + * AWS Marketplace + * scalar-ledger + * scalar-ledger-envoy + * scalardl-schema-loader-ledger + * Azure Marketplace + * scalar-ledger + * scalardl-envoy + * scalardl-schema-loader + +Please refer to the following documents for more details. + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +## What we create + +We will deploy the following components on a Kubernetes cluster as follows. + +``` ++--------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| | +| [Pod] [Pod] [Pod] [Pod] | +| | +| +-------+ +-----------------+ | +| +---> | Envoy | ---+ +---> | ScalarDL Ledger | ---+ | +| | +-------+ | | +-----------------+ | | +| | | | | | +| +--------+ +---------+ | +-------+ | +-------------------+ | +-----------------+ | +------------+ | +| | Client | ---> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | ScalarDL Ledger | ---+---> | PostgreSQL | | +| +--------+ | (Envoy) | | +-------+ | | (ScalarDL Ledger) | | +-----------------+ | +------------+ | +| +---------+ | | +-------------------+ | | | +| | +-------+ | | +-----------------+ | | +| +---> | Envoy | ---+ +---> | ScalarDL Ledger | ---+ | +| +-------+ +-----------------+ | +| | ++--------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## Step 1. Start a Kubernetes cluster + +First, you need to prepare a Kubernetes cluster. If you use a **minikube** environment, please refer to the [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx). If you have already started a Kubernetes cluster, you can skip this step. + +## Step 2. Start a PostgreSQL container + +ScalarDL Ledger uses some kind of database system as a backend database. In this document, we use PostgreSQL. + +You can deploy PostgreSQL on the Kubernetes cluster as follows. + +1. Add the Bitnami helm repository. + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +1. Deploy PostgreSQL. + ```console + helm install postgresql-ledger bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +1. Check if the PostgreSQL container is running. + ```console + kubectl get pod + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + postgresql-ledger-0 1/1 Running 0 11s + ``` + +## Step 3. Create a working directory + +We will create some configuration files and key/certificate files locally. So, create a working directory for them. + +1. Create a working directory. + ```console + mkdir -p ~/scalardl-test/certs/ + ``` + +## Step 4. Create key/certificate files + +Note: In this guide, we will use self-sign certificates for the test. However, it is strongly recommended that these certificates NOT be used in production. + +1. Change the working directory to `~/scalardl-test/certs/` directory. + ```console + cd ~/scalardl-test/certs/ + ``` + +1. Create a JSON file that includes Ledger information. + ```console + cat << 'EOF' > ~/scalardl-test/certs/ledger.json + { + "CN": "ledger", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "ledger", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. Create a JSON file that includes Client information. + ```console + cat << 'EOF' > ~/scalardl-test/certs/client.json + { + "CN": "client", + "hosts": ["example.com","*.example.com"], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "O": "client", + "OU": "test team", + "L": "Shinjuku", + "ST": "Tokyo", + "C": "JP" + } + ] + } + EOF + ``` + +1. Create key/certificate files for the Ledger. + ```console + cfssl selfsign "" ./ledger.json | cfssljson -bare ledger + ``` + +1. Create key/certificate files for the Client. + ```console + cfssl selfsign "" ./client.json | cfssljson -bare client + ``` + +1. Confirm key/certificate files are created. + ```console + ls -1 + ``` + [Command execution result] + ```console + client-key.pem + client.csr + client.json + client.pem + ledger-key.pem + ledger.csr + ledger.json + ledger.pem + ``` + +## Step 5. Create DB schemas for ScalarDL Ledger using Helm Charts + +We will deploy a ScalarDL Schema Loader on the Kubernetes cluster using Helm Charts. +The ScalarDL Schema Loader will create the DB schemas for ScalarDL Ledger in PostgreSQL. + +1. Change the working directory to `~/scalardl-test/`. + ```console + cd ~/scalardl-test/ + ``` + +1. Add the Scalar helm repository. + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +1. Create a secret resource to pull the ScalarDL container images from AWS/Azure Marketplace. + * AWS Marketplace + ```console + kubectl create secret docker-registry reg-ecr-mp-secrets \ + --docker-server=709825985650.dkr.ecr.us-east-1.amazonaws.com \ + --docker-username=AWS \ + --docker-password=$(aws ecr get-login-password --region us-east-1) + ``` + * Azure Marketplace + ```console + kubectl create secret docker-registry reg-acr-secrets \ + --docker-server= \ + --docker-username= \ + --docker-password= + ``` + + Please refer to the following documents for more details. + + * [How to install Scalar products through AWS Marketplace](../scalar-kubernetes/AwsMarketplaceGuide.mdx) + * [How to install Scalar products through Azure Marketplace](../scalar-kubernetes/AzureMarketplaceGuide.mdx) + +1. Create a custom values file for ScalarDL Schema Loader (schema-loader-ledger-custom-values.yaml). + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-schema-loader-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "ledger-credentials-secret" + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/schema-loader-ledger-custom-values.yaml + schemaLoading: + schemaType: "ledger" + image: + repository: "/scalarinc/scalardl-schema-loader" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + secretName: "ledger-credentials-secret" + EOF + ``` + +1. Create a secret resource that includes a username and password for PostgreSQL. + ```console + kubectl create secret generic ledger-credentials-secret \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DL_LEDGER_POSTGRES_PASSWORD=postgres + ``` + +1. Deploy the ScalarDL Schema Loader. + ```console + helm install schema-loader-ledger scalar-labs/schema-loading -f ./schema-loader-ledger-custom-values.yaml + ``` + +1. Check if the ScalarDL Schema Loader pod is deployed and completed. + ```console + kubectl get pod + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + postgresql-ledger-0 1/1 Running 0 11m + schema-loader-ledger-schema-loading-46rcr 0/1 Completed 0 3s + ``` + If the ScalarDL Schema Loader pod is **ContainerCreating** or **Running**, wait for the process will be completed (The STATUS will be **Completed**). + +## Step 6. Deploy ScalarDL Ledger on the Kubernetes cluster using Helm Charts + +1. Create a custom values file for ScalarDL Ledger (scalardl-ledger-custom-values.yaml). + * AWS Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ledgerProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + secretName: "ledger-credentials-secret" + extraVolumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + extraVolumeMounts: + - name: "ledger-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + + * Azure Marketplace + + ```console + cat << 'EOF' > ~/scalardl-test/scalardl-ledger-custom-values.yaml + envoy: + image: + repository: "/scalarinc/scalardl-envoy" + version: "1.3.0" + imagePullSecrets: + - name: "reg-acr-secrets" + + ledger: + image: + repository: "/scalarinc/scalar-ledger" + version: "3.6.0" + imagePullSecrets: + - name: "reg-acr-secrets" + ledgerProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-ledger.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DL_LEDGER_POSTGRES_PASSWORD "" }} + scalar.db.storage=jdbc + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + secretName: "ledger-credentials-secret" + extraVolumes: + - name: "ledger-keys" + secret: + secretName: "ledger-keys" + extraVolumeMounts: + - name: "ledger-keys" + mountPath: "/keys" + readOnly: true + EOF + ``` + +1. Create secret resource `ledger-keys`. + ```console + kubectl create secret generic ledger-keys --from-file=private-key=./certs/ledger-key.pem + ``` + +1. Deploy the ScalarDL Ledger. + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + +1. Check if the ScalarDL Ledger pods are deployed. + ```console + kubectl get pod + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + postgresql-ledger-0 1/1 Running 0 14m + scalardl-ledger-envoy-547bbf7546-6cn88 1/1 Running 0 52s + scalardl-ledger-envoy-547bbf7546-rpg5p 1/1 Running 0 52s + scalardl-ledger-envoy-547bbf7546-x2vlg 1/1 Running 0 52s + scalardl-ledger-ledger-9bdf7f8bd-29bzm 1/1 Running 0 52s + scalardl-ledger-ledger-9bdf7f8bd-9fklw 1/1 Running 0 52s + scalardl-ledger-ledger-9bdf7f8bd-9tw5x 1/1 Running 0 52s + schema-loader-ledger-schema-loading-46rcr 0/1 Completed 0 3m38s + ``` + If the ScalarDL Ledger pods are deployed properly, you can see the STATUS are **Running**. + +1. Check if the ScalarDL Ledger services are deployed. + ```console + kubectl get svc + ``` + [Command execution result] + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 47d + postgresql-ledger ClusterIP 10.109.253.150 5432/TCP 15m + postgresql-ledger-hl ClusterIP None 5432/TCP 15m + scalardl-ledger-envoy ClusterIP 10.106.141.153 50051/TCP,50052/TCP 83s + scalardl-ledger-envoy-metrics ClusterIP 10.108.36.136 9001/TCP 83s + scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 83s + scalardl-ledger-metrics ClusterIP 10.98.4.217 8080/TCP 83s + ``` + If the ScalarDL Ledger services are deployed properly, you can see private IP addresses in the CLUSTER-IP column. (Note: `scalardl-ledger-headless` has no CLUSTER-IP.) + +## Step 7. Start a Client container + +We will use certificate files in a Client container. So, we create a secret resource and mount it to a Client container. + +1. Create secret resource `client-keys`. + ``` + kubectl create secret generic client-keys --from-file=certificate=./certs/client.pem --from-file=private-key=./certs/client-key.pem + ``` + +1. Start a Client container on the Kubernetes cluster. + ```console + cat << 'EOF' | kubectl apply -f - + apiVersion: v1 + kind: Pod + metadata: + name: "scalardl-client" + spec: + containers: + - name: scalardl-client + image: eclipse-temurin:8-jdk + command: ['sleep'] + args: ['inf'] + volumeMounts: + - name: "client-keys" + mountPath: "/keys" + readOnly: true + volumes: + - name: "client-keys" + secret: + secretName: "client-keys" + restartPolicy: Never + EOF + ``` + +1. Check if the Client container is running. + ```console + kubectl get pod scalardl-client + ``` + [Command execution result] + ```console + NAME READY STATUS RESTARTS AGE + scalardl-client 1/1 Running 0 11s + ``` + +## Step 8. Run ScalarDL sample contracts in the Client container + +The following explains the minimum steps. If you want to know more details about ScalarDL and the contract, please refer to the [Getting Started with ScalarDL](https://scalardl.scalar-labs.com/docs/latest/getting-started). + +1. Run bash in the Client container. + ```console + kubectl exec -it scalardl-client -- bash + ``` + After this step, run each command in the Client container. + +1. Install the git, curl and unzip commands in the Client container. + ```console + apt update && apt install -y git curl unzip + ``` + +1. Clone ScalarDL Java Client SDK git repository. + ```console + git clone https://github.com/scalar-labs/scalardl-java-client-sdk.git + ``` + +1. Change the directory to `scalardl-java-client-sdk/`. + ```console + cd scalardl-java-client-sdk/ + ``` + ```console + pwd + ``` + [Command execution result] + ```console + + /scalardl-java-client-sdk + ``` + +1. Change branch to arbitrary version. + ```console + git checkout -b v3.6.0 refs/tags/v3.6.0 + ``` + ```console + git branch + ``` + [Command execution result] + ```console + master + * v3.6.0 + ``` + If you want to use another version, please specify the version (tag) you want to use. You need to use the same version of ScalarDL Ledger and ScalarDL Java Client SDK. + +1. Build the sample contracts. + ```console + ./gradlew assemble + ``` + +1. Download CLI tools of ScalarDL from [ScalarDL Java Client SDK Releases](https://github.com/scalar-labs/scalardl-java-client-sdk/releases). + ```console + curl -OL https://github.com/scalar-labs/scalardl-java-client-sdk/releases/download/v3.6.0/scalardl-java-client-sdk-3.6.0.zip + ``` + You need to use the same version of CLI tools and ScalarDL Ledger. + +1. Unzip the `scalardl-java-client-sdk-3.6.0.zip` file. + ```console + unzip ./scalardl-java-client-sdk-3.6.0.zip + ``` + +1. Create a configuration file (client.properties) to access ScalarDL Ledger on the Kubernetes cluster. + ```console + cat << 'EOF' > client.properties + scalar.dl.client.server.host=scalardl-ledger-envoy.default.svc.cluster.local + scalar.dl.client.cert_holder_id=client + scalar.dl.client.cert_path=/keys/certificate + scalar.dl.client.private_key_path=/keys/private-key + EOF + ``` + +1. Register the certificate file of the client. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-cert --properties ./client.properties + ``` + +1. Register the sample contract `StateUpdater`. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id StateUpdater --contract-binary-name com.org1.contract.StateUpdater --contract-class-file ./build/classes/java/main/com/org1/contract/StateUpdater.class + ``` + +1. Register the sample contract `StateReader`. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/register-contract --properties ./client.properties --contract-id StateReader --contract-binary-name com.org1.contract.StateReader --contract-class-file ./build/classes/java/main/com/org1/contract/StateReader.class + ``` + +1. Execute the contract `StateUpdater`. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/execute-contract --properties ./client.properties --contract-id StateUpdater --contract-argument '{"asset_id": "test_asset", "state": 3}' + ``` + This sample contract updates the `state` (value) of the asset named `test_asset` to `3`. + +1. Execute the contract `StateReader`. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/execute-contract --properties ./client.properties --contract-id StateReader --contract-argument '{"asset_id": "test_asset"}' + ``` + [Command execution result] + ```console + Contract result: + { + "id" : "test_asset", + "age" : 0, + "output" : { + "state" : 3 + } + } + ``` + +1. Execute a validation request for the asset. + ```console + ./scalardl-java-client-sdk-3.6.0/bin/validate-ledger --properties ./client.properties --asset-id "test_asset" + ``` + [Command execution result] + ```console + { + "status_code" : "OK", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "f31599c6-e6b9-4b77-adc3-61cb5f119bd3", + "hash" : "9ExfFl5Lg9IQwdXdW9b87Bi+PWccn3OSNRbhmI/dboo=", + "signature" : "MEQCIG6Xa4WOWGMIIbA3PnCje4aAapYfCMerF54xRW0gaUuzAiBCA1nCAPoFWgxArB34/u9b+KeoxQBMALI/pOzMNoLExg==" + }, + "Auditor" : null + } + ``` + * Reference information + * If the asset data is not tampered with, the validation request (validate-ledger command) returns `OK` as a result. + * If the asset data is tampered with (e.g. the `state` value in the DB is tampered with), the validation request (validate-ledger command) returns a value other than `OK` (e.g. `INVALID_OUTPUT`) as a result, like the following. + [Command execution result (If the asset data is tampered with)] + ```console + { + "status_code" : "INVALID_OUTPUT", + "Ledger" : { + "id" : "test_asset", + "age" : 0, + "nonce" : "f31599c6-e6b9-4b77-adc3-61cb5f119bd3", + "hash" : "9ExfFl5Lg9IQwdXdW9b87Bi+PWccn3OSNRbhmI/dboo=", + "signature" : "MEQCIGtJerW7N93c/bvIBy/7NXxoQwGFznHMmV6RzsgHQg0dAiBu+eBxkfmMQKJY2d9fLNvCH+4b+9rl7gZ3OXJ2NYeVsA==" + }, + "Auditor" : null + } + ``` + * In this way, the ScalarDL Ledger can detect data tampering. + +## Step 9. Delete all resources + +After completing the ScalarDL Ledger tests on the Kubernetes cluster, remove all resources. + +1. Uninstall ScalarDL Ledger, ScalarDL Schema Loader, and PostgreSQL. + ```console + helm uninstall scalardl-ledger schema-loader-ledger postgresql-ledger + ``` + +1. Remove the Client container. + ``` + kubectl delete pod scalardl-client --force --grace-period 0 + ``` + +1. Remove the working directory and sample files (configuration file, key, and certificate). + ```console + cd ~ + ``` + ```console + rm -rf ~/scalardl-test/ + ``` + +## Further reading + +You can see how to get started with monitoring or logging for Scalar products in the following documents. + +* [Getting Started with Helm Charts (Monitoring using Prometheus Operator)](getting-started-monitoring.mdx) +* [Getting Started with Helm Charts (Logging using Loki Stack)](getting-started-logging.mdx) +* [Getting Started with Helm Charts (Scalar Manager)](getting-started-scalar-manager.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalar-admin-for-kubernetes.mdx b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalar-admin-for-kubernetes.mdx new file mode 100644 index 00000000..931a3b46 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalar-admin-for-kubernetes.mdx @@ -0,0 +1,34 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to deploy Scalar Admin for Kubernetes + +This document explains how to deploy Scalar Admin for Kubernetes by using Scalar Helm Charts. For details on the custom values file for Scalar Admin for Kubernetes, see [Configure a custom values file for Scalar Admin for Kubernetes](configure-custom-values-scalar-admin-for-kubernetes.mdx). + +## Deploy Scalar Admin for Kubernetes + +To deploy Scalar Admin for Kubernetes, run the following command, replacing the contents in the angle brackets as described: + +```console +helm install scalar-labs/scalar-admin-for-kubernetes -n -f / --version +``` + +## Upgrade a Scalar Admin for Kubernetes job + +To upgrade a Scalar Admin for Kubernetes job, run the following command, replacing the contents in the angle brackets as described: + +```console +helm upgrade scalar-labs/scalar-admin-for-kubernetes -n -f / --version +``` + +## Delete a Scalar Admin for Kubernetes job + +To delete a Scalar Admin for Kubernetes job, run the following command, replacing the contents in the angle brackets as described: + +```console +helm uninstall -n +``` diff --git a/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalar-products.mdx b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalar-products.mdx new file mode 100644 index 00000000..a9489c1b --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalar-products.mdx @@ -0,0 +1,72 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Deploy Scalar products using Scalar Helm Charts + +This document explains how to deploy Scalar products using Scalar Helm Charts. If you want to test Scalar products on your local environment using a minikube cluster, please refer to the following getting started guide. + +* [Getting Started with Scalar Helm Charts](getting-started-scalar-helm-charts.mdx) + +## Prerequisites + +### Install the helm command + +You must install the helm command to use Scalar Helm Charts. Please install the helm command according to the [Helm document](https://helm.sh/docs/intro/install/). + +### Add the Scalar Helm Charts repository + +```console +helm repo add scalar-labs https://scalar-labs.github.io/helm-charts +``` +```console +helm repo update scalar-labs +``` + +### Prepare a Kubernetes cluster + +You must prepare a Kubernetes cluster for the deployment of Scalar products. If you use EKS (Amazon Elastic Kubernetes Service) or AKS (Azure Kubernetes Service) in the production environment. Please refer to the following document for more details. + +- [Guidelines for creating an Amazon EKS cluster for Scalar products](../scalar-kubernetes/CreateEKSClusterForScalarProducts.mdx) +- [Guidelines for creating an AKS cluster for Scalar products](../scalar-kubernetes/CreateAKSClusterForScalarProducts.mdx) + +You must prepare a supported version of Kubernetes. For versions that Scalar Helm Charts supports, see [Kubernetes](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes). + +### Prepare a database (ScalarDB, ScalarDL Ledger, ScalarDL Auditor) + +You must prepare a database as a backend storage of ScalarDB/ScalarDL. You can see the supported databases by ScalarDB/ScalarDL in the following document. + +* [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) + +### Prepare a custom values file + +You must prepare your custom values file based on your environment. Please refer to the following documents for more details on how to create a custom values file. + +* [Configure a custom values file for Scalar Helm Charts](configure-custom-values-file.mdx) + +### Get the container images + +If you're using commercially licensed Scalar products, you must get the container images of those products. For details, see [How to get the container images of Scalar products](../scalar-kubernetes/HowToGetContainerImages.mdx). + +If you're using any of the following products from the public container repository, you can get the container images from the public container repository with the default configuration of Scalar Helm Chart: + +* Scalar Envoy (deploy with ScalarDB Cluster, ScalarDL Ledger, or ScalarDL Auditor) +* ScalarDL Schema Loader +* Scalar Admin for Kubernetes +* ScalarDB Analytics with PostgreSQL + +## Deploy Scalar products + +Please refer to the following documents for more details on how to deploy each product. + +* [ScalarDB Cluster](how-to-deploy-scalardb-cluster.mdx) +* [ScalarDB Analytics with PostgreSQL](how-to-deploy-scalardb-analytics-postgresql.mdx) +* [ScalarDL Ledger](how-to-deploy-scalardl-ledger.mdx) +* [ScalarDL Auditor](how-to-deploy-scalardl-auditor.mdx) +* [Scalar Admin for Kubernetes](how-to-deploy-scalar-admin-for-kubernetes.mdx) +* [Scalar Manager](getting-started-scalar-manager.mdx) +* [[Deprecated] ScalarDB Server](how-to-deploy-scalardb.mdx) +* [[Deprecated] ScalarDB GraphQL](how-to-deploy-scalardb-graphql.mdx) diff --git a/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-analytics-postgresql.mdx b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-analytics-postgresql.mdx new file mode 100644 index 00000000..fb190064 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-analytics-postgresql.mdx @@ -0,0 +1,41 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# How to deploy ScalarDB Analytics with PostgreSQL + +This document explains how to deploy ScalarDB Analytics with PostgreSQL by using Scalar Helm Charts. For details on the custom values file for ScalarDB Analytics with PostgreSQL, see [Configure a custom values file for ScalarDB Analytics with PostgreSQL](configure-custom-values-scalardb-analytics-postgresql.mdx). + +## Prepare a secret resource + +You must create a secret resource `scalardb-analytics-postgresql-superuser-password` with the key `superuser-password` that includes a superuser password for PostgreSQL before you deploy ScalarDB Analytics with PostgreSQL. Scalar Helm Chart mounts this secret resource and sets the `POSTGRES_PASSWORD` environment variable to the value of the `superuser-password` key. + +```console +kubectl create secret generic scalardb-analytics-postgresql-superuser-password --from-literal=superuser-password= -n +``` + +## Deploy ScalarDB Analytics with PostgreSQL + +To deploy ScalarDB Analytics with PostgreSQL, run the following command, replacing the contents in the angle brackets as described: + +```console +helm install scalar-labs/scalardb-analytics-postgresql -n -f / --version +``` + +## Upgrade a ScalarDB Analytics with PostgreSQL deployment + +To upgrade a ScalarDB Analytics with PostgreSQL deployment, run the following command, replacing the contents in the angle brackets as described: + +```console +helm upgrade scalar-labs/scalardb-analytics-postgresql -n -f / --version +``` + +## Delete a ScalarDB Analytics with PostgreSQL deployment + +To delete a ScalarDB Analytics with PostgreSQL deployment, run the following command, replacing the contents in the angle brackets as described: + +```console +helm uninstall -n +``` diff --git a/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-cluster.mdx b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-cluster.mdx new file mode 100644 index 00000000..1dcc911e --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-cluster.mdx @@ -0,0 +1,74 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to deploy ScalarDB Cluster + +This document explains how to deploy ScalarDB Cluster by using Scalar Helm Charts. For details on the custom values file for ScalarDB Cluster, see [Configure a custom values file for ScalarDB Cluster](configure-custom-values-scalardb-cluster.mdx). + +## Deploy ScalarDB Cluster + +```console +helm install scalar-labs/scalardb-cluster -n -f / --version +``` + +## Upgrade a ScalarDB Cluster deployment + +```console +helm upgrade scalar-labs/scalardb-cluster -n -f / --version +``` + +## Delete a ScalarDB Cluster deployment + +```console +helm uninstall -n +``` + +## Deploy your client application on Kubernetes with `direct-kubernetes` mode + +If you use ScalarDB Cluster with `direct-kubernetes` mode, you must: + +1. Deploy your application pods on the same Kubernetes cluster as ScalarDB Cluster. +2. Create three Kubernetes resources (`Role`, `RoleBinding`, and `ServiceAccount`). +3. Mount the `ServiceAccount` on your application pods. + +This method is necessary because the ScalarDB Cluster client library with `direct-kubernetes` mode runs the Kubernetes API from inside of your application pods to get information about the ScalarDB Cluster pods. + +* Role + ```yaml + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: scalardb-cluster-client-role + namespace: + rules: + - apiGroups: [""] + resources: ["endpoints"] + verbs: ["get", "watch", "list"] + ``` +* RoleBinding + ```yaml + apiVersion: rbac.authorization.k8s.io/v1 + kind: RoleBinding + metadata: + name: scalardb-cluster-client-rolebinding + namespace: + subjects: + - kind: ServiceAccount + name: scalardb-cluster-client-sa + roleRef: + kind: Role + name: scalardb-cluster-role + apiGroup: rbac.authorization.k8s.io + ``` +* ServiceAccount + ```yaml + apiVersion: v1 + kind: ServiceAccount + metadata: + name: scalardb-cluster-client-sa + namespace: + ``` diff --git a/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-graphql.mdx b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-graphql.mdx new file mode 100644 index 00000000..8bb557e6 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb-graphql.mdx @@ -0,0 +1,46 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# [Deprecated] How to deploy ScalarDB GraphQL + +:::note + +ScalarDB GraphQL Server is now deprecated. Please use [ScalarDB Cluster](how-to-deploy-scalardb-cluster.mdx) instead. + +::: + +This document explains how to deploy ScalarDB GraphQL using Scalar Helm Charts. You must prepare your custom values file. Please refer to the following document for more details on the custom values file for ScalarDB GraphQL. + +* [[Deprecated] Configure a custom values file for ScalarDB GraphQL](configure-custom-values-scalardb-graphql.mdx) + +## Deploy ScalarDB Server (recommended option) + +When you deploy ScalarDB GraphQL, it is recommended to deploy ScalarDB Server between ScalarDB GraphQL and backend databases as follows. + +``` +[Client] ---> [ScalarDB GraphQL] ---> [ScalarDB Server] ---> [Backend databases] +``` + +Please deploy ScalarDB Server before you deploy ScalarDB GraphQL according to the document [How to deploy ScalarDB Server](how-to-deploy-scalardb.mdx). + +## Deploy ScalarDB GraphQL + +```console +helm install scalar-labs/scalardb-graphql -n -f / --version +``` + +## Upgrade the deployment of ScalarDB GraphQL + +```console +helm upgrade scalar-labs/scalardb-graphql -n -f / --version +``` + +## Delete the deployment of ScalarDB GraphQL + +```console +helm uninstall -n +``` diff --git a/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb.mdx b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb.mdx new file mode 100644 index 00000000..5acd3200 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardb.mdx @@ -0,0 +1,37 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsEnglish +--- + +# [Deprecated] How to deploy ScalarDB Server + +:::note + +ScalarDB Server is now deprecated. Please use [ScalarDB Cluster](how-to-deploy-scalardb-cluster.mdx) instead. + +::: + +This document explains how to deploy ScalarDB Server using Scalar Helm Charts. You must prepare your custom values file. Please refer to the following document for more details on the custom values file for ScalarDB Server. + +* [[Deprecated] Configure a custom values file for ScalarDB Server](configure-custom-values-scalardb.mdx) + +## Deploy ScalarDB Server + +```console +helm install scalar-labs/scalardb -n -f / --version +``` + +## Upgrade the deployment of ScalarDB Server + +```console +helm upgrade scalar-labs/scalardb -n -f / --version +``` + +## Delete the deployment of ScalarDB Server + +```console +helm uninstall -n +``` diff --git a/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardl-auditor.mdx b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardl-auditor.mdx new file mode 100644 index 00000000..8ee46377 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardl-auditor.mdx @@ -0,0 +1,44 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# How to deploy ScalarDL Auditor + +This document explains how to deploy ScalarDL Auditor using Scalar Helm Charts. You must prepare your custom values file. Please refer to the following document for more details on the custom values file for ScalarDL Auditor and ScalarDL Schema Loader. + +* [Configure a custom values file for ScalarDL Auditor](configure-custom-values-scalardl-auditor.mdx) +* [Configure a custom values file for ScalarDL Schema Loader](configure-custom-values-scalardl-schema-loader.mdx) + +## Prepare a private key file and a certificate file + +When you deploy ScalarDL Auditor, you must create a Secrete resource to mount the private key file and the certificate file on the ScalarDL Auditor pods. + +For more details on how to mount the key and certificate files on the ScalarDL pods, refer to [Mount key and certificate files on a pod in ScalarDL Helm Charts](mount-files-or-volumes-on-scalar-pods.mdx#mount-key-and-certificate-files-on-a-pod-in-scalardl-helm-charts). + +## Create schemas for ScalarDL Auditor (Deploy ScalarDL Schema Loader) + +Before you deploy ScalarDL Auditor, you must create schemas for ScalarDL Auditor on the backend database. + +```console +helm install scalar-labs/schema-loading -n -f / --version +``` + +## Deploy ScalarDL Auditor + +```console +helm install scalar-labs/scalardl-audit -n -f / --version +``` + +## Upgrade the deployment of ScalarDL Auditor + +```console +helm upgrade scalar-labs/scalardl-audit -n -f / --version +``` + +## Delete the deployment of ScalarDL Auditor and ScalarDL Schema Loader + +```console +helm uninstall -n +``` diff --git a/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardl-ledger.mdx b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardl-ledger.mdx new file mode 100644 index 00000000..1b934e47 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/how-to-deploy-scalardl-ledger.mdx @@ -0,0 +1,46 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# How to deploy ScalarDL Ledger + +This document explains how to deploy ScalarDL Ledger using Scalar Helm Charts. You must prepare your custom values file. Please refer to the following document for more details on the custom values file for ScalarDL Ledger and ScalarDL Schema Loader. + +* [Configure a custom values file for ScalarDL Ledger](configure-custom-values-scalardl-ledger.mdx) +* [Configure a custom values file for ScalarDL Schema Loader](configure-custom-values-scalardl-schema-loader.mdx) + +## Prepare a private key file (optional / it is necessary if you use ScalarDL Auditor) + +If you use the [asset proofs](https://scalardl.scalar-labs.com/docs/latest/how-to-write-applications#what-is-asset-proof) of ScalarDL Ledger, you must create a Secrete resource to mount the private key file on the ScalarDL Ledger pods. If you use ScalarDL Auditor, asset proof is necessary. + +Please refer to the following document for more details on how to mount the key/certificate files on the ScalarDL pods. + +* [Mount key and certificate files on a pod in ScalarDL Helm Charts](mount-files-or-volumes-on-scalar-pods.mdx#mount-key-and-certificate-files-on-a-pod-in-scalardl-helm-charts) + +## Create schemas for ScalarDL Ledger (Deploy ScalarDL Schema Loader) + +Before you deploy ScalarDL Ledger, you must create schemas for ScalarDL Ledger on the backend database. + +```console +helm install scalar-labs/schema-loading -n -f / --version +``` + +## Deploy ScalarDL Ledger + +```console +helm install scalar-labs/scalardl -n -f / --version +``` + +## Upgrade the deployment of ScalarDL Ledger + +```console +helm upgrade scalar-labs/scalardl -n -f / --version +``` + +## Delete the deployment of ScalarDL Ledger and ScalarDL Schema Loader + +```console +helm uninstall -n +``` diff --git a/versioned_docs/version-3.15/helm-charts/mount-files-or-volumes-on-scalar-pods.mdx b/versioned_docs/version-3.15/helm-charts/mount-files-or-volumes-on-scalar-pods.mdx new file mode 100644 index 00000000..a8adcce6 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/mount-files-or-volumes-on-scalar-pods.mdx @@ -0,0 +1,143 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Mount any files or volumes on Scalar product pods + +You can mount any files or volumes on Scalar product pods when you use ScalarDB Server, ScalarDB Cluster, ScalarDB Analytics with PostgreSQL, or ScalarDL Helm Charts (ScalarDL Ledger and ScalarDL Auditor). + +## Mount key and certificate files on a pod in ScalarDL Helm Charts + +You must mount the key and certificate files to run ScalarDL Auditor. + +* Configuration example + * ScalarDL Ledger + ```yaml + ledger: + ledgerProperties: | + ... + scalar.dl.ledger.proof.enabled=true + scalar.dl.ledger.auditor.enabled=true + scalar.dl.ledger.proof.private_key_path=/keys/private-key + ``` + * ScalarDL Auditor + ```yaml + auditor: + auditorProperties: | + ... + scalar.dl.auditor.private_key_path=/keys/private-key + scalar.dl.auditor.cert_path=/keys/certificate + ``` + +In this example, you need to mount a **private-key** and a **certificate** file under the `/keys` directory in the container. And, you need to mount files named `private-key` and `certificate`. You can use `extraVolumes` and `extraVolumeMounts` to mount these files. + +1. Set `extraVolumes` and `extraVolumeMounts` in the custom values file using the same syntax of Kubernetes manifest. You need to specify the directory name to the key `mountPath`. + * Example + * ScalarDL Ledger + ```yaml + ledger: + extraVolumes: + - name: ledger-keys + secret: + secretName: ledger-keys + extraVolumeMounts: + - name: ledger-keys + mountPath: /keys + readOnly: true + ``` + * ScalarDL Auditor + ```yaml + auditor: + extraVolumes: + - name: auditor-keys + secret: + secretName: auditor-keys + extraVolumeMounts: + - name: auditor-keys + mountPath: /keys + readOnly: true + ``` + +1. Create a `Secret` resource that includes key and certificate files. + + You need to specify the file name as keys of `Secret`. + + * Example + * ScalarDL Ledger + ```console + kubectl create secret generic ledger-keys \ + --from-file=tls.key=./ledger-key.pem + ``` + * ScalarDL Auditor + ```console + kubectl create secret generic auditor-keys \ + --from-file=tls.key=./auditor-key.pem \ + --from-file=certificate=./auditor-cert.pem + ``` + +1. Deploy Scalar products with the above custom values file. + + After deploying Scalar products, key and certificate files are mounted under the `/keys` directory as follows. + + * Example + * ScalarDL Ledger + ```console + ls -l /keys/ + ``` + + You should see the following output: + + ```console + total 0 + lrwxrwxrwx 1 root root 18 Jun 27 03:12 private-key -> ..data/private-key + ``` + + * ScalarDL Auditor + ```console + ls -l /keys/ + ``` + + You should see the following output: + + ```console + total 0 + lrwxrwxrwx 1 root root 18 Jun 27 03:16 certificate -> ..data/certificate + lrwxrwxrwx 1 root root 18 Jun 27 03:16 private-key -> ..data/private-key + ``` + +## Mount emptyDir to get a heap dump file + +You can mount emptyDir to Scalar product pods by using the following keys in your custom values file. For example, you can use this volume to get a heap dump of Scalar products. + +* Keys + * `scalardb.extraVolumes` / `scalardb.extraVolumeMounts` (ScalarDB Server) + * `scalardbCluster.extraVolumes` / `scalardbCluster.extraVolumeMounts` (ScalarDB Cluster) + * `scalardbAnalyticsPostgreSQL.extraVolumes` / `scalardbAnalyticsPostgreSQL.extraVolumeMounts` (ScalarDB Analytics with PostgreSQL) + * `ledger.extraVolumes` / `ledger.extraVolumeMounts` (ScalarDL Ledger) + * `auditor.extraVolumes` / `auditor.extraVolumeMounts` (ScalarDL Auditor) + +* Example (ScalarDB Server) + ```yaml + scalardb: + extraVolumes: + - name: heap-dump + emptyDir: {} + extraVolumeMounts: + - name: heap-dump + mountPath: /dump + ``` + +In this example, you can see the mounted volume in the ScalarDB Server pod as follows. + +```console +ls -ld /dump +``` + +You should see the following output: + +```console +drwxrwxrwx 2 root root 4096 Feb 6 07:43 /dump +``` diff --git a/versioned_docs/version-3.15/helm-charts/use-secret-for-credentials.mdx b/versioned_docs/version-3.15/helm-charts/use-secret-for-credentials.mdx new file mode 100644 index 00000000..12499460 --- /dev/null +++ b/versioned_docs/version-3.15/helm-charts/use-secret-for-credentials.mdx @@ -0,0 +1,246 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to use Secret resources to pass credentials as environment variables into the properties file + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +You can pass credentials like **username** or **password** as environment variables via a `Secret` resource in Kubernetes. The docker images for previous versions of Scalar products use the `dockerize` command for templating properties files. The docker images for the latest versions of Scalar products get values directly from environment variables. + +Note: You cannot use the following environment variable names in your custom values file since these are used in the Scalar Helm Chart internal. + +```console +HELM_SCALAR_DB_CONTACT_POINTS +HELM_SCALAR_DB_CONTACT_PORT +HELM_SCALAR_DB_USERNAME +HELM_SCALAR_DB_PASSWORD +HELM_SCALAR_DB_STORAGE +HELM_SCALAR_DL_LEDGER_PROOF_ENABLED +HELM_SCALAR_DL_LEDGER_AUDITOR_ENABLED +HELM_SCALAR_DL_LEDGER_PROOF_PRIVATE_KEY_PATH +HELM_SCALAR_DL_AUDITOR_SERVER_PORT +HELM_SCALAR_DL_AUDITOR_SERVER_PRIVILEGED_PORT +HELM_SCALAR_DL_AUDITOR_SERVER_ADMIN_PORT +HELM_SCALAR_DL_AUDITOR_LEDGER_HOST +HELM_SCALAR_DL_AUDITOR_CERT_HOLDER_ID +HELM_SCALAR_DL_AUDITOR_CERT_VERSION +HELM_SCALAR_DL_AUDITOR_CERT_PATH +HELM_SCALAR_DL_AUDITOR_PRIVATE_KEY_PATH +SCALAR_DB_LOG_LEVEL +SCALAR_DL_LEDGER_LOG_LEVEL +SCALAR_DL_AUDITOR_LOG_LEVEL +SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME +SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME +``` + +1. Set environment variable name to the properties configuration in the custom values file. See the following examples based on the product you're using. + + + + ```yaml + scalardbCluster: + scalardbClusterNodeProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + + + ```yaml + scalardbAnalyticsPostgreSQL: + databaseProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + + +

ScalarDB Server 3.8 or later (Apache Commons Text syntax)

+ + ```yaml + scalardb: + databaseProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + +

ScalarDB Server 3.7 or earlier (Go template syntax)

+ + ```yaml + scalardb: + databaseProperties: | + ... + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + ... + ``` +
+ +

ScalarDL Ledger 3.8 or later (Apache Commons Text syntax)

+ + ```yaml + ledger: + ledgerProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + +

ScalarDL Ledger 3.7 or earlier (Go template syntax)

+ + ```yaml + ledger: + ledgerProperties: | + ... + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + ... + ``` +
+ +

ScalarDL Auditor 3.8 or later (Apache Commons Text syntax)

+ + ```yaml + auditor: + auditorProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + +

ScalarDL Auditor 3.7 or earlier (Go template syntax)

+ + ```yaml + auditor: + auditorProperties: | + ... + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + ... + ``` +
+ +

ScalarDL Schema Loader 3.8 or later (Apache Commons Text syntax)

+ + ```yaml + schemaLoading: + databaseProperties: | + ... + scalar.db.username=${env:SCALAR_DB_USERNAME} + scalar.db.password=${env:SCALAR_DB_PASSWORD} + ... + ``` + +

ScalarDL Schema Loader 3.7 or earlier (Go template syntax)

+ + ```yaml + schemaLoading: + databaseProperties: | + ... + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + ... + ``` +
+
+ +1. Create a `Secret` resource that includes credentials. + You need to specify the environment variable name as keys of the `Secret`. + * Example + + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_USERNAME=postgres \ + --from-literal=SCALAR_DB_PASSWORD=postgres + ``` + +1. Set the `Secret` name to the following keys in the custom values file. See the following examples based on the product you're using. + + + + **Key:** `scalardbCluster.secretName` + + ```yaml + scalardbCluster: + secretName: "scalardb-cluster-credentials-secret" + ``` + + + **Key:** `scalardbAnalyticsPostgreSQL.secretName` + + ```yaml + scalardbAnalyticsPostgreSQL: + secretName: "scalardb-analytics-postgresql-credentials-secret" + ``` + + + **Key:** `scalardb.secretName` + + ```yaml + scalardb: + secretName: "scalardb-credentials-secret" + ``` + + + **Key:** `ledger.secretName` + + ```yaml + ledger: + secretName: "ledger-credentials-secret" + ``` + + + **Key:** `auditor.secretName` + + ```yaml + auditor: + secretName: "auditor-credentials-secret" + ``` + + + **Key:** `schemaLoading.secretName` + + ```yaml + schemaLoading: + secretName: "schema-loader-ledger-credentials-secret" + ``` + + + +1. Deploy Scalar products with the above custom values file. + + After deploying Scalar products, the Go template strings (environment variables) are replaced by the values of the `Secret`. + + * Example + * Custom values file + + ```yaml + scalardb: + databaseProperties: | + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.username={{ default .Env.SCALAR_DB_USERNAME "" }} + scalar.db.password={{ default .Env.SCALAR_DB_PASSWORD "" }} + scalar.db.storage=jdbc + ``` + + * Properties file in containers + + ```properties + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb.default.svc.cluster.local:5432/postgres + scalar.db.username=postgres + scalar.db.password=postgres + scalar.db.storage=jdbc + ``` + + If you use Apache Commons Text syntax, Scalar products get values directly from environment variables. diff --git a/versioned_docs/version-3.15/images/data_model.png b/versioned_docs/version-3.15/images/data_model.png new file mode 100644 index 00000000..15a0e4d4 Binary files /dev/null and b/versioned_docs/version-3.15/images/data_model.png differ diff --git a/versioned_docs/version-3.15/images/getting-started-ERD.png b/versioned_docs/version-3.15/images/getting-started-ERD.png new file mode 100644 index 00000000..1a6d13c5 Binary files /dev/null and b/versioned_docs/version-3.15/images/getting-started-ERD.png differ diff --git a/versioned_docs/version-3.15/images/scalardb-architecture.png b/versioned_docs/version-3.15/images/scalardb-architecture.png new file mode 100644 index 00000000..6f22111c Binary files /dev/null and b/versioned_docs/version-3.15/images/scalardb-architecture.png differ diff --git a/versioned_docs/version-3.15/images/scalardb-metadata.png b/versioned_docs/version-3.15/images/scalardb-metadata.png new file mode 100644 index 00000000..49880267 Binary files /dev/null and b/versioned_docs/version-3.15/images/scalardb-metadata.png differ diff --git a/versioned_docs/version-3.15/images/scalardb.png b/versioned_docs/version-3.15/images/scalardb.png new file mode 100644 index 00000000..658486cb Binary files /dev/null and b/versioned_docs/version-3.15/images/scalardb.png differ diff --git a/versioned_docs/version-3.15/images/scalardb_data_model.png b/versioned_docs/version-3.15/images/scalardb_data_model.png new file mode 100644 index 00000000..7a02fa23 Binary files /dev/null and b/versioned_docs/version-3.15/images/scalardb_data_model.png differ diff --git a/versioned_docs/version-3.15/images/software_stack.png b/versioned_docs/version-3.15/images/software_stack.png new file mode 100644 index 00000000..75fba6e6 Binary files /dev/null and b/versioned_docs/version-3.15/images/software_stack.png differ diff --git a/versioned_docs/version-3.15/images/two_phase_commit_load_balancing.png b/versioned_docs/version-3.15/images/two_phase_commit_load_balancing.png new file mode 100644 index 00000000..5cdc26f0 Binary files /dev/null and b/versioned_docs/version-3.15/images/two_phase_commit_load_balancing.png differ diff --git a/versioned_docs/version-3.15/images/two_phase_commit_sequence_diagram.png b/versioned_docs/version-3.15/images/two_phase_commit_sequence_diagram.png new file mode 100644 index 00000000..116ef635 Binary files /dev/null and b/versioned_docs/version-3.15/images/two_phase_commit_sequence_diagram.png differ diff --git a/versioned_docs/version-3.15/index.mdx b/versioned_docs/version-3.15/index.mdx new file mode 100644 index 00000000..8924cb93 --- /dev/null +++ b/versioned_docs/version-3.15/index.mdx @@ -0,0 +1,14 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +image: img/scalardb-social-card-preview.png +hide_table_of_contents: true +title: "" +--- + +import CategoryGrid from '/src/components/Cards/3.15'; + + diff --git a/versioned_docs/version-3.15/manage-backup-and-restore.mdx b/versioned_docs/version-3.15/manage-backup-and-restore.mdx new file mode 100644 index 00000000..a89dea81 --- /dev/null +++ b/versioned_docs/version-3.15/manage-backup-and-restore.mdx @@ -0,0 +1,23 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Back Up and Restore Databases + +This guide explains how to back up and restore databases that are used by ScalarDB. + +## Basic guidelines to back up and restore databases + +Before performing a backup, be sure to read [How to Back Up and Restore Databases Used Through ScalarDB](backup-restore.mdx). + +## Back up databases when using ScalarDB in a Kubernetes environment + +For details on how to back up databases in a Kubernetes environment, see [Back up a NoSQL database in a Kubernetes environment](scalar-kubernetes/BackupNoSQL.mdx). + +## Restore databases when using ScalarDB in a Kubernetes environment + +For details on how to restore databases in a Kubernetes environment, see [Restore databases in a Kubernetes environment](scalar-kubernetes/RestoreDatabase.mdx). diff --git a/versioned_docs/version-3.15/manage-monitor-overview.mdx b/versioned_docs/version-3.15/manage-monitor-overview.mdx new file mode 100644 index 00000000..d120478c --- /dev/null +++ b/versioned_docs/version-3.15/manage-monitor-overview.mdx @@ -0,0 +1,21 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# Monitor Overview + +Scalar Manager is a centralized management and monitoring solution for ScalarDB within Kubernetes cluster environments that allows you to: + +- Check the availability of ScalarDB. +- Schedule or execute pausing jobs that create transactionally consistent periods in the databases used by ScalarDB. +- Check the time-series metrics and logs of ScalarDB through Grafana dashboards. + +For more details about Scalar Manager, see [Scalar Manager Overview](scalar-manager/overview.mdx). + +## Deploy Scalar Manager + +You can deploy Scalar Manager by using a Helm Chart. + +For details on how to deploy Scalar Manager, see [Deploy Scalar Manager](helm-charts/getting-started-scalar-manager.mdx). diff --git a/versioned_docs/version-3.15/manage-overview.mdx b/versioned_docs/version-3.15/manage-overview.mdx new file mode 100644 index 00000000..a58fdea0 --- /dev/null +++ b/versioned_docs/version-3.15/manage-overview.mdx @@ -0,0 +1,26 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Manage Overview + +In this category, you can follow guides to help you manage ScalarDB. + +- For details on how to scale ScalarDB, see [Scale](scalar-kubernetes/HowToScaleScalarDB.mdx). +- For details on how to upgrade ScalarDB, see [Upgrade](scalar-kubernetes/HowToUpgradeScalarDB.mdx). + +## Monitor + +In this sub-category, you can learn how to monitor your ScalarDB deployment. + +For an overview of this sub-category, see [Monitor Overview](manage-monitor-overview.mdx). + +## Back up and restore + +In this sub-category, you can learn how to back up and restore the databases that are connected to your ScalarDB deployment. + +For an overview of this sub-category, see [Back Up and Restore Databases](manage-backup-and-restore.mdx). diff --git a/versioned_docs/version-3.15/migrate-overview.mdx b/versioned_docs/version-3.15/migrate-overview.mdx new file mode 100644 index 00000000..5b67453f --- /dev/null +++ b/versioned_docs/version-3.15/migrate-overview.mdx @@ -0,0 +1,14 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Migrate Overview + +For details on importing your tables or migrating your applications and databases to a ScalarDB-based environment, see the following guides: + +- [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](schema-loader-import.mdx) +- [How to Migrate Your Applications and Databases into a ScalarDB-Based Environment](scalardb-sql/migration-guide.mdx) diff --git a/versioned_docs/version-3.15/multi-storage-transactions.mdx b/versioned_docs/version-3.15/multi-storage-transactions.mdx new file mode 100644 index 00000000..de8da288 --- /dev/null +++ b/versioned_docs/version-3.15/multi-storage-transactions.mdx @@ -0,0 +1,68 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Multi-Storage Transactions + +ScalarDB transactions can span multiple storages or databases while maintaining ACID compliance by using a feature called *multi-storage transactions*. + +This page explains how multi-storage transactions work and how to configure the feature in ScalarDB. + +## How multi-storage transactions work in ScalarDB + +In ScalarDB, the `multi-storage` implementation holds multiple storage instances and has mappings from a namespace name to a proper storage instance. When an operation is executed, the multi-storage transactions feature chooses a proper storage instance from the specified namespace by using the namespace-storage mapping and uses that storage instance. + +## How to configure ScalarDB to support multi-storage transactions + +To enable multi-storage transactions, you need to specify `consensus-commit` as the value for `scalar.db.transaction_manager`, `multi-storage` as the value for `scalar.db.storage`, and configure your databases in the ScalarDB properties file. + +The following is an example of configurations for multi-storage transactions: + +```properties +# Consensus Commit is required to support multi-storage transactions. +scalar.db.transaction_manager=consensus-commit + +# Multi-storage implementation is used for Consensus Commit. +scalar.db.storage=multi-storage + +# Define storage names by using a comma-separated format. +# In this case, "cassandra" and "mysql" are used. +scalar.db.multi_storage.storages=cassandra,mysql + +# Define the "cassandra" storage. +# When setting storage properties, such as `storage`, `contact_points`, `username`, and `password`, for multi-storage transactions, the format is `scalar.db.multi_storage.storages..`. +# For example, to configure the `scalar.db.contact_points` property for Cassandra, specify `scalar.db.multi_storage.storages.cassandra.contact_point`. +scalar.db.multi_storage.storages.cassandra.storage=cassandra +scalar.db.multi_storage.storages.cassandra.contact_points=localhost +scalar.db.multi_storage.storages.cassandra.username=cassandra +scalar.db.multi_storage.storages.cassandra.password=cassandra + +# Define the "mysql" storage. +# When defining JDBC-specific configurations for multi-storage transactions, you can follow a similar format of `scalar.db.multi_storage.storages..`. +# For example, to configure the `scalar.db.jdbc.connection_pool.min_idle` property for MySQL, specify `scalar.db.multi_storage.storages.mysql.jdbc.connection_pool.min_idle`. +scalar.db.multi_storage.storages.mysql.storage=jdbc +scalar.db.multi_storage.storages.mysql.contact_points=jdbc:mysql://localhost:3306/ +scalar.db.multi_storage.storages.mysql.username=root +scalar.db.multi_storage.storages.mysql.password=mysql +# Define the JDBC-specific configurations for the "mysql" storage. +scalar.db.multi_storage.storages.mysql.jdbc.connection_pool.min_idle=5 +scalar.db.multi_storage.storages.mysql.jdbc.connection_pool.max_idle=10 +scalar.db.multi_storage.storages.mysql.jdbc.connection_pool.max_total=25 + +# Define namespace mapping from a namespace name to a storage. +# The format is ":,...". +scalar.db.multi_storage.namespace_mapping=user:cassandra,coordinator:mysql + +# Define the default storage that's used if a specified table doesn't have any mapping. +scalar.db.multi_storage.default_storage=cassandra +``` + +For additional configurations, see [ScalarDB Configurations](configurations.mdx). + +## Hands-on tutorial + +For a hands-on tutorial, see [Create a Sample Application That Supports Multi-Storage Transactions](scalardb-samples/multi-storage-transaction-sample/README.mdx). diff --git a/versioned_docs/version-3.15/overview.mdx b/versioned_docs/version-3.15/overview.mdx new file mode 100644 index 00000000..e7a2532e --- /dev/null +++ b/versioned_docs/version-3.15/overview.mdx @@ -0,0 +1,77 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Overview + +This page describes what ScalarDB is and its primary use cases. + +## What is ScalarDB? + +ScalarDB is a universal hybrid transaction/analytical processing (HTAP) engine for diverse databases. It runs as middleware on databases and virtually unifies diverse databases by achieving ACID transactions and real-time analytics across them to simplify the complexity of managing multiple databases or multiple instances of a single database. + +![How ScalarDB simplifies complex data management architecture.](images/scalardb.png) + +As a versatile solution, ScalarDB supports a range of databases, including: + +- Relational databases that support JDBC, such as MariaDB, Microsoft SQL Server, MySQL, Oracle Database, PostgreSQL, SQLite, and their compatible databases, like Amazon Aurora and YugabyteDB. +- NoSQL databases like Amazon DynamoDB, Apache Cassandra, and Azure Cosmos DB. + +For details on which databases ScalarDB supports, refer to [Databases](requirements.mdx#databases). + +## Why ScalarDB? + +Several solutions, such as global transaction managers, data federation engines, and HTAP systems, have similar goals, but they are limited in the following perspectives: + +- Global transaction managers (like Oracle MicroTx and Atomikos) are designed to run transactions across a limited set of heterogeneous databases (like only XA-compliant databases). +- Data federation engines (like Denodo and Starburst) are designed to run analytical queries across heterogeneous databases. +- HTAP systems (like TiDB and SingleStore) run both transactions and analytical queries only on homogeneous databases. + +In other words, they virtually unify databases, but with limitations. For example, with data federation engines, users can run read-only analytical queries on a virtualized view across multiple databases. However, they often need to run update queries separately for each database. + +Unlike other solutions, ScalarDB stands out by offering the ability to run both transactional and analytical queries on heterogeneous databases, which can significantly simplify database management. + +The following table summarizes how ScalarDB is different from the other solutions. + +| | Transactions across heterogeneous databases | Analytics across heterogeneous databases | +| :------------------------------------------------------------: | :------------------------------------------------------------------: | :--------------------------------------: | +| Global transaction managers (like Oracle MicroTx and Atomikos) | Yes (but existing solutions support only a limited set of databases) | No | +| Data federation engines (like Denodo and Starburst) | No | Yes | +| HTAP systems (like TiDB and SingleStore) | No (support homogeneous databases only) | No (support homogeneous databases only) | +| **ScalarDB** | **Yes (supports various databases)** | **Yes** | + + +## ScalarDB use cases + +ScalarDB can be used in various ways. Here are the three primary use cases of ScalarDB. + +### Managing siloed databases easily +Many enterprises comprise several organizations, departments, and business units to support agile business operations, which often leads to siloed information systems. In particular, different organizations likely manage different applications with different databases. Managing such siloed databases is challenging because applications must communicate with each database separately and properly deal with the differences between databases. + +ScalarDB simplifies the management of siloed databases with a unified interface, enabling users to treat the databases as if they were a single database. For example, users can run (analytical) join queries over multiple databases without interacting with the databases respectively. + +### Managing consistency between multiple database +Modern architectures, like the microservice architecture, encourage a system to separate a service and its database into smaller subsets to increase system modularity and development efficiency. However, managing diverse databases, especially of different kinds, is challenging because applications must ensure the correct states (or, in other words, consistencies) of those databases, even using transaction management patterns like Saga and TCC. + +ScalarDB simplifies managing such diverse databases with a correctness guarantee (or, in other words, ACID with strict serializability), enabling you to focus on application development without worrying about guaranteeing consistency between databases. + +### Simplifying data management in a data mesh + +Enterprises have been investing their time in building [data meshes](https://martinfowler.com/articles/data-mesh-principles.html) to streamline and scale data utilization. However, constructing a data mesh is not necessarily easy. For example, there are many technical issues in how to manage decentralized data. + +ScalarDB simplifies the management of decentralized databases in a data mesh, for example, by providing a unified API for all the databases in a data mesh to align with the data-as-a-product principle easily. + +### Reducing database migration hurdles + +Applications tend to be locked into using a certain database because of the specific capabilities that the database provides. Such database lock-in discourages upgrading or changing the database because doing so often requires rewriting the application. + +ScalarDB provides a unified interface for diverse databases. Thus, once an application is written by using the ScalarDB interface, it becomes portable, which helps to achieve seamless database migration without rewriting the application. + +## Further reading + +- [ScalarDB Technical Overview](https://speakerdeck.com/scalar/scalar-db-universal-transaction-manager) +- [ScalarDB Research Paper [VLDB'23]](https://dl.acm.org/doi/10.14778/3611540.3611563) \ No newline at end of file diff --git a/versioned_docs/version-3.15/quickstart-overview.mdx b/versioned_docs/version-3.15/quickstart-overview.mdx new file mode 100644 index 00000000..50647c79 --- /dev/null +++ b/versioned_docs/version-3.15/quickstart-overview.mdx @@ -0,0 +1,41 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Quickstart Overview + +In this category, you can follow quickstart tutorials for how to get started with running transactions and queries through ScalarDB. + +## Try running transactions through the ScalarDB Core library + +In this sub-category, you can follow tutorials on how to run ACID transactions through the ScalarDB Core library, which is publicly available under the Apache 2 License. + +For an overview of this sub-category, see [ScalarDB Core Quickstart Overview](quickstart-scalardb-core-overview.mdx). + +## Try running transactions through ScalarDB Cluster + +In this sub-category, you can see tutorials on how to run ACID transactions through ScalarDB Cluster, which is a [gRPC](https://grpc.io/) server that wraps the ScalarDB Core library. + +For an overview of this sub-category, see [ScalarDB Cluster Quickstart Overview](quickstart-scalardb-cluster-overview.mdx). + +:::note + +ScalarDB Cluster is available only in the Enterprise edition. + +::: + +## Try running analytical queries through ScalarDB Analytics + +In this sub-category, you can see tutorials on how to run analytical queries over the databases that you write through ScalarDB by using a component called ScalarDB Analytics. ScalarDB Analytics targets both ScalarDB-managed databases, which are updated through ScalarDB transactions, and non-ScalarDB-managed databases. + +For an overview of this sub-category, see [ScalarDB Analytics Quickstart Overview](quickstart-scalardb-analytics-overview.mdx). + +:::note + +- ScalarDB Analytics with PostgreSQL is available only under the Apache 2 License and doesn't require a commercial license. + +::: diff --git a/versioned_docs/version-3.15/quickstart-scalardb-analytics-overview.mdx b/versioned_docs/version-3.15/quickstart-scalardb-analytics-overview.mdx new file mode 100644 index 00000000..6b3bc3ec --- /dev/null +++ b/versioned_docs/version-3.15/quickstart-scalardb-analytics-overview.mdx @@ -0,0 +1,13 @@ +--- +tags: + - Community + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# ScalarDB Analytics Quickstart Overview + +In this sub-category, you can see tutorials on how to run analytical queries over the databases that you write through ScalarDB by using a component called ScalarDB Analytics. + +- To try running analytical queries through PostgreSQL, see [Getting Started with ScalarDB Analytics with PostgreSQL](scalardb-analytics-postgresql/getting-started.mdx). +- To try running analytical queries through Spark, see [Getting Started with ScalarDB Analytics](scalardb-samples/scalardb-analytics-spark-sample/README.mdx). diff --git a/versioned_docs/version-3.15/quickstart-scalardb-cluster-overview.mdx b/versioned_docs/version-3.15/quickstart-scalardb-cluster-overview.mdx new file mode 100644 index 00000000..6d5538ca --- /dev/null +++ b/versioned_docs/version-3.15/quickstart-scalardb-cluster-overview.mdx @@ -0,0 +1,15 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster Quickstart Overview + +In this sub-category, you can see tutorials on how to run ACID transactions through ScalarDB Cluster, which is a [gRPC](https://grpc.io/) server that wraps the ScalarDB Core library. + +- To try running transactions, see [Getting Started with ScalarDB Cluster](scalardb-cluster/getting-started-with-scalardb-cluster.mdx). +- To try running transactions through the SQL interface via JDBC, see [Getting Started with ScalarDB Cluster SQL via JDBC](scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx). +- To try running transactions through the SQL interface via Spring Data JDBC, see [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx). +- To try running transactions through the GraphQL interface, see [Getting Started with ScalarDB Cluster GraphQL](scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx). diff --git a/versioned_docs/version-3.15/quickstart-scalardb-core-overview.mdx b/versioned_docs/version-3.15/quickstart-scalardb-core-overview.mdx new file mode 100644 index 00000000..36a59c55 --- /dev/null +++ b/versioned_docs/version-3.15/quickstart-scalardb-core-overview.mdx @@ -0,0 +1,14 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Core Quickstart Overview + +In this sub-category, you can follow tutorials on how to run ACID transactions through the ScalarDB Core library, which is publicly available under the Apache 2 license. + +- To try running transactions, see [Getting Started with ScalarDB](getting-started-with-scalardb.mdx). +- To try running transactions by using Kotlin, see [Getting Started with ScalarDB by Using Kotlin](getting-started-with-scalardb-by-using-kotlin.mdx). diff --git a/versioned_docs/version-3.15/releases/release-notes.mdx b/versioned_docs/version-3.15/releases/release-notes.mdx new file mode 100644 index 00000000..b3a4ebaf --- /dev/null +++ b/versioned_docs/version-3.15/releases/release-notes.mdx @@ -0,0 +1,157 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB 3.15 Release Notes + +This page includes a list of release notes for ScalarDB 3.15. + +## v3.15.4 + +**Release date:** June 21, 2025 + +### Summary + +This release includes fixes for vulnerabilities and bugs. + +### Community edition + +#### Bug fixes + +- Add exception handling for DateTimeParseException on column value conversion. ([#2662](https://github.com/scalar-labs/scalardb/pull/2662)) +- Upgraded the PostgreSQL driver to fix security issues. [CVE-2025-49146](https://github.com/advisories/GHSA-hq9p-pm7w-8p54 "CVE-2025-49146") ([#2772](https://github.com/scalar-labs/scalardb/pull/2772)) +- Fixed potential connection leak when using `jdbc` storage and Scan operation fails because the target table doesn't exist. ([#2766](https://github.com/scalar-labs/scalardb/pull/2766)) + +### Enterprise edition + +#### Bug fixes + +##### ScalarDB Cluster + +- Fixed a memory leak issue when the coordinator group commit feature is enabled. +- Upgraded the OpenSearch Java client to fix a security issue. [CVE-2025-27820](https://github.com/advisories/GHSA-73m2-qfq3-56cx "CVE-2025-27820") + +## v3.15.3 + +**Release date:** May 15, 2025 + +### Summary + +This release includes fixes for vulnerabilities and bugs, and adds support for running ScalarDB Cluster on the Omnistrate service. + +### Community edition + +#### Bug fixes + +- Fixed an issue with `DistributedStorageAdmin.getNamespaceNames()` API when using the DynamoDB storage with the namespace prefix setting `scalar.db.dynamo.namespace.prefix`. The namespace names returned by this method wrongly contained the prefix. ([#2641](https://github.com/scalar-labs/scalardb/pull/2641)) + +### Enterprise edition + +#### Improvements + +##### ScalarDB Cluster + +- Added support for the Omnistrate service. Now, you can run ScalarDB Cluster in the Omnistrate service. + +#### Bug fixes + +##### ScalarDB Cluster + +- Upgraded `grpc_health_probe` to fix a security issue. [CVE-2025-22869](https://github.com/advisories/GHSA-hcg3-q754-cr77) + +## v3.15.2 + +**Release date:** March 24, 2025 + +### Summary + +This release has several improvements and bug fixes. + +### Community edition + +#### Improvements + +- ScalarDB BIGINT datatype will now be mapped to Oracle's NUMBER(16). ([#2566](https://github.com/scalar-labs/scalardb/pull/2566)) + +#### Bug fixes + +- Upgraded the Netty library to fix a security issue. [CVE-2025-24970](https://github.com/advisories/GHSA-4g8c-wm8x-jfhw "CVE-2025-24970") ([#2552](https://github.com/scalar-labs/scalardb/pull/2552)) + +### Enterprise edition + +#### Enhancements + +##### ScalarDB Cluster + +- Added a configuration option (`scalar.db.transaction.enabled`) to enable or disable the transaction feature in ScalarDB Cluster. The default value is `true`. + +#### Bug fixes + +##### ScalarDB Cluster + +- Fixed a bug related to the metadata cache behavior when using auth in the SQL interface. +- Fixed configurations for the embedding feature. +- Fixed a bug that allowed superusers to execute ABAC administrative operations for non-existing users. +- Fixed a bug a table-not-found error occurs when dropping empty ABAC system tables. + +## v3.15.1 + +**Release date:** February 20, 2025 + +### Summary + +This release includes numerous enhancements, improvements, and bug fixes. The [3.15.0 release](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.0) has been discarded, making this the first official release for 3.15. + +### Community edition + +#### Enhancements + +- Introduced operation attributes, providing the capability to include additional key-value information in operations. ([#2333](https://github.com/scalar-labs/scalardb/pull/2333)) +- Add the new time-related data types DATE, TIME, TIMESTAMP, and TIMESTAMPTZ. ([#2468](https://github.com/scalar-labs/scalardb/pull/2468) [#2491](https://github.com/scalar-labs/scalardb/pull/2491)) + +#### Improvements + +- ScalarDB now supports MySQL 8.4, 8.0; PostgreSQL 17, 16, 15, 14, and 13; Amazon Aurora PostgreSQL 16, 15, 14, and 13; Amazon Aurora MySQL 3, and 2. ([#2302](https://github.com/scalar-labs/scalardb/pull/2302)) +- Use the MariaDB Connector/J JDBC driver for any connection URL starting with `jdbc:mariadb` ([#2391](https://github.com/scalar-labs/scalardb/pull/2391)) +- Removed unnecessary loggings in the statement handlers for Cassandra and Cosmos DB. ([#2469](https://github.com/scalar-labs/scalardb/pull/2469)) + +#### Bug fixes + +- Added validation for primary key columns in the Cosmos DB adapter. The validation ensures that the text values of the primary key columns do not contain illegal characters (`:`, `/`, `\`, `#`, and `?`). ([#2292](https://github.com/scalar-labs/scalardb/pull/2292)) +- Fixed the behavior of multiple mutations for the same record in a transaction in Consensus Commit. ([#2340](https://github.com/scalar-labs/scalardb/pull/2340)) +- Fixed the behavior when deleting a non-existing record in the Cosmos adapter. ([#2341](https://github.com/scalar-labs/scalardb/pull/2341)) +- Fixed bugs in GetBuilder and ScanBuilder. ([#2352](https://github.com/scalar-labs/scalardb/pull/2352)) + +### Enterprise edition + +#### Enhancements + +##### ScalarDB Cluster + +- Added support for operation attributes introduced in [#2333](https://github.com/scalar-labs/scalardb/pull/2333) to ScalarDB Cluster. +- Added the attribute-based access control feature. +- Added support for the time-related types introduced in [#2468](https://github.com/scalar-labs/scalardb/pull/2468) to ScalarDB Cluster. +- Added support for the metadata API for ABAC introduced in [scalar-labs/scalardb-sql#708](https://github.com/scalar-labs/scalardb-sql/pull/708). +- Added vector search capability to ScalarDB Cluster by integrating LangChain4j. + +##### ScalarDB SQL + +- Added support for operation attributes to DMLs. Also added support for read tags and write tags in ABAC to DMSs. +- Support the time-related types DATE, TIME, TIMESTAMP, and TIMESTAMPTZ. +- Added metadata API for ABAC. +- Added SQL statements for ABAC. + +#### Bug fixes + +##### ScalarDB Cluster + +- Upgraded `grpc_health_probe` to fix security issues. [CVE-2024-45337](https://github.com/advisories/GHSA-v778-237x-gjrc "CVE-2024-45337") [CVE-2024-45338](https://github.com/advisories/GHSA-w32m-9786-jp63 "CVE-2024-45338") + +##### ScalarDB SQL + +- [Spring Data JDBC For ScalarDB] Fixed a bug `existsById()` API not working +- Fix an issue causing the SQL statement parser to reject negative numeric literal for columns of type INT and BIGINT. diff --git a/versioned_docs/version-3.15/releases/release-support-policy.mdx b/versioned_docs/version-3.15/releases/release-support-policy.mdx new file mode 100644 index 00000000..b802fb49 --- /dev/null +++ b/versioned_docs/version-3.15/releases/release-support-policy.mdx @@ -0,0 +1,118 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Release Support Policy + +This page describes Scalar's support policy for major and minor version releases of ScalarDB. + +## Terms and definitions + +- **Maintenance Support:** Scalar will provide product updates, including code fixes and documentation, and technical support through its [support portal](https://support.scalar-labs.com/) to customers with a commercial license, until the date specified. +- **Assistance Support:** Scalar will provide limited technical support for non-code-related questions in the form of FAQs and inquiries through its [support portal](https://support.scalar-labs.com/) to customers with a commercial license until the date specified. +- **Extended Support:** Extended Support is available as an add-on for customers with a commercial license who want support for a version that is no longer under Maintenance Support or Assistance Support. + +## Release support timelines + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
VersionRelease DateMaintenance Support EndsAssistance Support EndsExtended Support
3.152025-02-202026-06-202026-12-17Contact us
3.142024-11-222026-02-202026-08-18Contact us
3.132024-07-082025-11-222026-05-21Contact us
3.122024-02-172025-07-082026-01-04Contact us
3.112023-12-272025-02-162025-08-15Contact us
3.102023-07-202024-12-262025-06-24Contact us
3.9*2023-04-272024-07-192025-01-15Contact us
3.8*2023-01-172024-04-262024-10-23Contact us
3.7*2022-09-032024-01-172024-07-15Contact us
3.6*2022-07-082023-09-032024-03-01Contact us
3.5*2022-02-162023-07-082024-01-04Contact us
3.4*2021-12-022023-02-162023-08-15Contact us
+ +\* This product version is no longer supported under Maintenance Support or Assistance Support. diff --git a/versioned_docs/version-3.15/requirements.mdx b/versioned_docs/version-3.15/requirements.mdx new file mode 100644 index 00000000..838b9715 --- /dev/null +++ b/versioned_docs/version-3.15/requirements.mdx @@ -0,0 +1,254 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Requirements + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This page describes the required tools and their versions to use ScalarDB correctly. + +## Client SDK + +Because ScalarDB is written in Java, the easiest way to interact with ScalarDB is to use the Java client SDKs: + +- [SDK for ScalarDB Core](add-scalardb-to-your-build.mdx) +- [SDK for ScalarDB Cluster](scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx) + +### Java + +The following Java Development Kits (JDKs) are verified and supported. + +- **[Oracle JDK](https://www.oracle.com/java/):** 8, 11, 17 or 21 (LTS versions) +- **[OpenJDK](https://openjdk.org/) ([Eclipse Temurin](https://adoptium.net/temurin/), [Amazon Corretto](https://aws.amazon.com/corretto/), or [Microsoft Build of OpenJDK](https://learn.microsoft.com/en-us/java/openjdk/)):** 8, 11, 17, or 21 (LTS versions) + +### .NET + +ScalarDB is provided as a gRPC server called ScalarDB Cluster, which also has a [.NET client SDK](scalardb-cluster-dotnet-client-sdk/index.mdx) that wraps the .NET client generated from the proto file. + +The following .NET versions are verified and supported: + +- [.NET 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) +- [.NET 6.0](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) + +### Other languages + +ScalarDB Cluster uses gRPC version 1.65.0, so you can create your own client by using the generated clients of your preferred languages. + +## Databases + +ScalarDB is middleware that runs on top of the following databases and their versions. + +### Relational databases + + + + +| Version | Oracle Database 23ai | Oracle Database 21c | Oracle Database 19c | +|:------------------|:--------------------|:------------------|:------------------| +| **ScalarDB 3.15** | ✅ | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | ✅ | + + + + +| Version | MySQL 8.4 | MySQL 8.0 | +|:------------------|:----------|:-----------| +| **ScalarDB 3.15** | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | + + + + +| Version | PostgreSQL 17 | PostgreSQL 16 | PostgreSQL 15 | PostgreSQL 14 | PostgreSQL 13 | +|:------------------|:--------------|:--------------|:--------------|:--------------|---------------| +| **ScalarDB 3.15** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | ✅ | ✅ | ✅ | + + + + +| Version | Aurora MySQL 3 | Aurora MySQL 2 | +|:------------------|:----------------|:----------------| +| **ScalarDB 3.15** | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | + + + + +| Version | Aurora PostgreSQL 16 | Aurora PostgreSQL 15 | Aurora PostgreSQL 14 | Aurora PostgreSQL 13 | +|:------------------|:---------------------|:---------------------|:---------------------|:---------------------| +| **ScalarDB 3.15** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | ✅ | ✅ | + + + + +| Version | MariaDB 11.4 | MariaDB 10.11 | +|:------------------|:--------------|:--------------| +| **ScalarDB 3.15** | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | + + + + +| Version | SQL Server 2022 | SQL Server 2019 | SQL Server 2017 | +|:------------------|:-----------------|:-----------------|:-----------------| +| **ScalarDB 3.15** | ✅ | ✅ | ✅ | +| **ScalarDB 3.14** | ✅ | ✅ | ✅ | +| **ScalarDB 3.13** | ✅ | ✅ | ✅ | +| **ScalarDB 3.12** | ✅ | ✅ | ✅ | +| **ScalarDB 3.11** | ✅ | ✅ | ✅ | +| **ScalarDB 3.10** | ✅ | ✅ | ✅ | +| **ScalarDB 3.9** | ✅ | ✅ | ✅ | +| **ScalarDB 3.8** | ✅ | ✅ | ✅ | +| **ScalarDB 3.7** | ✅ | ✅ | ✅ | + + + + +| Version | SQLite 3 | +|:------------------|:----------| +| **ScalarDB 3.15** | ✅ | +| **ScalarDB 3.14** | ✅ | +| **ScalarDB 3.13** | ✅ | +| **ScalarDB 3.12** | ✅ | +| **ScalarDB 3.11** | ✅ | +| **ScalarDB 3.10** | ✅ | +| **ScalarDB 3.9** | ✅ | +| **ScalarDB 3.8** | ❌ | +| **ScalarDB 3.7** | ❌ | + + + + +| Version | YugabyteDB 2 | +|:------------------|:-------------| +| **ScalarDB 3.15** | ✅ | +| **ScalarDB 3.14** | ✅ | +| **ScalarDB 3.13** | ✅ | +| **ScalarDB 3.12** | ❌ | +| **ScalarDB 3.11** | ❌ | +| **ScalarDB 3.10** | ❌ | +| **ScalarDB 3.9** | ❌ | +| **ScalarDB 3.8** | ❌ | +| **ScalarDB 3.7** | ❌ | + + + + +### NoSQL databases + + + + +| Version | DynamoDB | +|:------------------|:----------| +| **ScalarDB 3.15** | ✅ | +| **ScalarDB 3.14** | ✅ | +| **ScalarDB 3.13** | ✅ | +| **ScalarDB 3.12** | ✅ | +| **ScalarDB 3.11** | ✅ | +| **ScalarDB 3.10** | ✅ | +| **ScalarDB 3.9** | ✅ | +| **ScalarDB 3.8** | ✅ | +| **ScalarDB 3.7** | ✅ | + + + + +| Version | Cassandra 4.1 | Cassandra 4.0 | Cassandra 3.11 | Cassandra 3.0 | +|:------------------|:---------------|:---------------|:----------------|:---------------| +| **ScalarDB 3.15** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.14** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.13** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.12** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.11** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.10** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.9** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.8** | ❌ | ❌ | ✅ | ✅ | +| **ScalarDB 3.7** | ❌ | ❌ | ✅ | ✅ | + + + + +| Version | Cosmos DB for NoSQL | +|:------------------|:---------------------| +| **ScalarDB 3.15** | ✅ | +| **ScalarDB 3.14** | ✅ | +| **ScalarDB 3.13** | ✅ | +| **ScalarDB 3.12** | ✅ | +| **ScalarDB 3.11** | ✅ | +| **ScalarDB 3.10** | ✅ | +| **ScalarDB 3.9** | ✅ | +| **ScalarDB 3.8** | ✅ | +| **ScalarDB 3.7** | ✅ | + + + + +:::note + +For details on how to configure each database, see [Configurations for the Underlying Databases of ScalarDB](./database-configurations.mdx). + +::: + +## Kubernetes + +ScalarDB is provided as a Pod on the Kubernetes platform in production environments. ScalarDB supports the following platforms and tools. + +### Platform +- **[Kubernetes](https://kubernetes.io/):** 1.28 - 1.32 + - **[Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/)** + - **[Azure Kubernetes Service (AKS)](https://azure.microsoft.com/en-us/products/kubernetes-service)** +- **[Red Hat OpenShift](https://www.redhat.com/en/technologies/cloud-computing/openshift):** TBD + +### Package manager +- **[Helm](https://helm.sh/):** 3.5+ diff --git a/versioned_docs/version-3.15/roadmap.mdx b/versioned_docs/version-3.15/roadmap.mdx new file mode 100644 index 00000000..b195d884 --- /dev/null +++ b/versioned_docs/version-3.15/roadmap.mdx @@ -0,0 +1,135 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Roadmap + +This roadmap provides a look into the proposed future of ScalarDB. The purpose of this roadmap is to provide visibility into what changes may be coming so that you can more closely follow progress, learn about key milestones, and give feedback during development. This roadmap will be updated as new versions of ScalarDB are released. + +:::warning + +During the course of development, this roadmap is subject to change based on user needs and feedback. **Do not schedule your release plans according to the contents of this roadmap.** + +If you have a feature request or want to prioritize feature development, please create an issue in [GitHub](https://github.com/scalar-labs/scalardb/issues). + +::: + + +### CY2025 Q2 + + +#### Support for additional databases + +- **IBM Db2** + - Users will be able to use IBM Db2 as an underlying database through ScalarDB Cluster. +- **TiDB** + - Users will be able to use TiDB as an underlying database through ScalarDB Cluster. +- **Databricks** + - Users will be able to use Databricks as an underlying database through ScalarDB Cluster and ScalarDB Analytics. +- **Snowflake** + - Users will be able to use Snowflake as an underlying database through ScalarDB Cluster and ScalarDB Analytics. + +#### Usability + +- **Addition of decimal data types** + - Users will be able to use decimal data types so that users can handle decimal numbers with high precision. +- **Removal of extra-write strategy** + - Users will no longer be able to use the extra-write strategy to make transactions serializable. Although ScalarDB currently provides two strategies (extra-read and extra-write strategies) to make transactions serializable, the extra-write strategy has several limitations. For example, users can't issue write and scan operations in the same transaction. Therefore, the strategy will be removed so that users don't need to worry about such limitations when creating applications. +- **Better governance in ScalarDB Analytics** + - Users will be able to be authenticated and authorized by using the ScalarDB Core features. + +#### Performance + +- **Addition of read-committed isolation** + - Users will be able to run transactions with a read-committed isolation to achieve better performance for applications that do not require strong correctness. +- **One-phase commit optimization** + - Users will be able to run a transaction more efficiently by using one-phase commit if the operations of the transaction are all applied to a single database or a single partition. +- **Optimization for multiple write operations per database** + - Users will be able to run transactions more efficiently with a batch preparation and commitment if there are multiple write operations for a database. +- **Optimization for read-only transactions** + - Users will be able to run transactions more efficiently by avoiding coordinator writes when committing transactions. +- **Removal of WAL-interpreted views in ScalarDB Analytics** + - Users will be able to read committed data by using ScalarDB Core instead of WAL-interpreted views, which will increase query performance. + +#### Cloud support + +- **Container offering in Azure Marketplace for ScalarDB Cluster** + - Users will be able to deploy ScalarDB Cluster by using the Azure container offering, which enables users to use a pay-as-you-go subscription model. +- **Google Cloud Platform (GCP) support for ScalarDB Cluster** + - Users will be able to deploy ScalarDB Cluster in Google Kubernetes Engine (GKE) in GCP. +- **Container offering in Amazon Marketplace for ScalarDB Analytics** + - Users will be able to deploy ScalarDB Analytics by using the container offering, which enables users to use a pay-as-you-go subscription model. + +### CY2025 Q3 + +#### New capabilities + +- **Decoupled metadata management** + - Users will be able to start using ScalarDB Cluster without migrating or changing the schemas of existing applications by managing the transaction metadata of ScalarDB in a separate location. + +#### Usability + +- **Views** + - Users will be able to define views so that they can manage multiple different databases in an easier and simplified way. +- **Addition of SQL operations for aggregation** + - Users will be able to issue aggregation operations in ScalarDB SQL. +- **Elimination of out-of-memory errors due to large scans** + - Users will be able to issue large scans without experiencing out-of-memory errors. +- **Enabling of read operations during a paused duration** + - Users will be able to issue read operations even during a paused duration so that users can still read data while taking backups. + +#### Scalability and availability + +- **Semi-synchronous replication** + - Users will be able to replicate the data of ScalarDB-based applications in a disaster-recoverable manner. For example, assume you provide a primary service in Tokyo and a standby service in Osaka. In case of catastrophic failure in Tokyo, you can switch the primary service to Osaka so that you can continue to provide the service without data loss and extended downtime. + +### CY2025 Q4 + +#### New capabilities + +- **Native secondary index** + - Users will be able to define flexible secondary indexes. The existing secondary index is limited because it is implemented based on the common capabilities of the supported databases' secondary indexes. Therefore, for example, you cannot define a multi-column index. The new secondary index will be created at the ScalarDB layer so that you can create more flexible indexes, like a multi-column index. +- **Universal catalog** + - Users will be able to manage metadata, including schemas and semantic information, for operational and analytical databases across separate business domains in a unified manner. +- **Universal authentication and authorization** + - Users will be able to be given access to ScalarDB Cluster and ScalarDB Analytics by using a unified authentication and authorization method. + +#### Support for additional databases (object storage) + +- **Azure Blob Storage** + - Users will be able to use Azure Blob Storage as an underlying database through ScalarDB Cluster. +- **Amazon S3** + - Users will be able to use Amazon S3 as an underlying database through ScalarDB Cluster. +- **Google Cloud Storage** + - Users will be able to use Google Cloud Storage as an underlying database through ScalarDB Cluster and ScalarDB Analytics. + +#### Performance + +- **Reduction of storage space needed for managing ScalarDB metadata** + - Users will likely use less storage space to run ScalarDB. ScalarDB will remove the before image of committed transactions after they are committed. However, whether or not those committed transactions will impact actual storage space depends on the underlying databases. + +#### Cloud support + +- **Red Hat OpenShift support** + - Users will be able to use Red Hat–certified Helm Charts for ScalarDB Cluster in OpenShift environments. +- **Container offering in Google Cloud Marketplace** + - Users will be able to deploy ScalarDB Cluster by using the Google Cloud container offering, which enables users to use a pay-as-you-go subscription model. + +### CY2026 + +- **Audit logging** + - Users will be able to view and manage the access logs of ScalarDB Cluster and Analytics, mainly for auditing purposes. +- **Stored procedures** + - Users will be able to define stored procedures so that they can execute a set of operations with a complex logic inside ScalarDB Cluster. +- **Triggers** + - Users will be able to define triggers so that they can automatically execute a set of operations when a specific event occurs in ScalarDB Cluster. +- **User-defined functions (UDFs)** + - Users will be able to define functions so that they can use functions in SQLs to express complex logic in a simpler way. +- **Addition of SQL operations for sorting** + - Users will be able to issue arbitrary sorting (ORDER BY) operations in ScalarDB SQL for multiple or non-JDBC databases. (Currently, ScalarDB can issue sorting operations using clustering keys or arbitrary sorting operations for single JDBC databases.) +- **Addition of more data types** + - Users will be able to use complex data types, such as JSON. \ No newline at end of file diff --git a/versioned_docs/version-3.15/run-non-transactional-storage-operations-through-library.mdx b/versioned_docs/version-3.15/run-non-transactional-storage-operations-through-library.mdx new file mode 100644 index 00000000..4bee033f --- /dev/null +++ b/versioned_docs/version-3.15/run-non-transactional-storage-operations-through-library.mdx @@ -0,0 +1,272 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Non-Transactional Storage Operations Through the Core Library + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to run non-transactional storage operations through the ScalarDB Core library. + +## Preparation + +For the purpose of this guide, you will set up a database and ScalarDB by using a sample in the ScalarDB samples repository. + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the necessary files by running the following command: + +```console +cd scalardb-samples/scalardb-sample +``` + +## Set up a database + +Select your database, and follow the instructions to configure it for ScalarDB. + +For a list of databases that ScalarDB supports, see [Databases](requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for MySQL in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://localhost:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for PostgreSQL in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://localhost:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Oracle Database in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//localhost:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for SQL Server in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Amazon DynamoDB Local in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://localhost:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Apache Cassandra, run the following command: + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Cassandra in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +For a comprehensive list of configurations for ScalarDB, see [ScalarDB Configurations](configurations.mdx). + +## Configure ScalarDB to run non-transactional storage operations + +To run non-transactional storage operations, you need to configure the `scalar.db.transaction_manager` property to `single-crud-operation` in the configuration file **database.properties**: + +```properties +scalar.db.transaction_manager=single-crud-operation +``` + +## Create or import a schema + +ScalarDB has its own data model and schema that maps to the implementation-specific data model and schema. + +- **Need to create a database schema?** See [ScalarDB Schema Loader](schema-loader.mdx). +- **Need to import an existing database?** See [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](schema-loader-import.mdx). + +## Create your Java application + +This section describes how to add the ScalarDB Core library to your project and how to configure it to run non-transactional storage operations by using Java. + +### Add ScalarDB to your project + +The ScalarDB library is available on the [Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb). You can add the library as a build dependency to your application by using Gradle or Maven. + +Select your build tool, and follow the instructions to add the build dependency for ScalarDB to your application. + + + + To add the build dependency for ScalarDB by using Gradle, add the following to `build.gradle` in your application: + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb:3.15.4' + } + ``` + + + To add the build dependency for ScalarDB by using Maven, add the following to `pom.xml` in your application: + + ```xml + + com.scalar-labs + scalardb + 3.15.4 + + ``` + + + +### Use the Java API + +For details about the Java API, see [ScalarDB Java API Guide](api-guide.mdx). + +:::note + +The following limitations apply to non-transactional storage operations: + +- Beginning a transaction is not supported. For more details, see [Execute transactions without beginning or starting a transaction](api-guide.mdx#execute-transactions-without-beginning-or-starting-a-transaction). +- Executing multiple mutations in a single transaction is not supported. + +::: + +### Learn more + +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.15.4/index.html) diff --git a/versioned_docs/version-3.15/run-non-transactional-storage-operations-through-primitive-crud-interface.mdx b/versioned_docs/version-3.15/run-non-transactional-storage-operations-through-primitive-crud-interface.mdx new file mode 100644 index 00000000..21d732d9 --- /dev/null +++ b/versioned_docs/version-3.15/run-non-transactional-storage-operations-through-primitive-crud-interface.mdx @@ -0,0 +1,860 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# Run Non-Transactional Storage Operations Through the Primitive CRUD Interface + +This page explains how to run non-transactional storage operations through the primitive CRUD interface, also known as the Storage API. This guide assumes that you have an advanced understanding of ScalarDB. + +One of the keys to achieving storage-agnostic or database-agnostic ACID transactions on top of existing storage and database systems is the storage abstraction capabilities that ScalarDB provides. Storage abstraction defines a [data model](design.mdx#data-model) and the APIs (Storage API) that issue operations on the basis of the data model. + +Although you will likely use the [Transactional API](api-guide.mdx#transactional-api) in most cases, another option is to use the Storage API. + +The benefits of using the Storage API include the following: + +- As with the Transactional API, you can write your application code without worrying too much about the underlying storage implementation. +- If you don't need transactions for some of the data in your application, you can use the Storage API to partially avoid transactions, which results in faster execution. + +:::warning + +Directly using the Storage API or mixing the Transactional API and the Storage API could cause unexpected behavior. For example, since the Storage API cannot provide transaction capability, the API could cause anomalies or data inconsistency if failures occur when executing operations. + +Therefore, you should be *very* careful about using the Storage API and use it only if you know exactly what you are doing. + +::: + +## Storage API Example + +This section explains how the Storage API can be used in a basic electronic money application. + +:::warning + +The electronic money application is simplified for this example and isn’t suitable for a production environment. + +::: + +### ScalarDB configuration + +Before you begin, you should configure ScalarDB in the same way mentioned in [Getting Started with ScalarDB](getting-started-with-scalardb.mdx). + +With that in mind, this Storage API example assumes that the configuration file `scalardb.properties` exists. + +### Set up the database schema + +You need to define the database schema (the method in which the data will be organized) in the application. For details about the supported data types, see [Data type mapping between ScalarDB and other databases](https://scalardb.scalar-labs.com/docs/latest/schema-loader/#data-type-mapping-between-scalardb-and-the-other-databases). + +For this example, create a file named `emoney-storage.json` in the `scalardb/docs/getting-started` directory. Then, add the following JSON code to define the schema. + +:::note + +In the following JSON, the `transaction` field is set to `false`, which indicates that you should use this table with the Storage API. + +::: + +```json +{ + "emoney.account": { + "transaction": false, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } +} +``` + +To apply the schema, go to the [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) page and download the ScalarDB Schema Loader that matches the version of ScalarDB that you are using to the `getting-started` folder. + +Then, run the following command, replacing `` with the version of the ScalarDB Schema Loader that you downloaded: + +```console +java -jar scalardb-schema-loader-.jar --config scalardb.properties -f emoney-storage.json +``` + +### Example code + +The following is example source code for the electronic money application that uses the Storage API. + +:::warning + +As previously mentioned, since the Storage API cannot provide transaction capability, the API could cause anomalies or data inconsistency if failures occur when executing operations. Therefore, you should be *very* careful about using the Storage API and use it only if you know exactly what you are doing. + +::: + +```java +public class ElectronicMoney { + + private static final String SCALARDB_PROPERTIES = + System.getProperty("user.dir") + File.separator + "scalardb.properties"; + private static final String NAMESPACE = "emoney"; + private static final String TABLENAME = "account"; + private static final String ID = "id"; + private static final String BALANCE = "balance"; + + private final DistributedStorage storage; + + public ElectronicMoney() throws IOException { + StorageFactory factory = StorageFactory.create(SCALARDB_PROPERTIES); + storage = factory.getStorage(); + } + + public void charge(String id, int amount) throws ExecutionException { + // Retrieve the current balance for id + Get get = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, id)) + .build(); + Optional result = storage.get(get); + + // Calculate the balance + int balance = amount; + if (result.isPresent()) { + int current = result.get().getInt(BALANCE); + balance += current; + } + + // Update the balance + Put put = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, id)) + .intValue(BALANCE, balance) + .build(); + storage.put(put); + } + + public void pay(String fromId, String toId, int amount) throws ExecutionException { + // Retrieve the current balances for ids + Get fromGet = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, fromId)) + .build(); + Get toGet = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, toId)) + .build(); + Optional fromResult = storage.get(fromGet); + Optional toResult = storage.get(toGet); + + // Calculate the balances (it assumes that both accounts exist) + int newFromBalance = fromResult.get().getInt(BALANCE) - amount; + int newToBalance = toResult.get().getInt(BALANCE) + amount; + if (newFromBalance < 0) { + throw new RuntimeException(fromId + " doesn't have enough balance."); + } + + // Update the balances + Put fromPut = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, fromId)) + .intValue(BALANCE, newFromBalance) + .build(); + Put toPut = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, toId)) + .intValue(BALANCE, newToBalance) + .build(); + storage.put(fromPut); + storage.put(toPut); + } + + public int getBalance(String id) throws ExecutionException { + // Retrieve the current balances for id + Get get = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLENAME) + .partitionKey(Key.ofText(ID, id)) + .build(); + Optional result = storage.get(get); + + int balance = -1; + if (result.isPresent()) { + balance = result.get().getInt(BALANCE); + } + return balance; + } + + public void close() { + storage.close(); + } +} +``` + +## Storage API guide + +The Storage API is composed of the Administrative API and CRUD API. + +### Administrative API + +You can execute administrative operations programmatically as described in this section. + +:::note + +Another method that you could use to execute administrative operations is by using [Schema Loader](schema-loader.mdx). + +::: + +#### Get a `DistributedStorageAdmin` instance + +To execute administrative operations, you first need to get a `DistributedStorageAdmin` instance. You can obtain the `DistributedStorageAdmin` instance from `StorageFactory` as follows: + +```java +StorageFactory storageFactory = StorageFactory.create(""); +DistributedStorageAdmin admin = storageFactory.getStorageAdmin(); +``` + +For details about configurations, see [ScalarDB Configurations](configurations.mdx). + +After you have executed all administrative operations, you should close the `DistributedStorageAdmin` instance as follows: + +```java +admin.close(); +``` + +#### Create a namespace + +Before creating tables, namespaces must be created since a table belongs to one namespace. + +You can create a namespace as follows: + +```java +// Create the namespace "ns". If the namespace already exists, an exception will be thrown. +admin.createNamespace("ns"); + +// Create the namespace only if it does not already exist. +boolean ifNotExists = true; +admin.createNamespace("ns", ifNotExists); + +// Create the namespace with options. +Map options = ...; +admin.createNamespace("ns", options); +``` + +For details about creation options, see [Creation options](api-guide.mdx#creation-options). + +#### Create a table + +When creating a table, you should define the table metadata and then create the table. + +To define the table metadata, you can use `TableMetadata`. The following shows how to define the columns, partition key, clustering key including clustering orders, and secondary indexes of a table: + +```java +// Define the table metadata. +TableMetadata tableMetadata = + TableMetadata.newBuilder() + .addColumn("c1", DataType.INT) + .addColumn("c2", DataType.TEXT) + .addColumn("c3", DataType.BIGINT) + .addColumn("c4", DataType.FLOAT) + .addColumn("c5", DataType.DOUBLE) + .addPartitionKey("c1") + .addClusteringKey("c2", Scan.Ordering.Order.DESC) + .addClusteringKey("c3", Scan.Ordering.Order.ASC) + .addSecondaryIndex("c4") + .build(); +``` + +For details about the data model of ScalarDB, see [Data Model](design.mdx#data-model). + +Then, create a table as follows: + +```java +// Create the table "ns.tbl". If the table already exists, an exception will be thrown. +admin.createTable("ns", "tbl", tableMetadata); + +// Create the table only if it does not already exist. +boolean ifNotExists = true; +admin.createTable("ns", "tbl", tableMetadata, ifNotExists); + +// Create the table with options. +Map options = ...; +admin.createTable("ns", "tbl", tableMetadata, options); +``` + +#### Create a secondary index + +You can create a secondary index as follows: + +```java +// Create a secondary index on column "c5" for table "ns.tbl". If a secondary index already exists, an exception will be thrown. +admin.createIndex("ns", "tbl", "c5"); + +// Create the secondary index only if it does not already exist. +boolean ifNotExists = true; +admin.createIndex("ns", "tbl", "c5", ifNotExists); + +// Create the secondary index with options. +Map options = ...; +admin.createIndex("ns", "tbl", "c5", options); +``` + +#### Add a new column to a table + +You can add a new, non-partition key column to a table as follows: + +```java +// Add a new column "c6" with the INT data type to the table "ns.tbl". +admin.addNewColumnToTable("ns", "tbl", "c6", DataType.INT) +``` + +:::warning + +You should carefully consider adding a new column to a table because the execution time may vary greatly depending on the underlying storage. Please plan accordingly and consider the following, especially if the database runs in production: + +- **For Cosmos DB for NoSQL and DynamoDB:** Adding a column is almost instantaneous as the table schema is not modified. Only the table metadata stored in a separate table is updated. +- **For Cassandra:** Adding a column will only update the schema metadata and will not modify the existing schema records. The cluster topology is the main factor for the execution time. Changes to the schema metadata are shared to each cluster node via a gossip protocol. Because of this, the larger the cluster, the longer it will take for all nodes to be updated. +- **For relational databases (MySQL, Oracle, etc.):** Adding a column shouldn't take a long time to execute. + +::: + +#### Truncate a table + +You can truncate a table as follows: + +```java +// Truncate the table "ns.tbl". +admin.truncateTable("ns", "tbl"); +``` + +#### Drop a secondary index + +You can drop a secondary index as follows: + +```java +// Drop the secondary index on column "c5" from table "ns.tbl". If the secondary index does not exist, an exception will be thrown. +admin.dropIndex("ns", "tbl", "c5"); + +// Drop the secondary index only if it exists. +boolean ifExists = true; +admin.dropIndex("ns", "tbl", "c5", ifExists); +``` + +#### Drop a table + +You can drop a table as follows: + +```java +// Drop the table "ns.tbl". If the table does not exist, an exception will be thrown. +admin.dropTable("ns", "tbl"); + +// Drop the table only if it exists. +boolean ifExists = true; +admin.dropTable("ns", "tbl", ifExists); +``` + +#### Drop a namespace + +You can drop a namespace as follows: + +```java +// Drop the namespace "ns". If the namespace does not exist, an exception will be thrown. +admin.dropNamespace("ns"); + +// Drop the namespace only if it exists. +boolean ifExists = true; +admin.dropNamespace("ns", ifExists); +``` + +#### Get existing namespaces + +You can get the existing namespaces as follows: + +```java +Set namespaces = admin.getNamespaceNames(); +``` + +:::note + +This method extracts the namespace names of user tables dynamically. As a result, only namespaces that contain tables are returned. Starting from ScalarDB 4.0, we plan to improve the design to remove this limitation. + +::: + +#### Get the tables of a namespace + +You can get the tables of a namespace as follows: + +```java +// Get the tables of the namespace "ns". +Set tables = admin.getNamespaceTableNames("ns"); +``` + +#### Get table metadata + +You can get table metadata as follows: + +```java +// Get the table metadata for "ns.tbl". +TableMetadata tableMetadata = admin.getTableMetadata("ns", "tbl"); +``` + +#### Repair a table + +You can repair the table metadata of an existing table as follows: + +```java +// Repair the table "ns.tbl" with options. +TableMetadata tableMetadata = + TableMetadata.newBuilder() + ... + .build(); +Map options = ...; +admin.repairTable("ns", "tbl", tableMetadata, options); +``` + +### Implement CRUD operations + +The following sections describe CRUD operations. + +#### Get a `DistributedStorage` instance + +To execute CRUD operations in the Storage API, you need to get a `DistributedStorage` instance. + +You can get an instance as follows: + +```java +StorageFactory storageFactory = StorageFactory.create(""); +DistributedStorage storage = storageFactory.getStorage(); +``` + +After you have executed all CRUD operations, you should close the `DistributedStorage` instance as follows: + +```java +storage.close(); +``` + +#### `Get` operation + +`Get` is an operation to retrieve a single record specified by a primary key. + +You need to create a `Get` object first, and then you can execute the object by using the `storage.get()` method as follows: + +```java +// Create a `Get` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .projections("c1", "c2", "c3", "c4") + .build(); + +// Execute the `Get` operation. +Optional result = storage.get(get); +``` + +You can also specify projections to choose which columns are returned. + +For details about how to construct `Key` objects, see [Key construction](api-guide.mdx#key-construction). And, for details about how to handle `Result` objects, see [Handle Result objects](api-guide.mdx#handle-result-objects). + +##### Specify a consistency level + +You can specify a consistency level in each operation (`Get`, `Scan`, `Put`, and `Delete`) in the Storage API as follows: + +```java +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .consistency(Consistency.LINEARIZABLE) // Consistency level + .build(); +``` + +The following table describes the three consistency levels: + +| Consistency level | Description | +| ------------------- | ----------- | +| `SEQUENTIAL` | Sequential consistency assumes that the underlying storage implementation makes all operations appear to take effect in some sequential order and the operations of each individual process appear in this sequence. | +| `EVENTUAL` | Eventual consistency assumes that the underlying storage implementation makes all operations take effect eventually. | +| `LINEARIZABLE` | Linearizable consistency assumes that the underlying storage implementation makes each operation appear to take effect atomically at some point between its invocation and completion. | + +##### Execute `Get` by using a secondary index + +You can execute a `Get` operation by using a secondary index. + +Instead of specifying a partition key, you can specify an index key (indexed column) to use a secondary index as follows: + +```java +// Create a `Get` operation by using a secondary index. +Key indexKey = Key.ofFloat("c4", 1.23F); + +Get get = + Get.newBuilder() + .namespace("ns") + .table("tbl") + .indexKey(indexKey) + .projections("c1", "c2", "c3", "c4") + .build(); + +// Execute the `Get` operation. +Optional result = storage.get(get); +``` + +:::note + +If the result has more than one record, `storage.get()` will throw an exception. + +::: + +#### `Scan` operation + +`Scan` is an operation to retrieve multiple records within a partition. You can specify clustering-key boundaries and orderings for clustering-key columns in `Scan` operations. + +You need to create a `Scan` object first, and then you can execute the object by using the `storage.scan()` method as follows: + +```java +// Create a `Scan` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key startClusteringKey = Key.of("c2", "aaa", "c3", 100L); +Key endClusteringKey = Key.of("c2", "aaa", "c3", 300L); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .start(startClusteringKey, true) // Include startClusteringKey + .end(endClusteringKey, false) // Exclude endClusteringKey + .projections("c1", "c2", "c3", "c4") + .orderings(Scan.Ordering.desc("c2"), Scan.Ordering.asc("c3")) + .limit(10) + .build(); + +// Execute the `Scan` operation. +Scanner scanner = storage.scan(scan); +``` + +You can omit the clustering-key boundaries or specify either a `start` boundary or an `end` boundary. If you don't specify `orderings`, you will get results ordered by the clustering order that you defined when creating the table. + +In addition, you can specify `projections` to choose which columns are returned and use `limit` to specify the number of records to return in `Scan` operations. + +##### Handle `Scanner` objects + +A `Scan` operation in the Storage API returns a `Scanner` object. + +If you want to get results one by one from the `Scanner` object, you can use the `one()` method as follows: + +```java +Optional result = scanner.one(); +``` + +Or, if you want to get a list of all results, you can use the `all()` method as follows: + +```java +List results = scanner.all(); +``` + +In addition, since `Scanner` implements `Iterable`, you can use `Scanner` in a for-each loop as follows: + +```java +for (Result result : scanner) { + ... +} +``` + +Remember to close the `Scanner` object after getting the results: + +```java +scanner.close(); +``` + +Or you can use `try`-with-resources as follows: + +```java +try (Scanner scanner = storage.scan(scan)) { + ... +} +``` + +##### Execute `Scan` by using a secondary index + +You can execute a `Scan` operation by using a secondary index. + +Instead of specifying a partition key, you can specify an index key (indexed column) to use a secondary index as follows: + +```java +// Create a `Scan` operation by using a secondary index. +Key indexKey = Key.ofFloat("c4", 1.23F); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .indexKey(indexKey) + .projections("c1", "c2", "c3", "c4") + .limit(10) + .build(); + +// Execute the `Scan` operation. +Scanner scanner = storage.scan(scan); +``` + +:::note + +You can't specify clustering-key boundaries and orderings in `Scan` by using a secondary index. + +::: + +##### Execute `Scan` without specifying a partition key to retrieve all the records of a table + +You can execute a `Scan` operation without specifying a partition key. + +Instead of calling the `partitionKey()` method in the builder, you can call the `all()` method to scan a table without specifying a partition key as follows: + +```java +// Create a `Scan` operation without specifying a partition key. +Key partitionKey = Key.ofInt("c1", 10); +Key startClusteringKey = Key.of("c2", "aaa", "c3", 100L); +Key endClusteringKey = Key.of("c2", "aaa", "c3", 300L); + +Scan scan = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .projections("c1", "c2", "c3", "c4") + .limit(10) + .build(); + +// Execute the `Scan` operation. +Scanner scanner = storage.scan(scan); +``` + +:::note + +You can't specify clustering-key boundaries and orderings in `Scan` without specifying a partition key. + +::: + +#### `Put` operation + +`Put` is an operation to put a record specified by a primary key. The operation behaves as an upsert operation for a record, in which the operation updates the record if the record exists or inserts the record if the record does not exist. + +You need to create a `Put` object first, and then you can execute the object by using the `storage.put()` method as follows: + +```java +// Create a `Put` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +// Execute the `Put` operation. +storage.put(put); +``` + +You can also put a record with `null` values as follows: + +```java +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", null) + .doubleValue("c5", null) + .build(); +``` + +:::note + +If you specify `enableImplicitPreRead()`, `disableImplicitPreRead()`, or `implicitPreReadEnabled()` in the `Put` operation builder, they will be ignored. + + +::: + +#### `Delete` operation + +`Delete` is an operation to delete a record specified by a primary key. + +You need to create a `Delete` object first, and then you can execute the object by using the `storage.delete()` method as follows: + +```java +// Create a `Delete` operation. +Key partitionKey = Key.ofInt("c1", 10); +Key clusteringKey = Key.of("c2", "aaa", "c3", 100L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .build(); + +// Execute the `Delete` operation. +storage.delete(delete); +``` + +#### `Put` and `Delete` with a condition + +You can write arbitrary conditions (for example, a bank account balance must be equal to or more than zero) that you require an operation to meet before being executed by implementing logic that checks the conditions. Alternatively, you can write simple conditions in a mutation operation, such as `Put` and `Delete`. + +When a `Put` or `Delete` operation includes a condition, the operation is executed only if the specified condition is met. If the condition is not met when the operation is executed, an exception called `NoMutationException` will be thrown. + +##### Conditions for `Put` + +In a `Put` operation in the Storage API, you can specify a condition that causes the `Put` operation to be executed only when the specified condition matches. This operation is like a compare-and-swap operation where the condition is compared and the update is performed atomically. + +You can specify a condition in a `Put` operation as follows: + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.putIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .condition(condition) // condition + .build(); +``` + +Other than the `putIf` condition, you can specify the `putIfExists` and `putIfNotExists` conditions as follows: + +```java +// Build a `putIfExists` condition. +MutationCondition putIfExistsCondition = ConditionBuilder.putIfExists(); + +// Build a `putIfNotExists` condition. +MutationCondition putIfNotExistsCondition = ConditionBuilder.putIfNotExists(); +``` + +##### Conditions for `Delete` + +Similar to a `Put` operation, you can specify a condition in a `Delete` operation in the Storage API. + +You can specify a condition in a `Delete` operation as follows: + +```java +// Build a condition. +MutationCondition condition = + ConditionBuilder.deleteIf(ConditionBuilder.column("c4").isEqualToFloat(0.0F)) + .and(ConditionBuilder.column("c5").isEqualToDouble(0.0)) + .build(); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKey) + .condition(condition) // condition + .build(); +``` + +In addition to using the `deleteIf` condition, you can specify the `deleteIfExists` condition as follows: + +```java +// Build a `deleteIfExists` condition. +MutationCondition deleteIfExistsCondition = ConditionBuilder.deleteIfExists(); +``` + +#### Mutate operation + +Mutate is an operation to execute multiple mutations (`Put` and `Delete` operations) in a single partition. + +You need to create mutation objects first, and then you can execute the objects by using the `storage.mutate()` method as follows: + +```java +// Create `Put` and `Delete` operations. +Key partitionKey = Key.ofInt("c1", 10); + +Key clusteringKeyForPut = Key.of("c2", "aaa", "c3", 100L); + +Put put = + Put.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForPut) + .floatValue("c4", 1.23F) + .doubleValue("c5", 4.56) + .build(); + +Key clusteringKeyForDelete = Key.of("c2", "bbb", "c3", 200L); + +Delete delete = + Delete.newBuilder() + .namespace("ns") + .table("tbl") + .partitionKey(partitionKey) + .clusteringKey(clusteringKeyForDelete) + .build(); + +// Execute the operations. +storage.mutate(Arrays.asList(put, delete)); +``` + +:::note + +A Mutate operation only accepts mutations for a single partition; otherwise, an exception will be thrown. + +In addition, if you specify multiple conditions in a Mutate operation, the operation will be executed only when all the conditions match. + +::: + +#### Default namespace for CRUD operations + +A default namespace for all CRUD operations can be set by using a property in the ScalarDB configuration. + +```properties +scalar.db.default_namespace_name= +``` + +Any operation that does not specify a namespace will use the default namespace set in the configuration. + +```java +// This operation will target the default namespace. +Scan scanUsingDefaultNamespace = + Scan.newBuilder() + .table("tbl") + .all() + .build(); +// This operation will target the "ns" namespace. +Scan scanUsingSpecifiedNamespace = + Scan.newBuilder() + .namespace("ns") + .table("tbl") + .all() + .build(); +``` diff --git a/versioned_docs/version-3.15/run-transactions-through-scalardb-core-library.mdx b/versioned_docs/version-3.15/run-transactions-through-scalardb-core-library.mdx new file mode 100644 index 00000000..d6579d15 --- /dev/null +++ b/versioned_docs/version-3.15/run-transactions-through-scalardb-core-library.mdx @@ -0,0 +1,219 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Transactions Through the ScalarDB Core Library + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to configure your ScalarDB properties file and create schemas to run transactions through a one-phase or a two-phase commit interface by using the ScalarDB Core library. + +## Preparation + +For the purpose of this guide, you will set up a database and ScalarDB by using a sample in the ScalarDB samples repository. + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the necessary files by running the following command: + +```console +cd scalardb-samples/scalardb-sample +``` + +## Set up a database + +Select your database, and follow the instructions to configure it for ScalarDB. + +For a list of databases that ScalarDB supports, see [Databases](requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for MySQL in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://localhost:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for PostgreSQL in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://localhost:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Oracle Database in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//localhost:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for SQL Server in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Amazon DynamoDB Local in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://localhost:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yml` file in the `scalardb-samples/scalardb-sample` directory. + + To start Apache Cassandra, run the following command: + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB

+ + The **database.properties** file in the `scalardb-samples/scalardb-sample` directory contains database configurations for ScalarDB. Please uncomment the properties for Cassandra in the **database.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=localhost + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +For a comprehensive list of configurations for ScalarDB, see [ScalarDB Configurations](configurations.mdx). + +## Create or import a schema + +ScalarDB has its own data model and schema that maps to the implementation-specific data model and schema. + +- **Need to create a database schema?** See [ScalarDB Schema Loader](schema-loader.mdx). +- **Need to import an existing database?** See [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](schema-loader-import.mdx). + +## Run transactions by using Java + +- **Want to run transactions by using a one-phase commit interface?** See the [ScalarDB Java API Guide](api-guide.mdx#transactional-api). +- **Want to run transactions by using a two-phase commit interface?** See [Transactions with a Two-Phase Commit Interface](two-phase-commit-transactions.mdx). diff --git a/versioned_docs/version-3.15/scalar-kubernetes/AccessScalarProducts.mdx b/versioned_docs/version-3.15/scalar-kubernetes/AccessScalarProducts.mdx new file mode 100644 index 00000000..543dff2e --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/AccessScalarProducts.mdx @@ -0,0 +1,195 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Make ScalarDB or ScalarDL deployed in a Kubernetes cluster environment available from applications + +This document explains how to make ScalarDB or ScalarDL deployed in a Kubernetes cluster environment available from applications. To make ScalarDB or ScalarDL available from applications, you can use Scalar Envoy via a Kubernetes service resource named `-envoy`. You can use `-envoy` in several ways, such as: + +* Directly from inside the same Kubernetes cluster as ScalarDB or ScalarDL. +* Via a load balancer from outside the Kubernetes cluster. +* From a bastion server by using the `kubectl port-forward` command (for testing purposes only). + +The resource name `-envoy` is decided based on the helm release name. You can see the helm release name by running the following command: + +```console +helm list -n ns-scalar +``` + +You should see the following output: + +```console +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +scalardb ns-scalar 1 2023-02-09 19:31:40.527130674 +0900 JST deployed scalardb-2.5.0 3.8.0 +scalardl-auditor ns-scalar 1 2023-02-09 19:32:03.008986045 +0900 JST deployed scalardl-audit-2.5.1 3.7.1 +scalardl-ledger ns-scalar 1 2023-02-09 19:31:53.459548418 +0900 JST deployed scalardl-4.5.1 3.7.1 +``` + +You can also see the envoy service name `-envoy` by running the following command: + +```console +kubectl get service -n ns-scalar +``` + +You should see the following output: + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-envoy LoadBalancer 10.99.245.143 60051:31110/TCP 2m2s +scalardb-envoy-metrics ClusterIP 10.104.56.87 9001/TCP 2m2s +scalardb-headless ClusterIP None 60051/TCP 2m2s +scalardb-metrics ClusterIP 10.111.213.194 8080/TCP 2m2s +scalardl-auditor-envoy LoadBalancer 10.111.141.43 40051:31553/TCP,40052:31171/TCP 99s +scalardl-auditor-envoy-metrics ClusterIP 10.104.245.188 9001/TCP 99s +scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 99s +scalardl-auditor-metrics ClusterIP 10.105.119.158 8080/TCP 99s +scalardl-ledger-envoy LoadBalancer 10.96.239.167 50051:32714/TCP,50052:30857/TCP 109s +scalardl-ledger-envoy-metrics ClusterIP 10.97.204.18 9001/TCP 109s +scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 109s +scalardl-ledger-metrics ClusterIP 10.104.216.189 8080/TCP 109s +``` + +## Run application (client) requests to ScalarDB or ScalarDL via service resources directly from inside the same Kubernetes cluster + +If you deploy your application (client) in the same Kubernetes cluster as ScalarDB or ScalarDL (for example, if you deploy your application [client] on another node group or pool in the same Kubernetes cluster), the application can access ScalarDB or ScalarDL by using Kubernetes service resources. The format of the service resource name (FQDN) is `-envoy..svc.cluster.local`. + +The following are examples of ScalarDB and ScalarDL deployments on the `ns-scalar` namespace: + +* **ScalarDB Server** + ```console + scalardb-envoy.ns-scalar.svc.cluster.local + ``` +* **ScalarDL Ledger** + ```console + scalardl-ledger-envoy.ns-scalar.svc.cluster.local + ``` +* **ScalarDL Auditor** + ```console + scalardl-auditor-envoy.ns-scalar.svc.cluster.local + ``` + +When using the Kubernetes service resource, you must set the above FQDN in the properties file for the application (client) as follows: + +* **Client properties file for ScalarDB Server** + ```properties + scalar.db.contact_points=-envoy..svc.cluster.local + scalar.db.contact_port=60051 + scalar.db.storage=grpc + scalar.db.transaction_manager=grpc + ``` +* **Client properties file for ScalarDL Ledger** + ```properties + scalar.dl.client.server.host=-envoy..svc.cluster.local + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + ``` +* **Client properties file for ScalarDL Ledger with ScalarDL Auditor mode enabled** + ```properties + # Ledger + scalar.dl.client.server.host=-envoy..svc.cluster.local + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=-envoy..svc.cluster.local + scalar.dl.auditor.server.port=40051 + scalar.dl.auditor.server.privileged_port=40052 + ``` + +## Run application (client) requests to ScalarDB or ScalarDL via load balancers from outside the Kubernetes cluster + +If you deploy your application (client) in an environment outside the Kubernetes cluster for ScalarDB or ScalarDL (for example, if you deploy your application [client] on another Kubernetes cluster, container platform, or server), the application can access ScalarDB or ScalarDL by using a load balancer that each cloud service provides. + +You can create a load balancer by setting `envoy.service.type` to `LoadBalancer` in your custom values file. After configuring the custom values file, you can use Scalar Envoy through a Kubernetes service resource by using the load balancer. You can also set the load balancer configurations by using annotations. + +For more details on how to configure your custom values file, see [Service configurations](../helm-charts/configure-custom-values-envoy.mdx#service-configurations). + +When using a load balancer, you must set the FQDN or IP address of the load balancer in the properties file for the application (client) as follows. + +* **Client properties file for ScalarDB Server** + ```properties + scalar.db.contact_points= + scalar.db.contact_port=60051 + scalar.db.storage=grpc + scalar.db.transaction_manager=grpc + ``` +* **Client properties file for ScalarDL Ledger** + ```properties + scalar.dl.client.server.host= + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + ``` +* **Client properties file for ScalarDL Ledger with ScalarDL Auditor mode enabled** + ```properties + # Ledger + scalar.dl.client.server.host= + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host= + scalar.dl.auditor.server.port=40051 + scalar.dl.auditor.server.privileged_port=40052 + ``` + +The concrete implementation of the load balancer and access method depend on the Kubernetes cluster. If you are using a managed Kubernetes cluster, see the following official documentation based on your cloud service provider: + +* **Amazon Elastic Kubernetes Service (EKS)** + * [Network load balancing on Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/network-load-balancing.html) +* **Azure Kubernetes Service (AKS)** + * [Use a public standard load balancer in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/load-balancer-standard) + * [Use an internal load balancer with Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/internal-lb) + +## Run client requests to ScalarDB or ScalarDL from a bastion server (for testing purposes only; not recommended in a production environment) + +You can run client requests to ScalarDB or ScalarDL from a bastion server by running the `kubectl port-forward` command. If you create a ScalarDL Auditor mode environment, however, you must run two `kubectl port-forward` commands with different kubeconfig files from one bastion server to access two Kubernetes clusters. + +1. **(ScalarDL Auditor mode only)** In the bastion server for ScalarDL Ledger, configure an existing kubeconfig file or add a new kubeconfig file to access the Kubernetes cluster for ScalarDL Auditor. For details on how to configure the kubeconfig file of each managed Kubernetes cluster, see [Configure kubeconfig](CreateBastionServer.mdx#configure-kubeconfig). +2. Configure port forwarding to each service from the bastion server. + * **ScalarDB Server** + ```console + kubectl port-forward -n svc/-envoy 60051:60051 + ``` + * **ScalarDL Ledger** + ```console + kubectl --context port-forward -n svc/-envoy 50051:50051 + kubectl --context port-forward -n svc/-envoy 50052:50052 + ``` + * **ScalarDL Auditor** + ```console + kubectl --context port-forward -n svc/-envoy 40051:40051 + kubectl --context port-forward -n svc/-envoy 40052:40052 + ``` +3. Configure the properties file to access ScalarDB or ScalarDL via `localhost`. + * **Client properties file for ScalarDB Server** + ```properties + scalar.db.contact_points=localhost + scalar.db.contact_port=60051 + scalar.db.storage=grpc + scalar.db.transaction_manager=grpc + ``` + * **Client properties file for ScalarDL Ledger** + ```properties + scalar.dl.client.server.host=localhost + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + ``` + * **Client properties file for ScalarDL Ledger with ScalarDL Auditor mode enabled** + ```properties + # Ledger + scalar.dl.client.server.host=localhost + scalar.dl.ledger.server.port=50051 + scalar.dl.ledger.server.privileged_port=50052 + + # Auditor + scalar.dl.client.auditor.enabled=true + scalar.dl.client.auditor.host=localhost + scalar.dl.auditor.server.port=40051 + scalar.dl.auditor.server.privileged_port=40052 + ``` + diff --git a/versioned_docs/version-3.15/scalar-kubernetes/AwsMarketplaceGuide.mdx b/versioned_docs/version-3.15/scalar-kubernetes/AwsMarketplaceGuide.mdx new file mode 100644 index 00000000..f6270218 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/AwsMarketplaceGuide.mdx @@ -0,0 +1,469 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to install Scalar products through AWS Marketplace + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +Scalar products (ScalarDB, ScalarDL, and their tools) are available in the AWS Marketplace as container images. This guide explains how to install Scalar products through the AWS Marketplace. + +:::note + +- Some Scalar products are available under commercial licenses, and the AWS Marketplace provides those products as pay-as-you-go (PAYG) pricing. When you use pay-as-you-go pricing, AWS will charge you the Scalar product license fee based on your usage. +- Previously, a bring-your-own-license (BYOL) option was offered in the AWS Marketplace. However, that option has been deprecated and removed, so it is no longer supported in the AWS Marketplace. +- A BYOL option is provided in the following public container repositories outside of the AWS Marketplace. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact-us). + - [ScalarDB Cluster Enterprise Standard](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-node-byol-standard) + - [ScalarDB Cluster Enterprise Premium](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-node-byol-premium) + - [ScalarDL Ledger](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-ledger-byol) + - [ScalarDL Auditor](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-auditor-byol) + +::: + +## Subscribe to Scalar products from AWS Marketplace + +1. Select your Scalar product to see the links to the AWS Marketplace. + + + + Select your edition of ScalarDB Enterprise. + + + | PAYG | BYOL (Deprecated) | + |:---------------------------------------------------------------------------------|:---------------------------------------------------------------------------------| + | [ScalarDB Cluster](https://aws.amazon.com/marketplace/pp/prodview-jx6qxatkxuwm4) | [ScalarDB Cluster](https://aws.amazon.com/marketplace/pp/prodview-alcwrmw6v4cfy) | + + + | PAYG | BYOL (Deprecated) | + |:---------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------| + | [ScalarDB Cluster](https://aws.amazon.com/marketplace/pp/prodview-djqw3zk6dwyk6) | [ScalarDB Cluster](https://aws.amazon.com/marketplace/pp/prodview-alcwrmw6v4cfy) | + + + + + | PAYG | BYOL (Deprecated) | + |:---------------------------------------------------------------------------------|:---------------------------------------------------------------------------------| + | [ScalarDL Ledger](https://aws.amazon.com/marketplace/pp/prodview-wttioaezp5j6e) | [ScalarDL Ledger](https://aws.amazon.com/marketplace/pp/prodview-3jdwfmqonx7a2) | + + + | PAYG | BYOL (Deprecated) | + |:---------------------------------------------------------------------------------|:---------------------------------------------------------------------------------| + | [ScalarDL Auditor](https://aws.amazon.com/marketplace/pp/prodview-ke3yiw4mhriuu) | [ScalarDL Auditor](https://aws.amazon.com/marketplace/pp/prodview-tj7svy75gu7m6) | + + + +1. Select **Continue to Subscribe**. + +1. Sign in to AWS Marketplace using your IAM user. + If you have already signed in, this step will be skipped automatically. + +1. Read the **Terms and Conditions** and select **Accept Terms**. + It takes some time. When it's done, you can see the current date in the **Effective date** column. + Also, you can see our products on the [Manage subscriptions](https://us-east-1.console.aws.amazon.com/marketplace/home#/subscriptions) page of AWS Console. + +## **[Pay-As-You-Go]** Deploy containers on EKS (Amazon Elastic Kubernetes Service) from AWS Marketplace using Scalar Helm Charts + +By subscribing to Scalar products in the AWS Marketplace, you can pull the container images of Scalar products from the private container registry ([ECR](https://aws.amazon.com/ecr/)) of the AWS Marketplace. This section explains how to deploy Scalar products with pay-as-you-go pricing in your [EKS](https://aws.amazon.com/eks/) cluster from the private container registry. + +1. Create an OIDC provider. + + You must create an identity and access management (IAM) OpenID Connect (OIDC) provider to run the AWS Marketplace Metering Service from ScalarDL pods. + + ```console + eksctl utils associate-iam-oidc-provider --region --cluster --approve + ``` + + For details, see [Creating an IAM OIDC provider for your cluster](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html). + +1. Create a service account. + + To allow your pods to run the AWS Marketplace Metering Service, you can use [IAM roles for service accounts](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html). + + ```console + eksctl create iamserviceaccount \ + --name \ + --namespace \ + --region \ + --cluster \ + --attach-policy-arn arn:aws:iam::aws:policy/AWSMarketplaceMeteringFullAccess \ + --approve \ + --override-existing-serviceaccounts + ``` + +1. Update the custom values file of the Helm Chart for the Scalar product that you want to install. + You need to specify the private container registry (ECR) of the AWS Marketplace as the value for `[].image.repository` in the custom values file. You also need to specify the service account name that you created in the previous step as the value for `[].serviceAccount.serviceAccountName` and set `[].serviceAccount.automountServiceAccountToken` to `true`. See the following examples based on the product you're using. + + + + Select your edition of ScalarDB Enterprise. + + + In the `scalardb-cluster-standard-custom-values.yaml` file: + + ```yaml + scalardbCluster: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-cluster-node-aws-payg-standard" + serviceAccount: + serviceAccountName: "" + automountServiceAccountToken: true + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDB Cluster](../helm-charts/configure-custom-values-scalardb-cluster.mdx). + + ::: + + + + In the `scalardb-cluster-premium-custom-values.yaml` file: + + ```yaml + scalardbCluster: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-cluster-node-aws-payg-premium" + serviceAccount: + serviceAccountName: "" + automountServiceAccountToken: true + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDB Cluster](../helm-charts/configure-custom-values-scalardb-cluster.mdx). + + ::: + + + + + +

ScalarDL Ledger

+ + In the `scalardl-ledger-custom-values.yaml` file: + + ```yaml + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-ledger-aws-payg" + serviceAccount: + serviceAccountName: "" + automountServiceAccountToken: true + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Ledger](../helm-charts/configure-custom-values-scalardl-ledger.mdx). + + ::: + +

ScalarDL Schema Loader for Ledger

+ + You don't need to update the `[].image.repository` configuration in your `schema-loader-ledger-custom-values.yaml` file. The container image of ScalarDL Schema Loader is provided in the [public container repository](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader). + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Schema Loader](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx). + + ::: + +
+ +

ScalarDL Auditor

+ + In the `scalardl-auditor-custom-values.yaml` file: + + ```yaml + auditor: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardl-auditor-aws-payg" + serviceAccount: + serviceAccountName: "" + automountServiceAccountToken: true + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Auditor](../helm-charts/configure-custom-values-scalardl-auditor.mdx). + + ::: + +

ScalarDL Schema Loader for Auditor

+ + You don't need to update the `[].image.repository` configuration in your `schema-loader-auditor-custom-values.yaml` file. The container image of ScalarDL Schema Loader is provided in the [public container repository](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader). + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Schema Loader](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx). + + ::: + +
+
+ +1. Deploy Scalar products by using Helm Charts in conjunction with the above custom values files. See the following examples based on the product you're using. + + + + Select your edition of ScalarDB Enterprise. + + + ```console + helm install scalardb-cluster-standard scalar-labs/scalardb-cluster -f scalardb-cluster-standard-custom-values.yaml + ``` + + + ```console + helm install scalardb-cluster-premium scalar-labs/scalardb-cluster -f scalardb-cluster-premium-custom-values.yaml + ``` + + + + +

ScalarDL Ledger

+ + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + +

ScalarDL Schema Loader for Ledger

+ + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-ledger-custom-values.yaml + ``` +
+ +

ScalarDL Auditor

+ + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + +

ScalarDL Schema Loader for Auditor

+ + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-auditor-custom-values.yaml + ``` +
+
+ +## **[Deprecated] [BYOL]** Deploy containers on EKS (Amazon Elastic Kubernetes Service) from AWS Marketplace using Scalar Helm Charts + +By subscribing to Scalar products in the AWS Marketplace, you can pull the container images of Scalar products from the private container registry ([ECR](https://aws.amazon.com/ecr/)) of the AWS Marketplace. This section explains how to deploy Scalar products with the BYOL option in your [EKS](https://aws.amazon.com/eks/) cluster from the private container registry. + +1. Update the custom values file of the Helm Chart for the Scalar product that you want to install. + You need to specify the private container registry (ECR) of AWS Marketplace as the value of `[].image.repository` in the custom values file. See the following examples based on the product you're using. + + + + ```yaml + scalardbCluster: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-cluster-node-aws-byol" + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDB Cluster](../helm-charts/configure-custom-values-scalardb-cluster.mdx). + + ::: + + + +

ScalarDL Ledger

+ + In the `scalardl-ledger-custom-values.yaml` file: + + ```yaml + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger" + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Ledger](../helm-charts/configure-custom-values-scalardl-ledger.mdx). + + ::: + +

ScalarDL Schema Loader for Ledger

+ + You don't need to update the `[].image.repository` configuration in your `schema-loader-ledger-custom-values.yaml` file. The container image of ScalarDL Schema Loader is provided in the [public container repository](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader). + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Schema Loader](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx). + + ::: + +
+ +

ScalarDL Auditor

+ + In the `scalardl-auditor-custom-values.yaml` file: + + ```yaml + auditor: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-auditor" + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Auditor](../helm-charts/configure-custom-values-scalardl-auditor.mdx). + + ::: + +

ScalarDL Schema Loader for Auditor

+ + You don't need to update the `[].image.repository` configuration in your `schema-loader-auditor-custom-values.yaml` file. The container image of ScalarDL Schema Loader is provided in the [public container repository](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader). + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Schema Loader](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx). + + ::: + +
+
+ +1. Deploy the Scalar products using the Helm Chart with the above custom values files. See the following examples based on the product you're using. See the following examples based on the product you're using. + + + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f scalardb-cluster-custom-values.yaml + ``` + + +

ScalarDL Ledger

+ + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + +

ScalarDL Schema Loader for Ledger

+ + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-ledger-custom-values.yaml + ``` +
+ +

ScalarDL Auditor

+ + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + +

ScalarDL Schema Loader for Auditor

+ + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-auditor-custom-values.yaml + ``` +
+
+ +## **[Deprecated] [BYOL]** Deploy containers on Kubernetes other than EKS from AWS Marketplace using Scalar Helm Charts + +1. Install the `aws` command according to the [AWS Official Document (Installing or updating the latest version of the AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html). + +1. Configure the AWS CLI with your credentials according to the [AWS Official Document (Configuration basics)](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html). + +1. Create a `reg-ecr-mp-secrets` secret resource for pulling the container images from the ECR of AWS Marketplace. + ```console + kubectl create secret docker-registry reg-ecr-mp-secrets \ + --docker-server=709825985650.dkr.ecr.us-east-1.amazonaws.com \ + --docker-username=AWS \ + --docker-password=$(aws ecr get-login-password --region us-east-1) + ``` + +1. Update the custom values file of the Helm Chart for the Scalar product that you want to install. + You need to specify the private container registry (ECR) of AWS Marketplace as the value of `[].image.repository` in the custom values file. + Also, you need to specify the `reg-ecr-mp-secrets` as the value of `[].imagePullSecrets`. See the following examples based on the product you're using. + + + + ```yaml + scalardbCluster: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalardb-cluster-node-aws-byol" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDB Cluster](../helm-charts/configure-custom-values-scalardb-cluster.mdx). + + ::: + + + +

ScalarDL Ledger

+ + In the `scalardl-ledger-custom-values.yaml` file: + + ```yaml + ledger: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-ledger" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Ledger](../helm-charts/configure-custom-values-scalardl-ledger.mdx). + + ::: + +

ScalarDL Schema Loader for Ledger

+ + You don't need to update the `[].image.repository` configuration in your `schema-loader-ledger-custom-values.yaml` file. The container image of ScalarDL Schema Loader is provided in the [public container repository](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader). + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Schema Loader](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx). + + ::: + +
+ +

ScalarDL Auditor

+ + In the `scalardl-auditor-custom-values.yaml` file: + + ```yaml + auditor: + image: + repository: "709825985650.dkr.ecr.us-east-1.amazonaws.com/scalar/scalar-auditor" + imagePullSecrets: + - name: "reg-ecr-mp-secrets" + ``` + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Auditor](../helm-charts/configure-custom-values-scalardl-auditor.mdx). + + ::: + +

ScalarDL Schema Loader for Auditor

+ + You don't need to update the `[].image.repository` configuration in your `schema-loader-auditor-custom-values.yaml` file. The container image of ScalarDL Schema Loader is provided in the [public container repository](https://github.com/orgs/scalar-labs/packages/container/package/scalardl-schema-loader). + + :::note + + For more details on the configurations, see [Configure a custom values file for ScalarDL Schema Loader](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx). + + ::: + +
+
+ +1. Deploy the Scalar products using the Helm Chart with the above custom values files. + * Examples + Please refer to the **[Deprecated] [BYOL] Deploy containers on EKS (Amazon Elastic Kubernetes Service) from AWS Marketplace using Scalar Helm Charts** section of this document. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/AzureMarketplaceGuide.mdx b/versioned_docs/version-3.15/scalar-kubernetes/AzureMarketplaceGuide.mdx new file mode 100644 index 00000000..da3612a1 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/AzureMarketplaceGuide.mdx @@ -0,0 +1,235 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to install Scalar products through Azure Marketplace + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning + +Scalar products are currently not available in Azure Marketplace. For details on other ways to get the container images of Scalar products, please see [How to get the container images of Scalar products](./HowToGetContainerImages.mdx). + +::: + +Scalar products (ScalarDB, ScalarDL, and their tools) are provided in Azure Marketplace as container offers. This guide explains how to install Scalar products through Azure Marketplace. + +Note that some Scalar products are licensed under commercial licenses, and the Azure Marketplace provides them as BYOL (Bring Your Own License). Please make sure you have appropriate licenses. + +## Get Scalar products from Microsoft Azure Marketplace + +1. Select your Scalar product to see the links to the Microsoft Azure Marketplace. + + + + - [ScalarDB](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) + + + - [ScalarDL](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardl) + + + +1. Select **Get It Now**. + +1. Sign in to Azure Marketplace using your work email address. + Please use the work email address that is used as an account of Microsoft Azure. + If you have already signed in, this step will be skipped automatically. + +1. Input your information. +Note that **Company** is not required, but please enter it. + +1. Select a **Software plan** you need from the pull-down. + **Software plan** means a combination of the container image and the license. Please select the *Software plan* you use. + +1. Select **Continue**. + After selecting the **Continue**, it automatically moves to the Azure Portal. + +1. Create a private container registry (Azure Container Registry). + Follow the on-screen instructions, please create your private container registry. + The container images of Scalar products will be copied to your private container registry. + +1. Repeat these steps as needed. + You need several container images to run Scalar products on Kubernetes, but Azure Marketplace copies only one container image at a time. So, you need to subscribe to several software plans (repeat subscribe operation) as needed. + - Container images that you need are the following. Select your Scalar product to see details about the container images. + + + + - ScalarDB Cluster (BYOL) + - [Deprecated] ScalarDB Server Default (2vCPU, 4GiB Memory) + - [Deprecated] ScalarDB GraphQL Server (optional) + - [Deprecated] ScalarDB SQL Server (optional) + + + - ScalarDL Ledger Default (2vCPU, 4GiB Memory) + - ScalarDL Auditor Default (2vCPU, 4GiB Memory) + - **ScalarDL Auditor** is optional. If you use **ScalarDL Auditor**, subscribe to it. + - ScalarDL Schema Loader + + + +Now, you can pull the container images of the Scalar products from your private container registry. +Please refer to the [Azure Container Registry documentation](https://docs.microsoft.com/en-us/azure/container-registry/) for more details about the Azure Container Registry. + +## Deploy containers on AKS (Azure Kubernetes Service) from your private container registry using Scalar Helm Charts + +1. Specify your private container registry (Azure Container Registry) when you create an AKS cluster. + * GUI (Azure Portal) + At the **Azure Container Registry** parameter in the **Integrations** tab, please specify your private container registry. + * CLI ([az aks create](https://docs.microsoft.com/en-us/cli/azure/aks?view=azure-cli-latest#az-aks-create) command) + Please specify `--attach-acr` flag with the name of your private container registry. Also, you can configure Azure Container Registry integration for existing AKS clusters using [az aks update](https://docs.microsoft.com/en-us/cli/azure/aks?view=azure-cli-latest#az-aks-update) command with `--attach-acr` flag. Please refer to the [Azure Official Document](https://docs.microsoft.com/en-us/azure/aks/cluster-container-registry-integration) for more details. + +1. Update the custom values file of the Helm Chart of a Scalar product you want to install. You need to specify your private container registry as the value of `[].image.repository` in the custom values file. See the following examples based on the product you're using. + + + + ```yaml + scalardbCluster: + image: + repository: "example.azurecr.io/scalarinc/scalardb-cluster-node-azure-byol" + ``` + + + Select the ScalarDL product you're using. + + + In the `scalardl-ledger-custom-values.yaml` file: + + ```yaml + ledger: + image: + repository: "example.azurecr.io/scalarinc/scalar-ledger" + ``` + + + In the `scalardl-auditor-custom-values.yaml` file: + + ```yaml + auditor: + image: + repository: "example.azurecr.io/scalarinc/scalar-auditor" + ``` + + + In the `schema-loader-custom-values.yaml` file: + + ```yaml + schemaLoading: + image: + repository: "example.azurecr.io/scalarinc/scalardl-schema-loader" + ``` + + + + + +1. Deploy the Scalar product using the Helm Chart with the above custom values file. See the following examples based on the product you're using. + + + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f scalardb-cluster-custom-values.yaml + ``` + + + Select the ScalarDL product you're using. + + + ```console + helm install scalardl-ledger scalar-labs/scalardl -f ./scalardl-ledger-custom-values.yaml + ``` + + + ```console + helm install scalardl-auditor scalar-labs/scalardl-audit -f ./scalardl-auditor-custom-values.yaml + ``` + + + ```console + helm install schema-loader scalar-labs/schema-loading -f ./schema-loader-custom-values.yaml + ``` + + + + + +## Deploy containers on Kubernetes other than AKS (Azure Kubernetes Service) from your private container registry using Scalar Helm Charts + +1. Install the `az` command according to the [Azure Official Document (How to install the Azure CLI)](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli). + +1. Sign in with Azure CLI. + ```console + az login + ``` + +1. Create a **service principal** for authentication to your private container registry according to the [Azure Official Document (Azure Container Registry authentication with service principals)](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-auth-service-principal). + We use the **Service principal ID** and the **Service principal password** in the next step. + +1. Create a `reg-acr-secrets` secret resource for pulling the container images from your private container registry. + ```console + kubectl create secret docker-registry reg-acr-secrets \ + --docker-server= \ + --docker-username= \ + --docker-password= + ``` + +1. Update the custom values file of the Helm Chart of a Scalar product you want to install. + You need to specify your private container registry as the value of `[].image.repository` in the custom values file. + Also, you need to specify the `reg-acr-secrets` as the value of `[].imagePullSecrets`. See the following examples based on the product you're using. + + + + ```yaml + scalardbCluster: + image: + repository: "example.azurecr.io/scalarinc/scalardb-cluster-node-azure-byol" + imagePullSecrets: + - name: "reg-acr-secrets" + ``` + + + Select the ScalarDL product you're using. + + + In the `scalardl-ledger-custom-values.yaml` file: + + ```yaml + ledger: + image: + repository: "example.azurecr.io/scalarinc/scalar-ledger" + imagePullSecrets: + - name: "reg-acr-secrets" + ``` + + + In the `scalardl-auditor-custom-values.yaml` file: + + ```yaml + auditor: + image: + repository: "example.azurecr.io/scalarinc/scalar-auditor" + imagePullSecrets: + - name: "reg-acr-secrets" + ``` + + + In the `schema-loader-custom-values.yaml` file: + + ```yaml + schemaLoading: + image: + repository: "example.azurecr.io/scalarinc/scalardl-schema-loader" + imagePullSecrets: + - name: "reg-acr-secrets" + ``` + + + + + +1. Deploy the Scalar product using the Helm Chart with the above custom values file. + * Examples + Please refer to the **Deploy containers on AKS (Azure Kubernetes Service) from your private container registry using Scalar Helm Charts** section of this document. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/BackupNoSQL.mdx b/versioned_docs/version-3.15/scalar-kubernetes/BackupNoSQL.mdx new file mode 100644 index 00000000..6882c8b1 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/BackupNoSQL.mdx @@ -0,0 +1,149 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Back up a NoSQL database in a Kubernetes environment + +This guide explains how to create a transactionally consistent backup of managed databases that ScalarDB or ScalarDL uses in a Kubernetes environment. Please note that, when using a NoSQL database or multiple databases, you **must** pause ScalarDB or ScalarDL to create a transactionally consistent backup. + +For details on how ScalarDB backs up databases, see [A Guide on How to Backup and Restore Databases Used Through ScalarDB](https://scalardb.scalar-labs.com/docs/latest/backup-restore/). + +In this guide, we assume that you are using point-in-time recovery (PITR) or its equivalent features. Therefore, we must create a period where there are no ongoing transactions for restoration. You can then restore data to that specific period by using PITR. If you restore data to a time without creating a period where there are no ongoing transactions, the restored data could be transactionally inconsistent, causing ScalarDB or ScalarDL to not work properly with the data. + +## Create a period to restore data, and perform a backup + +1. Check the following four points by running the `kubectl get pod` command before starting the backup operation: + * **The number of ScalarDB or ScalarDL pods.** Write down the number of pods so that you can compare that number with the number of pods after performing the backup. + * **The ScalarDB or ScalarDL pod names in the `NAME` column.** Write down the pod names so that you can compare those names with the pod names after performing the backup. + * **The ScalarDB or ScalarDL pod status is `Running` in the `STATUS` column.** Confirm that the pods are running before proceeding with the backup. You will need to pause the pods in the next step. + * **The restart count of each pod in the `RESTARTS` column.** Write down the restart count of each pod so that you can compare the count with the restart counts after performing the backup. +2. Pause the ScalarDB or ScalarDL pods by using `scalar-admin`. For details on how to pause the pods, see the [Details on using `scalar-admin`](BackupNoSQL.mdx#details-on-using-scalar-admin) section in this guide. +3. Write down the `pause completed` time. You will need to refer to that time when restoring the data by using the PITR feature. +4. Back up each database by using the backup feature. If you have enabled the automatic backup and PITR features, the managed databases will perform back up automatically. Please note that you should wait for approximately 10 seconds so that you can create a sufficiently long period to avoid a clock skew issue between the client clock and the database clock. This 10-second period is the exact period in which you can restore data by using the PITR feature. +5. Unpause ScalarDB or ScalarDL pods by using `scalar-admin`. For details on how to unpause the pods, see the [Details on using `scalar-admin`](BackupNoSQL.mdx#details-on-using-scalar-admin) section in this guide. +6. Check the `unpause started` time. You must check the `unpause started` time to confirm the exact period in which you can restore data by using the PITR feature. +7. Check the pod status after performing the backup. You must check the following four points by using the `kubectl get pod` command after the backup operation is completed. + * **The number of ScalarDB or ScalarDL pods.** Confirm this number matches the number of pods that you wrote down before performing the backup. + * **The ScalarDB or ScalarDL pod names in the `NAME` column.** Confirm the names match the pod names that you wrote down before performing the backup. + * **The ScalarDB or ScalarDL pod status is `Running` in the `STATUS` column.** + * **The restart count of each pod in the `RESTARTS` column.** Confirm the counts match the restart counts that you wrote down before performing the backup + + **If any of the two values are different, you must retry the backup operation from the beginning.** The reason for the different values may be caused by some pods being added or restarted while performing the backup. In such case, those pods will run in the `unpause` state. Pods in the `unpause` state will cause the backup data to be transactionally inconsistent. +8. **(Amazon DynamoDB only)** If you use the PITR feature of DynamoDB, you will need to perform additional steps to create a backup because the feature restores data with another name table by using PITR. For details on the additional steps after creating the exact period in which you can restore the data, please see [Restore databases in a Kubernetes environment](RestoreDatabase.mdx#amazon-dynamodb). + +## Back up multiple databases + +If you have two or more databases that the [Multi-storage Transactions](https://scalardb.scalar-labs.com/docs/latest/multi-storage-transactions/) or [Two-phase Commit Transactions](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions/) feature uses, you must pause all instances of ScalarDB or ScalarDL and create the same period where no ongoing transactions exist in the databases. + +To ensure consistency between multiple databases, you must restore the databases to the same point in time by using the PITR feature. + +## Details on using `scalar-admin` + +### Check the Kubernetes resource name + +You must specify the SRV service URL to the `-s (--srv-service-url)` flag. In Kubernetes environments, the format of the SRV service URL is `_my-port-name._my-port-protocol.my-svc.my-namespace.svc.cluster.local`. + +If you use Scalar Helm Charts to deploy ScalarDB or ScalarDL, the `my-svc` and `my-namespace` may vary depending on your environment. You must specify the headless service name as `my-svc` and the namespace as `my-namespace`. + +* Example + * ScalarDB Server + ```console + _scalardb._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Ledger + ```console + _scalardl-admin._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Auditor + ```console + _scalardl-auditor-admin._tcp.-headless..svc.cluster.local + ``` + +The helm release name decides the headless service name `-headless`. You can see the helm release name by running the following command: + +```console +helm list -n ns-scalar +``` + +You should see the following output: + +```console +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +scalardb ns-scalar 1 2023-02-09 19:31:40.527130674 +0900 JST deployed scalardb-2.5.0 3.8.0 +scalardl-auditor ns-scalar 1 2023-02-09 19:32:03.008986045 +0900 JST deployed scalardl-audit-2.5.1 3.7.1 +scalardl-ledger ns-scalar 1 2023-02-09 19:31:53.459548418 +0900 JST deployed scalardl-4.5.1 3.7.1 +``` + +You can also see the headless service name `-headless` by running the `kubectl get service` command. + +```console +kubectl get service -n ns-scalar +``` + +You should see the following output: + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-envoy LoadBalancer 10.99.245.143 60051:31110/TCP 2m2s +scalardb-envoy-metrics ClusterIP 10.104.56.87 9001/TCP 2m2s +scalardb-headless ClusterIP None 60051/TCP 2m2s +scalardb-metrics ClusterIP 10.111.213.194 8080/TCP 2m2s +scalardl-auditor-envoy LoadBalancer 10.111.141.43 40051:31553/TCP,40052:31171/TCP 99s +scalardl-auditor-envoy-metrics ClusterIP 10.104.245.188 9001/TCP 99s +scalardl-auditor-headless ClusterIP None 40051/TCP,40053/TCP,40052/TCP 99s +scalardl-auditor-metrics ClusterIP 10.105.119.158 8080/TCP 99s +scalardl-ledger-envoy LoadBalancer 10.96.239.167 50051:32714/TCP,50052:30857/TCP 109s +scalardl-ledger-envoy-metrics ClusterIP 10.97.204.18 9001/TCP 109s +scalardl-ledger-headless ClusterIP None 50051/TCP,50053/TCP,50052/TCP 109s +scalardl-ledger-metrics ClusterIP 10.104.216.189 8080/TCP 109s +``` + +### Pause + +You can send a pause request to ScalarDB or ScalarDL pods in a Kubernetes environment. + +* Example + * ScalarDB Server + ```console + kubectl run scalar-admin-pause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c pause -s _scalardb._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Ledger + ```console + kubectl run scalar-admin-pause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c pause -s _scalardl-admin._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Auditor + ```console + kubectl run scalar-admin-pause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c pause -s _scalardl-auditor-admin._tcp.-headless..svc.cluster.local + ``` + +### Unpause + +You can send an unpause request to ScalarDB or ScalarDL pods in a Kubernetes environment. + +* Example + * ScalarDB Server + ```console + kubectl run scalar-admin-unpause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c unpause -s _scalardb._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Ledger + ```console + kubectl run scalar-admin-unpause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c unpause -s _scalardl-admin._tcp.-headless..svc.cluster.local + ``` + * ScalarDL Auditor + ```console + kubectl run scalar-admin-unpause --image=ghcr.io/scalar-labs/scalar-admin: --restart=Never -it -- -c unpause -s _scalardl-auditor-admin._tcp.-headless..svc.cluster.local + ``` + +### Check the `pause completed` time and `unpause started` time + +The `scalar-admin` pods output the `pause completed` time and `unpause started` time to stdout. You can also see those times by running the `kubectl logs` command. + +```console +kubectl logs scalar-admin-pause +``` +```console +kubectl logs scalar-admin-unpause +``` diff --git a/versioned_docs/version-3.15/scalar-kubernetes/BackupRDB.mdx b/versioned_docs/version-3.15/scalar-kubernetes/BackupRDB.mdx new file mode 100644 index 00000000..804d6360 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/BackupRDB.mdx @@ -0,0 +1,21 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Back up an RDB in a Kubernetes environment + +This guide explains how to create a backup of a single relational database (RDB) that ScalarDB or ScalarDL uses in a Kubernetes environment. Please note that this guide assumes that you are using a managed database from a cloud services provider. + +If you have two or more RDBs that the [Multi-storage Transactions](https://scalardb.scalar-labs.com/docs/latest/multi-storage-transactions/) or [Two-phase Commit Transactions](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions/) feature uses, you must follow the instructions in [Back up a NoSQL database in a Kubernetes environment](BackupNoSQL.mdx) instead. + +## Perform a backup + +To perform backups, you should enable the automated backup feature available in the managed databases. By enabling this feature, you do not need to perform any additional backup operations. For details on the backup configurations in each managed database, see the following guides: + +* [Set up a database for ScalarDB/ScalarDL deployment on AWS](SetupDatabaseForAWS.mdx) +* [Set up a database for ScalarDB/ScalarDL deployment on Azure](SetupDatabaseForAzure.mdx) + +Because the managed RDB keeps backup data consistent from a transactions perspective, you can restore backup data to any point in time by using the point-in-time recovery (PITR) feature in the managed RDB. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/BackupRestoreGuide.mdx b/versioned_docs/version-3.15/scalar-kubernetes/BackupRestoreGuide.mdx new file mode 100644 index 00000000..8faabbd4 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/BackupRestoreGuide.mdx @@ -0,0 +1,48 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Back up and restore ScalarDB or ScalarDL data in a Kubernetes environment + +This guide explains how to backup and restore ScalarDB or ScalarDL data in a Kubernetes environment. Please note that this guide assumes that you are using a managed database from a cloud services provider as the backend database for ScalarDB or ScalarDL. The following is a list of the managed databases that this guide assumes you might be using: + +* NoSQL: does not support transactions + * Amazon DynamoDB + * Azure Cosmos DB for NoSQL +* Relational database (RDB): supports transactions + * Amazon RDS + * MySQL + * Oracle + * PostgreSQL + * SQL Server + * Amazon Aurora + * MySQL + * PostgreSQL + * Azure Database + * MySQL + * PostgreSQL + +For details on how to back up and restore databases used with ScalarDB in a transactionally consistent way, see [A Guide on How to Backup and Restore Databases Used Through ScalarDB](https://scalardb.scalar-labs.com/docs/latest/backup-restore/). + +## Perform a backup + +### Confirm the type of database and number of databases you are using + +How you perform backup and restore depends on the type of database (NoSQL or RDB) and the number of databases you are using. + +#### NoSQL or multiple databases + +If you are using a NoSQL database, or if you have two or more databases that the [Multi-storage Transactions](https://scalardb.scalar-labs.com/docs/latest/multi-storage-transactions/) or [Two-phase Commit Transactions](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions/) feature uses, please see [Back up a NoSQL database in a Kubernetes environment](BackupNoSQL.mdx) for details on how to perform a backup. + +#### Single RDB + +If you are using a single RDB, please see [Back up an RDB in a Kubernetes environment](BackupRDB.mdx) for details on how to perform a backup. + +If you have two or more RDBs that the [Multi-storage Transactions](https://scalardb.scalar-labs.com/docs/latest/multi-storage-transactions/) or [Two-phase Commit Transactions](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions/) feature uses, you must follow the instructions in [Back up a NoSQL database in a Kubernetes environment](BackupNoSQL.mdx) instead. + +## Restore a database + +For details on how to restore data from a managed database, please see [Restore databases in a Kubernetes environment](RestoreDatabase.mdx). diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDB.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDB.mdx new file mode 100644 index 00000000..2ea91d54 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDB.mdx @@ -0,0 +1,104 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsEnglish +--- + +# Guidelines for creating an AKS cluster for ScalarDB Server + +This document explains the requirements and recommendations for creating an Azure Kubernetes Service (AKS) cluster for ScalarDB Server deployment. For details on how to deploy ScalarDB Server on an AKS cluster, see [Deploy ScalarDB Server on AKS](ManualDeploymentGuideScalarDBServerOnAKS.mdx). + +## Before you begin + +You must create an AKS cluster based on the following requirements, recommendations, and your project's requirements. For specific details about how to create an AKS cluster, refer to the following official Microsoft documentation based on the tool you use in your environment: + +* [Azure CLI](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-cli) +* [PowerShell](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-powershell) +* [Azure portal](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal) + +## Requirements + +When deploying ScalarDB Server, you must: + +* Create the AKS cluster by using a [supported Kubernetes version](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes). +* Configure the AKS cluster based on the version of Kubernetes and your project's requirements. + +## Recommendations (optional) + +The following are some recommendations for deploying ScalarDB Server. These recommendations are not required, so you can choose whether or not to apply these recommendations based on your needs. + +### Create at least three worker nodes and three pods + +To ensure that the AKS cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardb-custom-values.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different [availability zones](https://learn.microsoft.com/en-us/azure/availability-zones/az-overview) (AZs), you can withstand an AZ failure. + +::: + +### Use 4vCPU / 8GB memory nodes for the worker node in the ScalarDB Server node pool + +From the perspective of commercial licenses, resources for one pod running ScalarDB Server are limited to 2vCPU / 4GB memory. In addition to the ScalarDB Server pod, Kubernetes could deploy some of the following components to each worker node: + +* ScalarDB Server pod (2vCPU / 4GB) +* Envoy proxy +* Your application pods (if you choose to run your application's pods on the same worker node) +* Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) +* Kubernetes components + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [Create at least three worker nodes and three pods](#create-at-least-three-worker-nodes-and-three-pods). + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum for production environment. You should also consider the resources of the AKS cluster (for example, the number of worker nodes, vCPUs per node, memory per node, ScalarDB Server pods, and pods for your application), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Create a node pool for ScalarDB Server pods + +AKS creates one system node pool named **agentpool** that is preferred for system pods (used to keep AKS running) by default. We recommend creating another node pool with **user** mode for ScalarDB Server pods and deploying ScalarDB Server pods on this additional node pool. + +### Configure cluster autoscaler in AKS + +If you want to scale ScalarDB Server pods automatically by using [Horizontal Pod Autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#horizontal-pod-autoscaler), you should configure cluster autoscaler in AKS too. For details, refer to the official Microsoft documentation at [Cluster autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#cluster-autoscaler). + +In addition, if you configure cluster autoscaler, you should create a subnet in a virtual network (VNet) for AKS to ensure a sufficient number of IPs exist so that AKS can work without network issues after scaling. The required number of IPs varies depending on the networking plug-in. For more details about the number of IPs required, refer to the following: + +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### Create the AKS cluster on a private network + +You should create the AKS cluster on a private network (private subnet in a VNet) since ScalarDB Server does not provide any services to users directly via internet access. We recommend accessing ScalarDB Server via a private network from your applications. + +### Create the AKS cluster by using Azure CNI, if necessary + +The AKS default networking plug-in is [kubenet](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet). If your requirement does not match kubenet, you should use [Azure Container Networking Interface (CNI)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni). + +For example, if you want to deploy multiple ScalarDB Server environments on one AKS cluster (e.g., deploy a multi-tenant ScalarDB Server) and you want to control the connection between each tenant by using [Kubernetes NetworkPolicies](https://kubernetes.io/docs/concepts/services-networking/network-policies/), kubenet supports only the Calico Network Policy, which the [Azure support team does not support](https://learn.microsoft.com/en-us/azure/aks/use-network-policies#differences-between-azure-network-policy-manager-and-calico-network-policy-and-their-capabilities). Please note that the Calico Network Policy is supported only by the Calico community or through additional paid support. + +The Azure support and engineering teams, however, do support Azure CNI. So, if you want to use Kubernetes NetworkPolicies and receive support from the Azure support team, you should use Azure CNI. For more details about the differences between kubenet and Azure CNI, refer to the following official Microsoft documentation: + +* [Network concepts for applications in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/concepts-network) +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### Restrict connections by using some security features based on your requirements + +You should restrict unused connections in ScalarDB Server. To restrict unused connections, you can use some security features in Azure, like [network security groups](https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview). + +The connections (ports) that ScalarDB Server uses by default are as follows: + +* ScalarDB Server + * 60051/TCP (accepts requests from a client) + * 8080/TCP (accepts monitoring requests) +* Scalar Envoy (used with ScalarDB Server) + * 60051/TCP (load balancing for ScalarDB Server) + * 9001/TCP (accepts monitoring requests for Scalar Envoy itself) + +:::note + +- If you change the default listening port for ScalarDB Server in the configuration file (`database.properties`), you must allow connections by using the port that you configured. +- You must also allow the connections that AKS uses itself. For more details about AKS traffic requirements, refer to [Control egress traffic using Azure Firewall in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/limit-egress-traffic). + +::: + diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDL.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDL.mdx new file mode 100644 index 00000000..e0247988 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDL.mdx @@ -0,0 +1,109 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Guidelines for creating an AKS cluster for ScalarDL Ledger + +This document explains the requirements and recommendations for creating an Azure Kubernetes Service (AKS) cluster for ScalarDL Ledger deployment. For details on how to deploy ScalarDL Ledger on an AKS cluster, see [Deploy ScalarDL Ledger on AKS](ManualDeploymentGuideScalarDLOnAKS.mdx). + +## Before you begin + +You must create an AKS cluster based on the following requirements, recommendations, and your project's requirements. For specific details about how to create an AKS cluster, refer to the following official Microsoft documentation based on the tool you use in your environment: + +* [Azure CLI](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-cli) +* [PowerShell](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-powershell) +* [Azure portal](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal) + +## Requirements + +When deploying ScalarDL Ledger, you must: + +* Create the AKS cluster by using a [supported Kubernetes version](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes). +* Configure the AKS cluster based on the version of Kubernetes and your project's requirements. + +:::warning + +For Byzantine fault detection in ScalarDL to work properly, do not deploy your application pods on the same AKS cluster as the ScalarDL Ledger deployment. + +::: + +## Recommendations (optional) + +The following are some recommendations for deploying ScalarDL Ledger. These recommendations are not required, so you can choose whether or not to apply these recommendations based on your needs. + +### Create at least three worker nodes and three pods + +To ensure that the AKS cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different [availability zones](https://learn.microsoft.com/en-us/azure/availability-zones/az-overview) (AZs), you can withstand an AZ failure. + +::: + +### Use 4vCPU / 8GB memory nodes for the worker node in the ScalarDL Ledger node pool + +From the perspective of commercial licenses, resources for one pod running ScalarDL Ledger are limited to 2vCPU / 4GB memory. In addition to the ScalarDL Ledger pod, Kubernetes could deploy some of the following components to each worker node: + +* ScalarDL Ledger pod (2vCPU / 4GB) +* Envoy proxy +* Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) +* Kubernetes components + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [Create at least three worker nodes and three pods](#create-at-least-three-worker-nodes-and-three-pods). + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum environment for production. You should also consider the resources of the AKS cluster (for example, the number of worker nodes, vCPUs per node, memory per node, and ScalarDL Ledger pods), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Create a node pool for ScalarDL Ledger pods + +AKS creates one system node pool named **agentpool** that is preferred for system pods (used to keep AKS running) by default. We recommend creating another node pool with **user** mode for ScalarDL Ledger pods and deploying ScalarDL Ledger pods on this additional node pool. + +### Configure cluster autoscaler in AKS + +If you want to scale ScalarDL Ledger pods automatically by using [Horizontal Pod Autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#horizontal-pod-autoscaler), you should configure cluster autoscaler in AKS too. For details, refer to the official Microsoft documentation at [Cluster autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#cluster-autoscaler). + +In addition, if you configure cluster autoscaler, you should create a subnet in a virtual network (VNet) for AKS to ensure a sufficient number of IPs exist so that AKS can work without network issues after scaling. The required number of IPs varies depending on the networking plug-in. For more details about the number of IPs required, refer to the following: + +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### Create the AKS cluster on a private network + +You should create the AKS cluster on a private network (private subnet in a VNet) since ScalarDL Ledger does not provide any services to users directly via internet access. We recommend accessing ScalarDL Ledger via a private network from your applications. + +### Create the AKS cluster by using Azure CNI, if necessary + +The AKS default networking plug-in is [kubenet](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet). If your requirement does not match kubenet, you should use [Azure Container Networking Interface (CNI)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni). + +For example, if you want to deploy multiple ScalarDL Ledger environments on one AKS cluster (e.g., deploy multi-tenant ScalarDL Ledger) and you want to control the connection between each tenant by using [Kubernetes NetworkPolicies](https://kubernetes.io/docs/concepts/services-networking/network-policies/), kubenet supports only the Calico Network Policy, which the [Azure support team does not support](https://learn.microsoft.com/en-us/azure/aks/use-network-policies#differences-between-azure-network-policy-manager-and-calico-network-policy-and-their-capabilities). Please note that the Calico Network Policy is supported only by the Calico community or through additional paid support. + +The Azure support and engineering teams, however, do support Azure CNI. So, if you want to use Kubernetes NetworkPolicies and receive support from the Azure support team, you should use Azure CNI. For more details about the differences between kubenet and Azure CNI, refer to the following official Microsoft documentation: + +* [Network concepts for applications in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/concepts-network) +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### Restrict connections by using some security features based on your requirements + +You should restrict unused connections in ScalarDL Ledger. To restrict unused connections, you can use some security features in Azure, like [network security groups](https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview). + +The connections (ports) that ScalarDL Ledger uses by default are as follows: + +* ScalarDL Ledger + * 50051/TCP (accepts requests from a client) + * 50052/TCP (accepts privileged requests from a client) + * 50053/TCP (accepts pause and unpause requests from a scalar-admin client tool) + * 8080/TCP (accepts monitoring requests) +* Scalar Envoy (used with ScalarDL Ledger) + * 50051/TCP (load balancing for ScalarDL Ledger) + * 50052/TCP (load balancing for ScalarDL Ledger) + * 9001/TCP (accepts monitoring requests for Scalar Envoy itself) + +:::note + +- If you change the default listening port for ScalarDL Ledger in the configuration file (`ledger.properties`), you must allow connections by using the port that you configured. +- You must also allow the connections that AKS uses itself. For more details about AKS traffic requirements, refer to [Control egress traffic using Azure Firewall in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/limit-egress-traffic). + +::: diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDLAuditor.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDLAuditor.mdx new file mode 100644 index 00000000..6aab7b7f --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarDLAuditor.mdx @@ -0,0 +1,128 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Guidelines for creating an AKS cluster for ScalarDL Ledger and ScalarDL Auditor + +This document explains the requirements and recommendations for creating an Azure Kubernetes Service (AKS) cluster for ScalarDL Ledger and ScalarDL Auditor deployment. For details on how to deploy ScalarDL Ledger and ScalarDL Auditor on an AKS cluster, see [Deploy ScalarDL Ledger and ScalarDL Auditor on AKS](ManualDeploymentGuideScalarDLAuditorOnAKS.mdx). + +## Before you begin + +You must create an AKS cluster based on the following requirements, recommendations, and your project's requirements. For specific details about how to create an AKS cluster, refer to the following official Microsoft documentation based on the tool you use in your environment: + +* [Azure CLI](https://learn.microsoft.com/ja-jp/azure/aks/learn/quick-kubernetes-deploy-cli) +* [PowerShell](https://learn.microsoft.com/ja-jp/azure/aks/learn/quick-kubernetes-deploy-powershell) +* [Azure portal](https://learn.microsoft.com/ja-jp/azure/aks/learn/quick-kubernetes-deploy-portal) + +## Requirements + +When deploying ScalarDL Ledger and ScalarDL Auditor, you must: + +* Create two AKS clusters by using a [supported Kubernetes version](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes). + * One AKS cluster for ScalarDL Ledger + * One AKS cluster for ScalarDL Auditor +* Configure the AKS clusters based on the version of Kubernetes and your project's requirements. +* Configure a virtual network (VNet) as follows. + * Connect the **VNet of AKS (for Ledger)** and the **VNet of AKS (for Auditor)** by using [virtual network peering](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-manage-peering). To do so, you must specify the different IP ranges for the **VNet of AKS (for Ledger)** and the **VNet of AKS (for Auditor)** when you create those VNets. + * Allow **connections between Ledger and Auditor** to make ScalarDL (Auditor mode) work properly. + * For more details about these network requirements, refer to [Configure Network Peering for ScalarDL Auditor Mode](NetworkPeeringForScalarDLAuditor.mdx). + +:::warning + +For Byzantine fault detection in ScalarDL to work properly, do not deploy your application pods on the same AKS clusters as the ScalarDL Ledger and ScalarDL Auditor deployments. + +::: + +## Recommendations (optional) + +The following are some recommendations for deploying ScalarDL Ledger and ScalarDL Auditor. These recommendations are not required, so you can choose whether or not to apply these recommendations based on your needs. + +### Create at least three worker nodes and three pods per AKS cluster + +To ensure that the AKS cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [ScalarDL Ledger sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml) and [ScalarDL Auditor sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-audit-custom-values.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different [availability zones](https://learn.microsoft.com/en-us/azure/availability-zones/az-overview) (AZs), you can withstand an AZ failure. + +::: + +### Use 4vCPU / 8GB memory nodes for the worker node in the ScalarDL Ledger and ScalarDL Auditor node pool + +From the perspective of commercial licenses, resources for each pod running ScalarDL Ledger or ScalarDL Auditor are limited to 2vCPU / 4GB memory. In addition to the ScalarDL Ledger and ScalarDL Auditor pods, Kubernetes could deploy some of the following components to each worker node: + +* AKS cluster for ScalarDL Ledger + * ScalarDL Ledger pod (2vCPU / 4GB) + * Envoy proxy + * Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) + * Kubernetes components +* AKS cluster for ScalarDL Auditor + * ScalarDL Auditor pod (2vCPU / 4GB) + * Envoy proxy + * Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) + * Kubernetes components + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [Create at least three worker nodes and three pods](#create-at-least-three-worker-nodes-and-three-pods-per-aks-cluster). And remember, for Byzantine fault detection to work properly, you cannot deploy your application pods on the same AKS clusters as the ScalarDL Ledger and ScalarDL Auditor deployments. + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum environment for production. You should also consider the resources of the AKS cluster (for example, the number of worker nodes, vCPUs per node, memory per node, ScalarDL Ledger pods, and ScalarDL Auditor pods), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Create node pools for ScalarDL Ledger and ScalarDL Auditor pods + +AKS creates one system node pool named **agentpool** that is preferred for system pods (used to keep AKS running) by default. We recommend creating additional node pools with **user** mode for ScalarDL Ledger and ScalarDL Auditor pods and deploying ScalarDL Ledger and ScalarDL Auditor pods on those additional node pools. + +### Configure cluster autoscaler in AKS + +If you want to scale ScalarDL Ledger and ScalarDL Auditor pods automatically by using [Horizontal Pod Autoscaler)](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#horizontal-pod-autoscaler), you should configure cluster autoscaler in AKS too. For details, refer to the official Microsoft documentation at [Cluster autoscaler](https://learn.microsoft.com/en-us/azure/aks/concepts-scale#cluster-autoscaler). + +In addition, if you configure cluster autoscaler, you should create a subnet in a VNet for AKS to ensure a sufficient number of IPs exist so that AKS can work without network issues after scaling. The required number of IPs varies depending on the networking plug-in. For more details about the number of IPs required, refer to the following: + +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### Create the AKS cluster on a private network + +You should create the AKS cluster on a private network (private subnet in a VNet) since ScalarDL Ledger and ScalarDL Auditor do not provide any services to users directly via internet access. We recommend accessing ScalarDL Ledger and ScalarDL Auditor via a private network from your applications. + +### Create the AKS cluster by using Azure CNI, if necessary + +The AKS default networking plug-in is [kubenet](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet). If your requirement does not match kubenet, you should use [Azure Container Networking Interface (CNI)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni). + +For example, if you want to deploy multiple ScalarDL Ledger and ScalarDL Auditor environments on only one AKS cluster instead of two AKS clusters (e.g., deploy multi-tenant ScalarDL) and control the connection between each tenant by using [Kubernetes NetworkPolicies](https://kubernetes.io/docs/concepts/services-networking/network-policies/), kubenet supports only the Calico Network Policy, which the [Azure support team does not support](https://learn.microsoft.com/en-us/azure/aks/use-network-policies#differences-between-azure-network-policy-manager-and-calico-network-policy-and-their-capabilities). Please note that the Calico Network Policy is supported only by the Calico community or through additional paid support. + +The Azure support and engineering teams, however, do support Azure CNI. So, if you want to use Kubernetes NetworkPolicies and receive support from the Azure support team, you should use Azure CNI. For more details about the differences between kubenet and Azure CNI, refer to the following official Microsoft documentation: + +* [Network concepts for applications in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/concepts-network) +* [Use kubenet networking with your own IP address ranges in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-kubenet) +* [Configure Azure CNI networking in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/configure-azure-cni) + +### Restrict connections by using some security features based on your requirements + +You should restrict unused connections in ScalarDL and ScalarDL Auditor. To restrict unused connections, you can use some security features of Azure, like [network security groups](https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview). + +The connections (ports) that ScalarDL Ledger and ScalarDL Auditor use by default are as follows: + +* ScalarDL Ledger + * 50051/TCP (accepts requests from a client and ScalarDL Auditor) + * 50052/TCP (accepts privileged requests from a client and ScalarDL Auditor) + * 50053/TCP (accepts pause/unpause requests from a scalar-admin client tool) + * 8080/TCP (accepts monitoring requests) +* ScalarDL Auditor + * 40051/TCP (accepts requests from a client) + * 40052/TCP (accepts privileged requests from a client) + * 40053/TCP (accepts pause and unpause requests from a scalar-admin client tool) + * 8080/TCP (accepts monitoring requests) +* Scalar Envoy (used with ScalarDL Ledger and ScalarDL Auditor) + * 50051/TCP (load balancing for ScalarDL Ledger) + * 50052/TCP (load balancing for ScalarDL Ledger) + * 40051/TCP (load balancing for ScalarDL Auditor) + * 40052/TCP (load balancing for ScalarDL Auditor) + * 9001/TCP (accepts monitoring requests for Scalar Envoy itself) + +:::note + +- If you change the default listening port for ScalarDL Ledger and ScalarDL Auditor in their configuration files (`ledger.properties` and `auditor.properties`, respectively), you must allow connections by using the port that you configured. +- You must also allow the connections that AKS uses itself. For more details about AKS traffic requirements, refer to [Control egress traffic using Azure Firewall in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/limit-egress-traffic). + +::: diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarProducts.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarProducts.mdx new file mode 100644 index 00000000..0ecd0034 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateAKSClusterForScalarProducts.mdx @@ -0,0 +1,20 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Guidelines for creating an AKS cluster for Scalar products + +To create an Azure Kubernetes Service (AKS) cluster for Scalar products, refer to the following: + +* [Guidelines for creating an AKS cluster for ScalarDB Server](CreateAKSClusterForScalarDB.mdx) +* [Guidelines for creating an AKS cluster for ScalarDL Ledger](CreateAKSClusterForScalarDL.mdx) +* [Guidelines for creating an AKS cluster for ScalarDL Ledger and ScalarDL Auditor](CreateAKSClusterForScalarDLAuditor.mdx) + +To deploy Scalar products on AKS, refer to the following: + +* [Deploy ScalarDB Server on AKS](ManualDeploymentGuideScalarDBServerOnAKS.mdx) +* [Deploy ScalarDL Ledger on AKS](ManualDeploymentGuideScalarDLOnAKS.mdx) +* [Deploy ScalarDL Ledger and ScalarDL Auditor on AKS](ManualDeploymentGuideScalarDLAuditorOnAKS.mdx) diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateBastionServer.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateBastionServer.mdx new file mode 100644 index 00000000..331c147f --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateBastionServer.mdx @@ -0,0 +1,47 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Create a bastion server + +This document explains how to create a bastion server and install some tools for the deployment of Scalar products. + +## Create a server on the same private network as a Kubernetes cluster + +It is recommended to create a Kubernetes cluster for Scalar products on a private network. If you create a Kubernetes cluster on a private network, you should create a bastion server on the same private network to access your Kubernetes cluster. + +## Install tools + +Please install the following tools on the bastion server according to their official documents. + +* [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) +* [helm](https://helm.sh/docs/intro/install/) + +## Configure kubeconfig + +After you install the kubectl command, you must configure a **kubeconfig** to access your Kubernetes cluster. Please refer to the following official document for more details on how to configure kubeconfig in each managed Kubernetes. + +If you use Amazon EKS (Amazon Elastic Kubernetes Service), you must install the **AWS CLI** according to the official document [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html). After that, you can see how to configure kubeconfig in [Creating or updating a kubeconfig file for an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html). + +If you use AKS (Azure Kubernetes Service), you must install the **Azure CLI** according to the official document [How to install the Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli). After that, you can see how to configure kubeconfig in [az aks get-credentials](https://learn.microsoft.com/en-us/cli/azure/aks?view=azure-cli-latest#az-aks-get-credentials). + +## Check installation + +You can check if the tools are installed as follows. + +* kubectl + ```console + kubectl version --client + ``` +* helm + ```console + helm version + ``` + +You can also check if your kubeconfig is properly configured as follows. If you see a URL response, kubectl is correctly configured to access your cluster. +```console +kubectl cluster-info +``` diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDB.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDB.mdx new file mode 100644 index 00000000..56d8c918 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDB.mdx @@ -0,0 +1,86 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsEnglish +--- + +# (Deprecated) Guidelines for creating an EKS cluster for ScalarDB Server + +:::warning + +ScalarDB Server is now deprecated. Please use [ScalarDB Cluster](ManualDeploymentGuideScalarDBClusterOnEKS.mdx) instead. + +::: + +This document explains the requirements and recommendations for creating an Amazon Elastic Kubernetes Service (EKS) cluster for ScalarDB Server deployment. For details on how to deploy ScalarDB Server on an EKS cluster, see [Deploy ScalarDB Server on Amazon EKS](ManualDeploymentGuideScalarDBServerOnEKS.mdx). + +## Before you begin + +You must create an EKS cluster based on the following requirements, recommendations, and your project's requirements. For specific details about how to create an EKS cluster, see the official Amazon documentation at [Creating an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html). + +## Requirements + +When deploying ScalarDB Server, you must: + +* Create the EKS cluster by using a [supported Kubernetes version](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes). +* Configure the EKS cluster based on the version of Kubernetes and your project's requirements. + +## Recommendations (optional) + +The following are some recommendations for deploying ScalarDB Server. These recommendations are not required, so you can choose whether or not to apply these recommendations based on your needs. + +### Create at least three worker nodes and three pods + +To ensure that the EKS cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardb-custom-values.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different [availability zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) (AZs), you can withstand an AZ failure. + +::: + +### Use 4vCPU / 8GB memory nodes for the worker node in the ScalarDB Server node group + +From the perspective of commercial licenses, resources for one pod running ScalarDB Server are limited to 2vCPU / 4GB memory. In addition to the ScalarDB Server pod, Kubernetes could deploy some of the following components to each worker node: + +* ScalarDB Server pod (2vCPU / 4GB) +* Envoy proxy +* Your application pods (if you choose to run your application's pods on the same worker node) +* Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) +* Kubernetes components + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [Create at least three worker nodes and three pods](#create-at-least-three-worker-nodes-and-three-pods). + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum for production environment. You should also consider the resources of the EKS cluster (for example, the number of worker nodes, vCPUs per node, memory per node, ScalarDB Server pods, and pods for your application), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Configure Cluster Autoscaler in EKS + +If you want to scale ScalarDB Server pods automatically by using [Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html), you should configure Cluster Autoscaler in EKS too. For details, see the official Amazon documentation at [Autoscaling](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html#cluster-autoscaler). + +In addition, if you configure Cluster Autoscaler, you should create a subnet in an Amazon Virtual Private Cloud (VPC) for EKS with the prefix (e.g., `/24`) to ensure a sufficient number of IPs exist so that EKS can work without network issues after scaling. + +### Create the EKS cluster on a private network + +You should create the EKS cluster on a private network (private subnet in a VPC) since ScalarDB Server does not provide any services to users directly via internet access. We recommend accessing ScalarDB Server via a private network from your applications. + +### Restrict connections by using some security features based on your requirements + +You should restrict unused connections in ScalarDB Server. To restrict unused connections, you can use some security features in AWS, like [security groups](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) and [network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html). + +The connections (ports) that ScalarDB Server uses by default are as follows: + +* ScalarDB Server + * 60051/TCP (accepts requests from a client) + * 8080/TCP (accepts monitoring requests) +* Scalar Envoy (used with ScalarDB Server) + * 60051/TCP (load balancing for ScalarDB Server) + * 9001/TCP (accepts monitoring requests for Scalar Envoy itself) + +:::note + +- If you change the default listening port for ScalarDB Server in the configuration file (`database.properties`), you must allow connections by using the port that you configured. +- You must also allow the connections that EKS uses itself. For more details about Amazon EKS security group requirements, refer to [Amazon EKS security group requirements and considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html). + +::: diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDBCluster.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDBCluster.mdx new file mode 100644 index 00000000..73ffe005 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDBCluster.mdx @@ -0,0 +1,86 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Guidelines for creating an EKS cluster for ScalarDB Cluster + +This document explains the requirements and recommendations for creating an Amazon Elastic Kubernetes Service (EKS) cluster for ScalarDB Cluster deployment. For details on how to deploy ScalarDB Cluster on an EKS cluster, see [Deploy ScalarDB Cluster on Amazon EKS](ManualDeploymentGuideScalarDBClusterOnEKS.mdx). + +## Before you begin + +You must create an EKS cluster based on the following requirements, recommendations, and your project's requirements. For specific details about how to create an EKS cluster, see the official Amazon documentation at [Creating an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html). + +## Requirements + +When deploying ScalarDB Cluster, you must: + +* Create the EKS cluster by using a [supported Kubernetes version](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes). +* Configure the EKS cluster based on the version of Kubernetes and your project's requirements. + +## Recommendations (optional) + +The following are some recommendations for deploying ScalarDB Cluster. These recommendations are not required, so you can choose whether or not to apply these recommendations based on your needs. + +### Create at least three worker nodes and three pods + +To ensure that the EKS cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardb-cluster-custom-values-indirect-mode.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different [availability zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) (AZs), you can withstand an AZ failure. + +::: + +### Use 4vCPU / 8GB memory nodes for the worker node in the ScalarDB Cluster node group + +From the perspective of commercial licenses, resources for one pod running ScalarDB Cluster are limited to 2vCPU / 4GB memory. In addition to the ScalarDB Cluster pod, Kubernetes could deploy some of the following components to each worker node: + +* ScalarDB Cluster pod (2vCPU / 4GB) +* Envoy proxy (if you use `indirect` client mode or use a programming language other than Java) +* Your application pods (if you choose to run your application's pods on the same worker node) +* Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) +* Kubernetes components + +:::note + +You do not need to deploy an Envoy pod when using `direct-kubernetes` mode. + +::: + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [Create at least three worker nodes and three pods](#create-at-least-three-worker-nodes-and-three-pods). + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum for production environment. You should also consider the resources of the EKS cluster (for example, the number of worker nodes, vCPUs per node, memory per node, ScalarDB Cluster pods, and pods for your application), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Configure Cluster Autoscaler in EKS + +If you want to scale ScalarDB Cluster pods automatically by using [Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html), you should configure Cluster Autoscaler in EKS too. For details, see the official Amazon documentation at [Autoscaling](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html#cluster-autoscaler). + +In addition, if you configure Cluster Autoscaler, you should create a subnet in an Amazon Virtual Private Cloud (VPC) for EKS with the prefix (e.g., `/24`) to ensure a sufficient number of IPs exist so that EKS can work without network issues after scaling. + +### Create the EKS cluster on a private network + +You should create the EKS cluster on a private network (private subnet in a VPC) since ScalarDB Cluster does not provide any services to users directly via internet access. We recommend accessing ScalarDB Cluster via a private network from your applications. + +### Restrict connections by using some security features based on your requirements + +You should restrict unused connections in ScalarDB Cluster. To restrict unused connections, you can use some security features in AWS, like [security groups](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) and [network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html). + +The connections (ports) that ScalarDB Cluster uses by default are as follows: + +* ScalarDB Cluster + * 60053/TCP (accepts gRPC or SQL requests from a client) + * 8080/TCP (accepts GraphQL requests from a client) + * 9080/TCP (accepts monitoring requests) +* Scalar Envoy (used with ScalarDB Cluster `indirect` mode) + * 60053/TCP (load balancing for ScalarDB Cluster) + * 9001/TCP (accepts monitoring requests for Scalar Envoy itself) + +:::note + +- If you change the default listening port for ScalarDB Cluster in the configuration file (`scalardb-cluster-node.properties`), you must allow connections by using the port that you configured. +- You must also allow the connections that EKS uses itself. For more details about Amazon EKS security group requirements, refer to [Amazon EKS security group requirements and considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html). + +::: diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDL.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDL.mdx new file mode 100644 index 00000000..f5ba08e6 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDL.mdx @@ -0,0 +1,86 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Guidelines for creating an EKS cluster for ScalarDL Ledger + +This document explains the requirements and recommendations for creating an Amazon Elastic Kubernetes Service (EKS) cluster for ScalarDL Ledger deployment. For details on how to deploy ScalarDL Ledger on an EKS cluster, see [Deploy ScalarDL Ledger on Amazon EKS](ManualDeploymentGuideScalarDLOnEKS.mdx). + +## Before you begin + +You must create an EKS cluster based on the following requirements, recommendations, and your project's requirements. For specific details about how to create an EKS cluster, see the official Amazon documentation at [Creating an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html). + +## Requirements + +When deploying ScalarDL Ledger, you must: + +* Create the EKS cluster by using a [supported Kubernetes version](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes). +* Configure the EKS cluster based on the version of Kubernetes and your project's requirements. + +:::warning + +For Byzantine fault detection in ScalarDL to work properly, do not deploy your application pods on the same EKS cluster as the ScalarDL Ledger deployment. + +::: + +## Recommendations (optional) + +The following are some recommendations for deploying ScalarDL Ledger. These recommendations are not required, so you can choose whether or not to apply these recommendations based on your needs. + +### Create at least three worker nodes and three pods + +To ensure that the EKS cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different [availability zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) (AZs), you can withstand an AZ failure. + +::: + +### Use 4vCPU / 8GB memory nodes for the worker node in the ScalarDL Ledger node group + +From the perspective of commercial licenses, resources for one pod running ScalarDL Ledger are limited to 2vCPU / 4GB memory. In addition to the ScalarDL Ledger pod, Kubernetes could deploy some of the following components to each worker node: + +* ScalarDL Ledger pod (2vCPU / 4GB) +* Envoy proxy +* Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) +* Kubernetes components + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [Create at least three worker nodes and three pods](#create-at-least-three-worker-nodes-and-three-pods). + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum environment for production. You should also consider the resources of the EKS cluster (for example, the number of worker nodes, vCPUs per node, memory per node, and ScalarDL Ledger pods), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Configure Cluster Autoscaler in EKS + +If you want to scale ScalarDL Ledger pods automatically by using [Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html), you should configure Cluster Autoscaler in EKS too. For details, see the official Amazon documentation at [Autoscaling](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html#cluster-autoscaler). + +In addition, if you configure Cluster Autoscaler, you should create a subnet in an Amazon Virtual Private Cloud (VPC) for EKS with the prefix (e.g., `/24`) to ensure a sufficient number of IPs exist so that EKS can work without network issues after scaling. + +### Create the EKS cluster on a private network + +You should create the EKS cluster on a private network (private subnet in a VPC) since ScalarDL Ledger does not provide any services to users directly via internet access. We recommend accessing ScalarDL Ledger via a private network from your applications. + +### Restrict connections by using some security features based on your requirements + +You should restrict unused connections in ScalarDL Ledger. To restrict unused connections, you can use some security features in AWS, like [security groups](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) and [network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html). + +The connections (ports) that ScalarDL Ledger uses by default are as follows: + +* ScalarDL Ledger + * 50051/TCP (Accept the requests from a client) + * 50052/TCP (accepts privileged requests from a client) + * 50053/TCP (accepts pause and unpause requests from a scalar-admin client tool) + * 8080/TCP (accepts monitoring requests) +* Scalar Envoy (used with ScalarDL Ledger) + * 50051/TCP (load balancing for ScalarDL Ledger) + * 50052/TCP (load balancing for ScalarDL Ledger) + * 9001/TCP (accepts monitoring requests for Scalar Envoy itself) + +:::note + +- If you change the default listening port for ScalarDL Ledger in the configuration file (`ledger.properties`), you must allow connections by using the port that you configured. +- You must also allow the connections that EKS uses itself. For more details about Amazon EKS security group requirements, refer to [Amazon EKS security group requirements and considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html). + +::: diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDLAuditor.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDLAuditor.mdx new file mode 100644 index 00000000..d0d0f952 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarDLAuditor.mdx @@ -0,0 +1,105 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Guidelines for creating an EKS cluster for ScalarDL Ledger and ScalarDL Auditor + +This document explains the requirements and recommendations for creating an Amazon Elastic Kubernetes Service (EKS) cluster for ScalarDL Ledger and ScalarDL Auditor deployment. For details on how to deploy ScalarDL Ledger and ScalarDL Auditor on an EKS cluster, see [Deploy ScalarDL Ledger and ScalarDL Auditor on Amazon EKS](ManualDeploymentGuideScalarDLAuditorOnEKS.mdx). + +## Before you begin + +You must create an EKS cluster based on the following requirements, recommendations, and your project's requirements. For specific details about how to create an EKS cluster, see the official Amazon documentation at [Creating an Amazon EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html). + +## Requirements + +When deploying ScalarDL Ledger and ScalarDL Auditor, you must: + +* Create two EKS clusters by using a [supported Kubernetes version](https://scalardb.scalar-labs.com/docs/latest/requirements/#kubernetes). + * One EKS cluster for ScalarDL Ledger + * One EKS cluster for ScalarDL Auditor +* Configure the EKS clusters based on the version of Kubernetes and your project's requirements. +* Configure an Amazon Virtual Private Cloud (VPC) as follows. + * Connect the **VPC of EKS (for Ledger)** and the **VPC of EKS (for Auditor)** by using [VPC peering](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html). To do so, you must specify the different IP ranges for the **VPC of EKS (for Ledger)** and the **VPC of EKS (for Auditor)** when you create those VPCs. + * Allow **connections between Ledger and Auditor** to make ScalarDL (Auditor mode) work properly. + * For more details about these network requirements, refer to [Configure Network Peering for ScalarDL Auditor Mode](NetworkPeeringForScalarDLAuditor.mdx). + +:::warning + +For Byzantine fault detection in ScalarDL to work properly, do not deploy your application pods on the same EKS clusters as the ScalarDL Ledger and ScalarDL Auditor deployments. + +::: + +## Recommendations (optional) + +The following are some recommendations for deploying ScalarDL Ledger and ScalarDL Auditor. These recommendations are not required, so you can choose whether or not to apply these recommendations based on your needs. + +### Create at least three worker nodes and three pods per EKS cluster + +To ensure that the EKS cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [ScalarDL Ledger sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml) and [ScalarDL Auditor sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-audit-custom-values.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different [availability zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) (AZs), you can withstand an AZ failure. + +::: + +### Use 4vCPU / 8GB memory nodes for the worker node in the ScalarDL Ledger and ScalarDL Auditor node group + +From the perspective of commercial licenses, resources for each pod running ScalarDL Ledger or ScalarDL Auditor are limited to 2vCPU / 4GB memory. In addition to the ScalarDL Ledger and ScalarDL Auditor pods, Kubernetes could deploy some of the following components to each worker node: + +* EKS cluster for ScalarDL Ledger + * ScalarDL Ledger pod (2vCPU / 4GB) + * Envoy proxy + * Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) + * Kubernetes components +* EKS cluster for ScalarDL Auditor + * ScalarDL Auditor pod (2vCPU / 4GB) + * Envoy proxy + * Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) + * Kubernetes components + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [Create at least three worker nodes and three pods](#create-at-least-three-worker-nodes-and-three-pods-per-eks-cluster). And remember, for Byzantine fault detection to work properly, you cannot deploy your application pods on the same EKS clusters as the ScalarDL Ledger and ScalarDL Auditor deployments. + +However, three nodes with at least 4vCPU / 8GB memory resources per node is a minimum environment for production. You should also consider the resources of the EKS cluster (for example, the number of worker nodes, vCPUs per node, memory per node, ScalarDL Ledger pods, and ScalarDL Auditor pods), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Configure Cluster Autoscaler in EKS + +If you want to scale ScalarDL Ledger or ScalarDL Auditor pods automatically by using [Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html), you should configure Cluster Autoscaler in EKS too. For details, see the official Amazon documentation at [Autoscaling](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html#cluster-autoscaler). + +In addition, if you configure Cluster Autoscaler, you should create a subnet in a VPC for EKS with the prefix (e.g., `/24`) to ensure a sufficient number of IPs exist so that EKS can work without network issues after scaling. + +### Create the EKS cluster on a private network + +You should create the EKS cluster on a private network (private subnet in a VPC) since ScalarDL Ledger and ScalarDL Auditor do not provide any services to users directly via internet access. We recommend accessing ScalarDL Ledger and ScalarDL Auditor via a private network from your applications. + +### Restrict connections by using some security features based on your requirements + +You should restrict unused connections in ScalarDL Ledger and ScalarDL Auditor. To restrict unused connections, you can use some security features in AWS, like [security groups](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) and [network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html). + +The connections (ports) that ScalarDL Ledger and ScalarDL Auditor use by default are as follows: + +* ScalarDL Ledger + * 50051/TCP (accepts requests from a client and ScalarDL Auditor) + * 50052/TCP (accepts privileged requests from a client and ScalarDL Auditor) + * 50053/TCP (accepts pause and unpause requests from a scalar-admin client tool) + * 8080/TCP (accepts monitoring requests) +* ScalarDL Auditor + * 40051/TCP (accepts requests from a client) + * 40052/TCP (accepts privileged requests from a client) + * 40053/TCP (accepts pause and unpause requests from a scalar-admin client tool) + * 8080/TCP (accepts monitoring requests) +* Scalar Envoy (used with ScalarDL Ledger and ScalarDL Auditor) + * 50051/TCP (load balancing for ScalarDL Ledger) + * 50052/TCP (load balancing for ScalarDL Ledger) + * 40051/TCP (load balancing for ScalarDL Auditor) + * 40052/TCP (load balancing for ScalarDL Auditor) + * 9001/TCP (accepts monitoring requests for Scalar Envoy itself) + +:::note + +- If you change the default listening port for ScalarDL Ledger and ScalarDL Auditor in their configuration files (`ledger.properties` and `auditor.properties`, respectively), you must allow the connections by using the port that you configured. +- You must also allow the connections that EKS uses itself. For more details about Amazon EKS security group requirements, refer to [Amazon EKS security group requirements and considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html). + +::: diff --git a/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarProducts.mdx b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarProducts.mdx new file mode 100644 index 00000000..278ee172 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/CreateEKSClusterForScalarProducts.mdx @@ -0,0 +1,21 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Guidelines for creating an Amazon EKS cluster for Scalar products + +To create an Amazon Elastic Kubernetes Service (EKS) cluster for Scalar products, refer to the following: + +* [Guidelines for creating an EKS cluster for ScalarDB Cluster](CreateEKSClusterForScalarDBCluster.mdx) +* [(Deprecated) Guidelines for creating an EKS cluster for ScalarDB Server](CreateEKSClusterForScalarDB.mdx) +* [Guidelines for creating an EKS cluster for ScalarDL Ledger](CreateEKSClusterForScalarDL.mdx) +* [Guidelines for creating an EKS cluster for ScalarDL Ledger and ScalarDL Auditor](CreateEKSClusterForScalarDLAuditor.mdx) + +To deploy Scalar products on Amazon EKS, refer to the following: + +* [Deploy ScalarDB Server on Amazon EKS (Amazon Elastic Kubernetes Service)](ManualDeploymentGuideScalarDBServerOnEKS.mdx) +* [Deploy ScalarDL Ledger on Amazon EKS (Amazon Elastic Kubernetes Service)](ManualDeploymentGuideScalarDLOnEKS.mdx) +* [Deploy ScalarDL Ledger and ScalarDL Auditor on Amazon EKS (Amazon Elastic Kubernetes Service)](ManualDeploymentGuideScalarDLAuditorOnEKS.mdx) diff --git a/versioned_docs/version-3.15/scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx b/versioned_docs/version-3.15/scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx new file mode 100644 index 00000000..76ad97a1 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/HowToCreateKeyAndCertificateFiles.mdx @@ -0,0 +1,147 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to Create Private Key and Certificate Files for TLS Connections in Scalar Products + +This guide explains how to create private key and certificate files for TLS connections in ScalarDB Cluster and ScalarDL. When you enable the TLS feature, you must prepare private key and certificate files. + +## Certificate requirements + +* You can use only `RSA` or `ECDSA` as an algorithm for private key and certificate files. + +## Example steps to create sample private key and certificate files + +In this example, you'll create sample private key and certificate files by using `cfssl` and `cfssljson`. If you don't have those tools installed, please install `cfssl` and `cfssljson` to run this example. + +:::note + +* You can use other tools, like `openssl`, to create the private key and certificate files. Alternatively, you can ask a third-party CA or the administrator of your private CA to create the private key and certificate for your production environment. +* This example creates a self-signed certificate. However, it is strongly recommended that these certificates **not** be used in production. Please ask trusted issuers (a public CA or your private CA) to create certificate files for your production environment based on your security requirements. + +::: + +1. Create a working directory. + + ```console + mkdir -p ${HOME}/scalar/example/certs/ + ``` + +1. Change the working directory to `${HOME}/scalar/example/certs/`. + + ```console + cd ${HOME}/scalar/example/certs/ + ``` + +1. Create a JSON file that includes CA information. + + ```console + cat << 'EOF' > ${HOME}/scalar/example/certs/ca.json + { + "CN": "scalar-example-ca", + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Example CA" + } + ] + } + EOF + ``` + +1. Create the CA private key and certificate files. + + ```console + cfssl gencert -initca ca.json | cfssljson -bare ca + ``` + +1. Create a JSON file that includes CA configurations. + + ```console + cat << 'EOF' > ${HOME}/scalar/example/certs/ca-config.json + { + "signing": { + "default": { + "expiry": "87600h" + }, + "profiles": { + "scalar-example-ca": { + "expiry": "87600h", + "usages": [ + "signing", + "key encipherment", + "server auth" + ] + } + } + } + } + EOF + ``` + +1. Create a JSON file that includes server information. + + ```console + cat << 'EOF' > ${HOME}/scalar/example/certs/server.json + { + "CN": "scalar-example-server", + "hosts": [ + "server.scalar.example.com", + "localhost" + ], + "key": { + "algo": "ecdsa", + "size": 256 + }, + "names": [ + { + "C": "JP", + "ST": "Tokyo", + "L": "Shinjuku", + "O": "Scalar Example Server" + } + ] + } + EOF + ``` + +1. Create the private key and certificate files for the server. + + ```console + cfssl gencert -ca ca.pem -ca-key ca-key.pem -config ca-config.json -profile scalar-example-ca server.json | cfssljson -bare server + ``` + +1. Confirm that the private key and certificate files were created. + + ```console + ls -1 + ``` + + [Command execution result] + + ```console + ca-config.json + ca-key.pem + ca.csr + ca.json + ca.pem + server-key.pem + server.csr + server.json + server.pem + ``` + + In this case: + + * `server-key.pem` is the private key file. + * `server.pem` is the certificate file. + * `ca.pem` is the root CA certificate file. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/HowToGetContainerImages.mdx b/versioned_docs/version-3.15/scalar-kubernetes/HowToGetContainerImages.mdx new file mode 100644 index 00000000..10b77dbc --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/HowToGetContainerImages.mdx @@ -0,0 +1,25 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to get the container images of Scalar products + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +You can get the container images of Scalar products in several ways. Please choose one of the following methods. + + + + You can get the container images from the public container repository if you have a commercial license. For more details on how to use container images, see [How to use the container images](./HowToUseContainerImages.mdx). + + + For details on how to get Scalar products from AWS Marketplace, see [How to install Scalar products through AWS Marketplace](./AwsMarketplaceGuide.mdx). + + + Scalar products are currently not available in Azure Marketplace. Please get the container images from one of the other methods. + + diff --git a/versioned_docs/version-3.15/scalar-kubernetes/HowToScaleScalarDB.mdx b/versioned_docs/version-3.15/scalar-kubernetes/HowToScaleScalarDB.mdx new file mode 100644 index 00000000..76d6e2a5 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/HowToScaleScalarDB.mdx @@ -0,0 +1,46 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to Scale ScalarDB + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to scale ScalarDB. The contents of this guide assume that you used [Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) to deploy ScalarDB Cluster, which is the recommended way. + +:::note + +You might be able to resolve some performance issues by scaling ScalarDB Cluster if a bottleneck exists on the ScalarDB Cluster side. However, sometimes a performance issue is caused by a bottleneck in the backend databases. In such cases, scaling ScalarDB Cluster will not resolve the performance issue. + +Instead, please check where the bottleneck exists. If the bottleneck exists in the backend databases, consider scaling the backend databases. + +::: + + + + + 1. Add the following to your custom values file, replacing `` with the number of pods you want to scale: + + ```yaml + scalardbCluster: + replicaCount: + ``` + + 1. Upgrade your ScalarDB Cluster deployment by running the following `helm upgrade` command, which uses the updated custom values file. Be sure to replace the contents in the angle brackets as described: + + ```console + helm upgrade scalar-labs/scalardb-cluster -n -f / --version + ``` + + + + + ScalarDB Core is provided as a Java library. So, when you scale your application, ScalarDB scales with your application. + + + diff --git a/versioned_docs/version-3.15/scalar-kubernetes/HowToScaleScalarDL.mdx b/versioned_docs/version-3.15/scalar-kubernetes/HowToScaleScalarDL.mdx new file mode 100644 index 00000000..9ed8ad7d --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/HowToScaleScalarDL.mdx @@ -0,0 +1,55 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# How to Scale ScalarDL + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to scale ScalarDL. The contents of this guide assume that you used [Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) to deploy ScalarDL, which is the recommended way. + +:::note + +You might be able to resolve some performance issues by scaling ScalarDL if a bottleneck exists on the ScalarDL side. However, sometimes a performance issue is caused by a bottleneck in the backend databases. In such cases, scaling ScalarDL will not resolve the performance issue. + +Instead, please check where the bottleneck exists. If the bottleneck exists in the backend databases, consider scaling the backend databases. + +::: + + + + + 1. Add the following to your custom values file, replacing `` with the number of pods you want to scale: + + ```yaml + ledger: + replicaCount: + ``` + + 1. Upgrade your ScalarDL Ledger deployment by running the following `helm upgrade` command, which uses the updated custom values file. Be sure to replace the contents in the angle brackets as described: + + ```console + helm upgrade scalar-labs/scalardl -n -f / --version + ``` + + + + + 1. Add the following to your custom values file, replacing `` with the number of pods you want to scale: + + ```yaml + auditor: + replicaCount: + ``` + + 1. Upgrade your ScalarDL Auditor deployment by running the following `helm upgrade` command, which uses the updated custom values file. Be sure to replace the contents in the angle brackets as described: + + ```console + helm upgrade scalar-labs/scalardl-audit -n -f / --version + ``` + + + diff --git a/versioned_docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDB.mdx b/versioned_docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDB.mdx new file mode 100644 index 00000000..98ce9714 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDB.mdx @@ -0,0 +1,86 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to Upgrade ScalarDB + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to upgrade to a newer version of ScalarDB. + +## Before you begin + +Before you upgrade to a new version, please check the [ScalarDB Cluster Compatibility Matrix](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/compatibility/) to ensure compatibility between ScalarDB Cluster and the client SDKs. + +## Upgrade versions + +To learn about upgrading your version of ScalarDB, select the type of upgrade you want to do. + + + + Major versions do **not** keep backward compatibility. So, you might need to do special operations when you upgrade from one major version to another major version. For example: + + - Update the database schema on the backend database side. + - Update the API in your application. + + For details on what you need when you upgrade to a major version, please refer to the release notes for the major version that you want to upgrade to. + + + Minor versions keep backward compatibility. So, you can upgrade ScalarDB from one minor version to another minor version in the same major version without doing any special operations. For example, you don't need to update the database schema on the backend database side or update the API in your application. + + + + If you use [Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) to deploy ScalarDB Cluster, you can upgrade your ScalarDB Cluster deployment as follows: + + 1. Set the ScalarDB Cluster Helm Chart version as an environment variable. You can do this by running the following command to put the chart version into the environment variable `SCALAR_DB_CLUSTER_CHART_VERSION`: + + ```console + SCALAR_DB_CLUSTER_CHART_VERSION=1.5.0 + ``` + + :::tip + + You can search for the chart version that corresponds to the ScalarDB Cluster version, run the following command: + + ```console + helm search repo scalar-labs/scalardb-cluster -l + ``` + + The following command might be helpful, but please make sure to replace the contents in the angle brackets with your version of ScalarDB Cluster: + + ```console + SCALAR_DB_CLUSTER_VERSION=..; SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + + ::: + + 1. Upgrade your ScalarDB Cluster deployment by replacing the contents in the angle brackets as described: + + ```console + helm upgrade scalar-labs/scalardb-cluster -n -f / --version ${SCALAR_DB_CLUSTER_CHART_VERSION} + ``` + + After you upgrade the ScalarDB Cluster deployment, you should consider upgrading the version of the [ScalarDB Cluster Java Client SDK](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-cluster-java-client-sdk) or the [ScalarDB Cluster .NET Client SDK](https://www.nuget.org/packages/ScalarDB.Net.Client) on your application side. + + + ScalarDB Core is provided as a Java library. So, you can update the dependencies of your Java project and rebuild your application to upgrade ScalarDB versions. + + + + + Patch versions keep backward compatibility. So, you can upgrade ScalarDB from one patch version to another patch version in the same major version and minor version without doing any special operations. For example, you don't need to update the database schema on the backend database side or update the API in your application. + + The method for upgrading to a patch version is the same as for upgrading to a minor version. For details on how to upgrade, see the [Upgrade to a minor version](?versions=upgrade-minor-version) tab. + + + +:::warning + +ScalarDB does **not** support downgrading to a previous version (major, minor, or patch). You can only upgrade to a newer version. + +::: diff --git a/versioned_docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDL.mdx b/versioned_docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDL.mdx new file mode 100644 index 00000000..ed352945 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/HowToUpgradeScalarDL.mdx @@ -0,0 +1,114 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# How to Upgrade ScalarDL + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to upgrade to a newer version of ScalarDL. + +## Before you begin + +Before you upgrade to a new version, please check the [ScalarDL Compatibility Matrix](https://scalardl.scalar-labs.com/docs/latest/compatibility/) to ensure compatibility between ScalarDL and the client SDKs. + +## Upgrade versions + +To learn about upgrading your version of ScalarDL, select the type of upgrade you want to do. + + + + Major versions do **not** keep backward compatibility. So, you might need to do special operations when you upgrade from one major version to another major version. For example: + + - Update the database schema on the backend database side. + - Update the API in your application. + + For details on what you need when you upgrade to a major version, please refer to the release notes for the major version that you want to upgrade to. + + + Minor versions keep backward compatibility. So, you can upgrade ScalarDL from one minor version to another minor version in the same major version without doing any special operations. For example, you don't need to update the database schema on the backend database side or update the API in your application. + + + + If you use [Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) to deploy ScalarDL Ledger, you can upgrade your ScalarDL Ledger deployment as follows: + + 1. Set the ScalarDL Ledger Helm Chart version as an environment variable. You can do this by running the following command to put the chart version into the environment variable `SCALAR_DL_LEDGER_CHART_VERSION`: + + ```console + SCALAR_DL_LEDGER_CHART_VERSION=4.8.0 + ``` + + :::tip + + You can search for the chart version that corresponds to the ScalarDL Ledger version as follows: + + ```console + helm search repo scalar-labs/scalardl -l + ``` + + The following command might be helpful, but please make sure to replace the contents in the angle brackets with your version of ScalarDL Ledger: + + ```console + SCALAR_DL_VERSION=..; SCALAR_DL_LEDGER_CHART_VERSION=$(helm search repo scalar-labs/scalardl -l | grep -v -e "scalar-labs/scalardl-audit" | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + + ::: + + 1. Upgrade your ScalarDL Ledger deployment by replacing the contents in the angle brackets as described: + + ```console + helm upgrade scalar-labs/scalardl -n -f / --version ${SCALAR_DL_LEDGER_CHART_VERSION} + ``` + + After you upgrade the ScalarDL Ledger deployment (and the ScalarDL Auditor deployment if you use Auditor mode), you should consider upgrading the version of the [ScalarDL Java Client SDK](https://mvnrepository.com/artifact/com.scalar-labs/scalardl-java-client-sdk) on your application side. + + + If you use [Scalar Helm Chart](https://github.com/scalar-labs/helm-charts) to deploy ScalarDL Auditor, you can upgrade your ScalarDL Auditor deployment as follows: + + 1. Set the ScalarDL Auditor Helm Chart version as an environment variable. You can do this by running the following command to put the chart version into the environment variable `SCALAR_DL_AUDITOR_CHART_VERSION`: + + ```console + SCALAR_DL_AUDITOR_CHART_VERSION=2.8.0 + ``` + + :::tip + + You can search for the chart version that corresponds to the ScalarDL Auditor version as follows: + + ```console + helm search repo scalar-labs/scalardl-audit -l + ``` + + The following command might be helpful, but please make sure to replace the contents in the angle brackets with your version of ScalarDL Auditor: + + ```console + SCALAR_DL_VERSION=..; SCALAR_DL_AUDITOR_CHART_VERSION=$(helm search repo scalar-labs/scalardl-audit -l | grep -F "${SCALAR_DL_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + + ::: + + 1. Upgrade your ScalarDL Auditor deployment by replacing the contents in the angle brackets as described: + + ```console + helm upgrade scalar-labs/scalardl-audit -n -f / --version ${SCALAR_DL_AUDITOR_CHART_VERSION} + ``` + + After you upgrade the ScalarDL Auditor deployment and the ScalarDL Ledger deployment, you should consider upgrading the version of the [ScalarDL Java Client SDK](https://mvnrepository.com/artifact/com.scalar-labs/scalardl-java-client-sdk) on your application side. + + + + + Patch versions keep backward compatibility. So, you can upgrade ScalarDL from one patch version to another patch version in the same major version and minor version without doing any special operations. For example, you don't need to update the database schema on the backend database side or update the API in your application. + + The method for upgrading to a patch version is the same as for upgrading to a minor version. For details on how to upgrade, see the [Upgrade to a minor version](?versions=upgrade-minor-version) tab. + + + +:::warning + +ScalarDL does **not** support downgrading to a previous version (major, minor, or patch). You can only upgrade to a newer version. + +::: diff --git a/versioned_docs/version-3.15/scalar-kubernetes/HowToUseContainerImages.mdx b/versioned_docs/version-3.15/scalar-kubernetes/HowToUseContainerImages.mdx new file mode 100644 index 00000000..95b93618 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/HowToUseContainerImages.mdx @@ -0,0 +1,137 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to use the container images + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +You can pull the container images from the public container repository. You must configure the license key and the certificate in your `.properties` file if you use the container images. + +## Prerequisites + +The public container images are available for the following products and versions: + +* ScalarDB Cluster v3.12 or later +* ScalarDL v3.9 or later + +## Pull the container images from the public container repository + +You can pull the container image of each product from the public container repository. To pull a container image, select your Scalar product to see the link to the container image. + + + + + Select your edition of ScalarDB Enterprise. + + + https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-node-byol-standard + + + https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-node-byol-premium + + + + + https://github.com/orgs/scalar-labs/packages/container/package/scalardl-ledger-byol + + + https://github.com/orgs/scalar-labs/packages/container/package/scalardl-auditor-byol + + + +If you're using Scalar Helm Charts, you must set `*.image.repository` in the custom values file for the product that you're using. Select your Scalar product to see how to set `*.image.repository`. + + + + Select your edition of ScalarDB Enterprise. + + + ```yaml + scalardbCluster: + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-standard" + ``` + + + ```yaml + scalardbCluster: + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium" + ``` + + + + + ```yaml + ledger: + image: + repository: "ghcr.io/scalar-labs/scalardl-ledger-byol" + ``` + + + ```yaml + auditor: + image: + repository: "ghcr.io/scalar-labs/scalardl-auditor-byol" + ``` + + + +## Set the license key in the `.properties` file + +To run the container images, you must set `license key` and `certificate` in your `.properties` file. Select your Scalar product to see how to set `license key` and `certificate`. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). + + + + ```properties + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem= + ``` + + + ```properties + scalar.dl.licensing.license_key= + scalar.dl.licensing.license_check_cert_pem= + ``` + + + ```properties + scalar.dl.licensing.license_key= + scalar.dl.licensing.license_check_cert_pem= + ``` + + + +If you're using Scalar Helm Charts, you must set the properties in the custom values file for the product that you're using. Select your Scalar product to see how to set the properties in the custom values file. + + + + ```yaml + scalardbCluster: + scalardbClusterNodeProperties: | + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem= + ``` + + + ```yaml + ledger: + ledgerProperties: | + scalar.dl.licensing.license_key= + scalar.dl.licensing.license_check_cert_pem= + ``` + + + ```yaml + auditor: + auditorProperties: | + scalar.dl.licensing.license_key= + scalar.dl.licensing.license_check_cert_pem= + ``` + + diff --git a/versioned_docs/version-3.15/scalar-kubernetes/K8sLogCollectionGuide.mdx b/versioned_docs/version-3.15/scalar-kubernetes/K8sLogCollectionGuide.mdx new file mode 100644 index 00000000..f6013a54 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/K8sLogCollectionGuide.mdx @@ -0,0 +1,183 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Collecting logs from Scalar products on a Kubernetes cluster + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This document explains how to deploy Grafana Loki and Promtail on Kubernetes with Helm. After following this document, you can collect logs of Scalar products on your Kubernetes environment. + +If you use a managed Kubernetes cluster and you want to use the cloud service features for monitoring and logging, please refer to the following document. + +* [Logging and monitoring on Amazon EKS](https://docs.aws.amazon.com/prescriptive-guidance/latest/implementing-logging-monitoring-cloudwatch/amazon-eks-logging-monitoring.html) +* [Monitoring Azure Kubernetes Service (AKS) with Azure Monitor](https://learn.microsoft.com/en-us/azure/aks/monitor-aks) + +## Prerequisites + +* Create a Kubernetes cluster. + * [Create an EKS cluster for Scalar products](CreateEKSClusterForScalarProducts.mdx) + * [Create an AKS cluster for Scalar products](CreateAKSClusterForScalarProducts.mdx) +* Create a Bastion server and set `kubeconfig`. + * [Create a bastion server](CreateBastionServer.mdx) +* Deploy Prometheus Operator (we use Grafana to explore collected logs) + * [Monitoring Scalar products on the Kubernetes cluster](K8sMonitorGuide.mdx) + +## Add the grafana helm repository + +This document uses Helm for the deployment of Prometheus Operator. + +```console +helm repo add grafana https://grafana.github.io/helm-charts +``` +```console +helm repo update +``` + +## Prepare a custom values file + +Please get the sample file [scalar-loki-stack-custom-values.yaml](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalar-loki-stack-custom-values.yaml) for loki-stack. For the logging of Scalar products, this sample file's configuration is recommended. + +### Set nodeSelector in the custom values file (Optional) + +You might need to set nodeSelector in the custom values file (scalar-loki-stack-custom-values.yaml) as follows if you add labels to your Kubernetes worker node. See the following examples based on the product you're using. + + + + Select the ScalarDB product you're using. + + + ```yaml + promtail: + nodeSelector: + scalar-labs.com/dedicated-node: scalardb-cluster + ``` + + + ```yaml + promtail: + nodeSelector: + scalar-labs.com/dedicated-node: scalardb + ``` + + + + + Select the ScalarDL product you're using. + + + ```yaml + promtail: + nodeSelector: + scalar-labs.com/dedicated-node: scalardl-ledger + ``` + + + ```yaml + promtail: + nodeSelector: + scalar-labs.com/dedicated-node: scalardl-auditor + ``` + + + + + +### Set tolerations in the custom values file (Optional) + +You might need to set tolerations in the custom values file (scalar-loki-stack-custom-values.yaml) as follows if you add taints to your Kubernetes worker node. See the following examples based on the product you're using. + + + + Select the ScalarDB product you're using. + + + ```yaml + promtail: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb-cluster + ``` + + + ```yaml + promtail: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardb + ``` + + + + + Select the ScalarDL product you're using. + + + ```yaml + promtail: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardl-ledger + ``` + + + ```yaml + promtail: + tolerations: + - effect: NoSchedule + key: scalar-labs.com/dedicated-node + operator: Equal + value: scalardl-auditor + ``` + + + + + +## Deploy Loki and Promtail + +It is recommended to deploy Loki and Promtail on the same namespace `monitoring` as Prometheus and Grafana. You have already created the `monitoring` namespace in the document [Monitoring Scalar products on the Kubernetes cluster](K8sMonitorGuide.mdx). + +```console +helm install scalar-logging-loki grafana/loki-stack -n monitoring -f scalar-loki-stack-custom-values.yaml +``` + +## Check if Loki and Promtail are deployed + +If the Loki and Promtail pods are deployed properly, you can see the `STATUS` is `Running` using the `kubectl get pod -n monitoring` command. Since promtail pods are deployed as DaemonSet, the number of promtail pods depends on the number of Kubernetes nodes. In the following example, there are three worker nodes for Scalar products in the Kubernetes cluster. + +```console +kubectl get pod -n monitoring +``` + +You should see the following output: + +```console +NAME READY STATUS RESTARTS AGE +scalar-logging-loki-0 1/1 Running 0 35m +scalar-logging-loki-promtail-2fnzn 1/1 Running 0 32m +scalar-logging-loki-promtail-2pwkx 1/1 Running 0 30m +scalar-logging-loki-promtail-gfx44 1/1 Running 0 32m +``` + +## View log in Grafana dashboard + +You can see the collected logs in the Grafana dashboard as follows. + +1. Access the Grafana dashboard +1. Go to the `Explore` page +1. Select `Loki` from the top left pull-down +1. Set conditions to query logs +1. Select the `Run query` button at the top right + +Please refer to the [Monitoring Scalar products on the Kubernetes cluster](K8sMonitorGuide.mdx) for more details on how to access the Grafana dashboard. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/K8sMonitorGuide.mdx b/versioned_docs/version-3.15/scalar-kubernetes/K8sMonitorGuide.mdx new file mode 100644 index 00000000..66cb123b --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/K8sMonitorGuide.mdx @@ -0,0 +1,156 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Monitoring Scalar products on a Kubernetes cluster + +This document explains how to deploy Prometheus Operator on Kubernetes with Helm. After following this document, you can use Prometheus, Alertmanager, and Grafana for monitoring Scalar products on your Kubernetes environment. + +If you use a managed Kubernetes cluster and you want to use the cloud service features for monitoring and logging, please refer to the following document. + +* [Logging and monitoring on Amazon EKS](https://docs.aws.amazon.com/prescriptive-guidance/latest/implementing-logging-monitoring-cloudwatch/amazon-eks-logging-monitoring.html) +* [Monitoring Azure Kubernetes Service (AKS) with Azure Monitor](https://learn.microsoft.com/en-us/azure/aks/monitor-aks) + +## Prerequisites + +* Create a Kubernetes cluster. + * [Create an EKS cluster for Scalar products](CreateEKSClusterForScalarProducts.mdx) + * [Create an AKS cluster for Scalar products](CreateAKSClusterForScalarProducts.mdx) +* Create a Bastion server and set `kubeconfig`. + * [Create a bastion server](CreateBastionServer.mdx) + +## Add the prometheus-community helm repository + +This document uses Helm for the deployment of Prometheus Operator. + +```console +helm repo add prometheus-community https://prometheus-community.github.io/helm-charts +``` +```console +helm repo update +``` + +## Prepare a custom values file + +Please get the sample file [scalar-prometheus-custom-values.yaml](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalar-prometheus-custom-values.yaml) for kube-prometheus-stack. For the monitoring of Scalar products, this sample file's configuration is recommended. + +In this sample file, the Service resources are not exposed to access from outside of a Kubernetes cluster. If you want to access dashboards from outside of your Kubernetes cluster, you must set `*.service.type` to `LoadBalancer` or `*.ingress.enabled` to `true`. + +Please refer to the following official document for more details on the configurations of kube-prometheus-stack. + +* [kube-prometheus-stack - Configuration](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack#configuration) + +## Deploy Prometheus Operator + +Scalar products assume the Prometheus Operator is deployed in the `monitoring` namespace by default. So, please create the namespace `monitoring` and deploy Prometheus Operator in the `monitoring` namespace. + +1. Create a namespace `monitoring` on Kubernetes. + ```console + kubectl create namespace monitoring + ``` + +1. Deploy the kube-prometheus-stack. + ```console + helm install scalar-monitoring prometheus-community/kube-prometheus-stack -n monitoring -f scalar-prometheus-custom-values.yaml + ``` + +## Check if the Prometheus Operator is deployed + +If the Prometheus Operator (includes Prometheus, Alertmanager, and Grafana) pods are deployed properly, you can see the `STATUS` is `Running` using the following command: + +```console +kubectl get pod -n monitoring +``` + +You should see the following output: + +```console +NAME READY STATUS RESTARTS AGE +alertmanager-scalar-monitoring-kube-pro-alertmanager-0 2/2 Running 0 55s +prometheus-scalar-monitoring-kube-pro-prometheus-0 2/2 Running 0 55s +scalar-monitoring-grafana-cb4f9f86b-jmkpz 3/3 Running 0 62s +scalar-monitoring-kube-pro-operator-865bbb8454-9ppkc 1/1 Running 0 62s +``` + +## Deploy (or Upgrade) Scalar products using Helm Charts + +1. To enable Prometheus monitoring for Scalar products, you must set `true` to the following configurations in the custom values file. + + * Configurations + * `*.prometheusRule.enabled` + * `*.grafanaDashboard.enabled` + * `*.serviceMonitor.enabled` + + Please refer to the following documents for more details on the custom values file of each Scalar product. + + * [ScalarDB Cluster](../helm-charts/configure-custom-values-scalardb-cluster.mdx#prometheus-and-grafana-configurations-recommended-in-production-environments) + * [(Deprecated) ScalarDB Server](../helm-charts/configure-custom-values-scalardb.mdx#prometheusgrafana-configurations-recommended-in-the-production-environment) + * [(Deprecated) ScalarDB GraphQL](../helm-charts/configure-custom-values-scalardb-graphql.mdx#prometheusgrafana-configurations-recommended-in-the-production-environment) + * [ScalarDL Ledger](../helm-charts/configure-custom-values-scalardl-ledger.mdx#prometheusgrafana-configurations-recommended-in-the-production-environment) + * [ScalarDL Auditor](../helm-charts/configure-custom-values-scalardl-auditor.mdx#prometheusgrafana-configurations-recommended-in-the-production-environment) + +1. Deploy (or Upgrade) Scalar products using Helm Charts with the above custom values file. + + Please refer to the following documents for more details on how to deploy/upgrade Scalar products. + + * [ScalarDB Cluster](../helm-charts/how-to-deploy-scalardb-cluster.mdx) + * [(Deprecated) ScalarDB Server](../helm-charts/how-to-deploy-scalardb.mdx) + * [(Deprecated) ScalarDB GraphQL](../helm-charts/how-to-deploy-scalardb-graphql.mdx) + * [ScalarDL Ledger](../helm-charts/how-to-deploy-scalardl-ledger.mdx) + * [ScalarDL Auditor](../helm-charts/how-to-deploy-scalardl-auditor.mdx) + +## How to access dashboards + +When you set `*.service.type` to `LoadBalancer` or `*.ingress.enabled` to `true`, you can access dashboards via Service or Ingress of Kubernetes. The concrete implementation and access method depend on the Kubernetes cluster. If you use a managed Kubernetes cluster, please refer to the cloud provider's official document for more details. + +* EKS + * [Network load balancing on Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/network-load-balancing.html) + * [Application load balancing on Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/alb-ingress.html) +* AKS + * [Use a public standard load balancer in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/load-balancer-standard) + * [Create an ingress controller in Azure Kubernetes Service (AKS)](https://learn.microsoft.com/en-us/azure/aks/ingress-basic) + +## Access the dashboard from your local machine (For testing purposes only / Not recommended in the production environment) + +You can access each dashboard from your local machine using the `kubectl port-forward` command. + +1. Port forwarding to each service from your local machine. + * Prometheus + ```console + kubectl port-forward -n monitoring svc/scalar-monitoring-kube-pro-prometheus 9090:9090 + ``` + * Alertmanager + ```console + kubectl port-forward -n monitoring svc/scalar-monitoring-kube-pro-alertmanager 9093:9093 + ``` + * Grafana + ```console + kubectl port-forward -n monitoring svc/scalar-monitoring-grafana 3000:3000 + ``` + +1. Access each Dashboard. + * Prometheus + ```console + http://localhost:9090/ + ``` + * Alertmanager + ```console + http://localhost:9093/ + ``` + * Grafana + ```console + http://localhost:3000/ + ``` + * Note: + * You can see the user and password of Grafana as follows. + * user + ```console + kubectl get secrets scalar-monitoring-grafana -n monitoring -o jsonpath='{.data.admin-user}' | base64 -d + ``` + * password + ```console + kubectl get secrets scalar-monitoring-grafana -n monitoring -o jsonpath='{.data.admin-password}' | base64 -d + ``` diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS.mdx new file mode 100644 index 00000000..bee02994 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS.mdx @@ -0,0 +1,66 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Deploy ScalarDB Cluster on Amazon Elastic Kubernetes Service (EKS) + +This guide explains how to deploy ScalarDB Cluster on Amazon Elastic Kubernetes Service (EKS). + +In this guide, you will create one of the following two environments in your AWS environment. The environments differ depending on which [client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#client-modes) you use: + +* **[`direct-kubernetes` client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#direct-kubernetes-client-mode).** In this mode, you deploy your application in the same EKS cluster as your ScalarDB Cluster deployment. + + ![image](images/png/EKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png) + +* **[`indirect` client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#indirect-client-mode).** In this mode, you deploy your application in an environment that is different from the EKS cluster that contains your ScalarDB Cluster deployment. + + ![image](images/png/EKS_ScalarDB_Cluster_Indirect_Mode.drawio.png) + +## Step 1. Subscribe to ScalarDB Cluster in AWS Marketplace + +You must get the ScalarDB Cluster container image by visiting AWS Marketplace and subscribing to [ScalarDB Cluster Standard Edition (Pay-As-You-Go)](https://aws.amazon.com/marketplace/pp/prodview-jx6qxatkxuwm4) or [ScalarDB Cluster Premium Edition (Pay-As-You-Go)](https://aws.amazon.com/marketplace/pp/prodview-djqw3zk6dwyk6). For details on how to subscribe to ScalarDB Cluster in AWS Marketplace, see [Subscribe to Scalar products from AWS Marketplace](AwsMarketplaceGuide.mdx#subscribe-to-scalar-products-from-aws-marketplace). + +## Step 2. Create an EKS cluster + +You must create an EKS cluster for the ScalarDB Cluster deployment. For details, see [Guidelines for creating an Amazon EKS cluster for Scalar products](CreateEKSClusterForScalarProducts.mdx). + +## Step 3. Set up a database for ScalarDB Cluster + +You must prepare a database before deploying ScalarDB Cluster. To see which types of databases ScalarDB supports, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases). + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment on AWS](SetupDatabaseForAWS.mdx). + +## Step 4. Create a bastion server + +To execute some tools for deploying and managing ScalarDB Cluster on EKS, you must prepare a bastion server in the same Amazon Virtual Private Cloud (VPC) of the EKS cluster that you created in **Step 2**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 5. Prepare a custom values file for the Scalar Helm Chart + +To perform tasks, like accessing information in the database that you created in **Step 3**, you must configure a custom values file for the Scalar Helm Chart for ScalarDB Cluster based on your environment. For details, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + +**Note:** If you deploy your application in an environment that is different from the EKS cluster that has your ScalarDB Cluster deployment (i.e., you use `indirect` client mode), you must set the `envoy.enabled` parameter to `true` and the `envoy.service.type` parameter to `LoadBalancer` to access Scalar Envoy from your application. + +## Step 6. Deploy ScalarDB Cluster by using the Scalar Helm Chart + +Deploy ScalarDB Cluster on your EKS cluster by using the Helm Chart for ScalarDB Cluster. For details, see [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardb-cluster` command and deploying ScalarDB Cluster in the namespace by using the `-n scalardb-cluster` option with the `helm install` command. + +## Step 7. Check the status of your ScalarDB Cluster deployment + +After deploying ScalarDB Cluster in your EKS cluster, you must check the status of each component. For details, see [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx). + +## Step 8. Monitor your ScalarDB Cluster deployment + +After deploying ScalarDB Cluster in your EKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Step 9. Deploy your application + +If you use [`direct-kubernetes` client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#direct-kubernetes-client-mode), you must deploy additional Kubernetes resources. For details, see [Deploy your client application on Kubernetes with `direct-kubernetes` mode](../helm-charts/how-to-deploy-scalardb-cluster.mdx#deploy-your-client-application-on-kubernetes-with-direct-kubernetes-mode). + +## Remove ScalarDB Cluster from EKS + +If you want to remove the environment that you created, please remove all the resources in reverse order from which you created them in. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnAKS.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnAKS.mdx new file mode 100644 index 00000000..5a9e1d90 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnAKS.mdx @@ -0,0 +1,63 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsEnglish +--- + +# [Deprecated] Deploy ScalarDB Server on Azure Kubernetes Service (AKS) + +This guide explains how to deploy ScalarDB Server on Azure Kubernetes Service (AKS). + +In this guide, you will create one of the following two environments in your Azure environment. The difference between the two environments is how you plan to deploy the application: + +* Deploy your application in the same AKS cluster as your ScalarDB Server deployment. In this case, you don't need to use the load balancers that Azure provides to access Scalar Envoy from your application. + + ![image](images/png/AKS_ScalarDB_Server_App_In_Cluster.drawio.png) + +* Deploy your application in an environment that is different from the AKS cluster that contains your ScalarDB Server deployment. In this case, you must use the load balancers that Azure provides to access Scalar Envoy from your application. + + ![image](images/png/AKS_ScalarDB_Server_App_Out_Cluster.drawio.png) + +## Step 1. Subscribe to ScalarDB Server in Azure Marketplace + +You must get the ScalarDB Server container image by visiting [Azure Marketplace](https://azuremarketplace.microsoft.com/en/marketplace/apps/scalarinc.scalardb) and subscribing to ScalarDB Server. For details on how to subscribe to ScalarDB Server in Azure Marketplace, see [Get Scalar products from Microsoft Azure Marketplace](AzureMarketplaceGuide.mdx#get-scalar-products-from-microsoft-azure-marketplace). + +## Step 2. Create an AKS cluster + +You must create an AKS cluster for the ScalarDB Server deployment. For details, see [Guidelines for creating an AKS cluster for Scalar products](CreateAKSClusterForScalarProducts.mdx). + +## Step 3. Set up a database for ScalarDB Server + +You must prepare a database before deploying ScalarDB Server. To see which types of databases ScalarDB supports, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases). + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment in Azure](SetupDatabaseForAzure.mdx). + +## Step 4. Create a bastion server + +To execute some tools for deploying and managing ScalarDB Server on AKS, you must prepare a bastion server in the same Azure Virtual Network (VNet) of the AKS cluster that you created in **Step 2**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 5. Prepare a custom values file for the Scalar Helm Chart + +To perform tasks, like accessing information in the database that you created in **Step 3**, you must configure a custom values file for the Scalar Helm Chart for ScalarDB Server based on your environment. For details, see [Configure a custom values file of Scalar Helm Chart](../helm-charts/configure-custom-values-file.mdx). + +**Note:** If you deploy your application in an environment that is different from the AKS cluster that has your ScalarDB Server deployment, you must set the `envoy.service.type` parameter to `LoadBalancer` to access Scalar Envoy from your application. + +## Step 6. Deploy ScalarDB Server by using the Scalar Helm Chart + +Deploy ScalarDB Server on your AKS cluster by using the Helm Chart for ScalarDB Server. For details, see [Deploy Scalar Products using Scalar Helm Chart](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardb` command and deploying ScalarDB Server in the namespace by using the `-n scalardb` option with the `helm install` command. + +## Step 7. Check the status of your ScalarDB Server deployment + +After deploying ScalarDB Server in your AKS cluster, you must check the status of each component. For details, see [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx). + +## Step 8. Monitor your ScalarDB Server deployment + +After deploying ScalarDB Server in your AKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Remove ScalarDB Server from AKS + +If you want to remove the environment that you created, please remove all the resources in reverse order from which you created them in. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnEKS.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnEKS.mdx new file mode 100644 index 00000000..e2781658 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDBServerOnEKS.mdx @@ -0,0 +1,63 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium + - Deprecated +displayed_sidebar: docsEnglish +--- + +# Deploy ScalarDB Server on Amazon Elastic Kubernetes Service (EKS) + +This guide explains how to deploy ScalarDB Server on Amazon Elastic Kubernetes Service (EKS). + +In this guide, you will create one of the following two environments in your AWS environment. The difference between the two environments is how you plan to deploy the application: + +* Deploy your application in the same EKS cluster as your ScalarDB Server deployment. In this case, you don't need to use the load balancers that AWS provides to access Scalar Envoy from your application. + + ![image](images/png/EKS_ScalarDB_Server_App_In_Cluster.drawio.png) + +* Deploy your application in an environment that is different from the EKS cluster that contains your ScalarDB Server deployment. In this case, you must use the load balancers that AWS provides to access Scalar Envoy from your application. + + ![image](images/png/EKS_ScalarDB_Server_App_Out_Cluster.drawio.png) + +## Step 1. Subscribe to ScalarDB Server in AWS Marketplace + +You must get the ScalarDB Server container image by visiting [AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-rzbuhxgvqf4d2) and subscribing to ScalarDB Server. For details on how to subscribe to ScalarDB Server in AWS Marketplace, see [Subscribe to Scalar products from AWS Marketplace](AwsMarketplaceGuide.mdx#subscribe-to-scalar-products-from-aws-marketplace). + +## Step 2. Create an EKS cluster + +You must create an EKS cluster for the ScalarDB Server deployment. For details, see [Guidelines for creating an Amazon EKS cluster for Scalar products](CreateEKSClusterForScalarProducts.mdx). + +## Step 3. Set up a database for ScalarDB Server + +You must prepare a database before deploying ScalarDB Server. To see which types of databases ScalarDB supports, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases). + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment on AWS](SetupDatabaseForAWS.mdx). + +## Step 4. Create a bastion server + +To execute some tools for deploying and managing ScalarDB Server on EKS, you must prepare a bastion server in the same Amazon Virtual Private Cloud (VPC) of the EKS cluster that you created in **Step 2**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 5. Prepare a custom values file for the Scalar Helm Chart + +To perform tasks, like accessing information in the database that you created in **Step 3**, you must configure a custom values file for the Scalar Helm Chart for ScalarDB Server based on your environment. For details, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + +**Note:** If you deploy your application in an environment that is different from the EKS cluster that has your ScalarDB Server deployment, you must set the `envoy.service.type` parameter to `LoadBalancer` to access Scalar Envoy from your application. + +## Step 6. Deploy ScalarDB Server by using the Scalar Helm Chart + +Deploy ScalarDB Server on your EKS cluster by using the Helm Chart for ScalarDB Server. For details, see [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardb` command and deploying ScalarDB Server in the namespace by using the `-n scalardb` option with the `helm install` command. + +## Step 7. Check the status of your ScalarDB Server deployment + +After deploying ScalarDB Server in your EKS cluster, you must check the status of each component. For details, see [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx). + +## Step 8. Monitor your ScalarDB Server deployment + +After deploying ScalarDB Server in your EKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Remove ScalarDB Server from EKS + +If you want to remove the environment that you created, please remove all the resources in reverse order from which you created them in. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnAKS.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnAKS.mdx new file mode 100644 index 00000000..5f88bd94 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnAKS.mdx @@ -0,0 +1,101 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Deploy ScalarDL Ledger and ScalarDL Auditor on Azure Kubernetes Service (AKS) + +This guide explains how to deploy ScalarDL Ledger and ScalarDL Auditor on Azure Kubernetes Service (AKS). + +In this guide, you will create one of the following three environments in your Azure environment. To make Byzantine fault detection work properly, we recommend deploying ScalarDL Ledger and ScalarDL Auditor on different administrative domains (i.e., separate environments). + +* Use different Azure accounts (most recommended way) + + ![image](images/png/AKS_ScalarDL_Auditor_Multi_Account.drawio.png) + +* Use different Azure Virtual Networks (VNets) (second recommended way) + + ![image](images/png/AKS_ScalarDL_Auditor_Multi_VNet.drawio.png) + +* Use different namespaces (third recommended way) + + ![image](images/png/AKS_ScalarDL_Auditor_Multi_Namespace.drawio.png) + +**Note:** This guide follows the second recommended way, "Use different VNets." + +## Step 1. Get the ScalarDL Ledger and ScalarDL Auditor container images + +You must get the ScalarDL Ledger and ScalarDL Auditor container images. For details, see [How to get the container images of Scalar products](HowToGetContainerImages.mdx). + +## Step 2. Create an AKS cluster for ScalarDL Ledger + +You must create an AKS cluster for the ScalarDL Ledger deployment. For details, see [Guidelines for creating an AKS cluster for Scalar products](CreateAKSClusterForScalarProducts.mdx). + +## Step 3. Create an AKS cluster for ScalarDL Auditor + +You must also create an AKS cluster for the ScalarDL Auditor deployment. For details, see [Guidelines for creating an AKS cluster for Scalar products](CreateAKSClusterForScalarProducts.mdx). + +## Step 4. Set up a database for ScalarDL Ledger + +You must prepare a database before deploying ScalarDL Ledger. Because ScalarDL Ledger uses ScalarDB internally to access databases, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) to see which types of databases ScalarDB supports. + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment in Azure](SetupDatabaseForAzure.mdx). + +## Step 5. Set up a database for ScalarDL Auditor + +You must also prepare a database before deploying ScalarDL Auditor. Because ScalarDL Auditor uses ScalarDB internally to access databases, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) to see which types of databases ScalarDB supports. + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment in Azure](SetupDatabaseForAzure.mdx). + +## Step 6. Create a bastion server for ScalarDL Ledger + +To execute some tools for deploying and managing ScalarDL Ledger on AKS, you must prepare a bastion server in the same VNet of the AKS cluster that you created in **Step 2**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 7. Create a bastion server for ScalarDL Auditor + +To execute some tools for deploying and managing ScalarDL Auditor on AKS, you must prepare a bastion server in the same VNet of the AKS cluster that you created in **Step 3**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 8. Create network peering between two AKS clusters + +To make ScalarDL work properly, ScalarDL Ledger and ScalarDL Auditor need to connect to each other. You must connect two VNets by using [virtual network peering](https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview). For details, see [Configure Network Peering for ScalarDL Auditor Mode](NetworkPeeringForScalarDLAuditor.mdx). + +## Step 9. Prepare custom values files for the Scalar Helm Charts for both ScalarDL Ledger and ScalarDL Schema Loader + +To perform tasks, like accessing information in the database that you created in **Step 4**, you must configure custom values files for the Scalar Helm Charts for both ScalarDL Ledger and ScalarDL Schema Loader (for Ledger) based on your environment. For details, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + +## Step 10. Deploy ScalarDL Ledger by using the Scalar Helm Chart + +Deploy ScalarDL Ledger on your AKS cluster by using the Helm Chart for ScalarDL Ledger. For details, see [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardl-ledger` command and deploying ScalarDL Ledger in the namespace by using the `-n scalardl-ledger` option with the `helm install` command. + +## Step 11. Prepare custom values files for the Scalar Helm Charts for both ScalarDL Auditor and ScalarDL Schema Loader + +To perform tasks, like accessing information in the database that you created in **Step 5**, you must also configure a custom values files for the Scalar Helm Chart for both ScalarDL Auditor and ScalarDL Schema Loader (for Auditor) based on your environment. For details, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + +## Step 12. Deploy ScalarDL Auditor by using the Scalar Helm Chart + +Deploy ScalarDL Auditor on your AKS cluster by using the Helm Chart for ScalarDL Auditor. For details, see [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardl-auditor` command and deploying ScalarDL Auditor in the namespace by using the `-n scalardl-auditor` option with the `helm install` command. + +## Step 13. Check the status of your ScalarDL Ledger deployment + +After deploying ScalarDL Ledger in your AKS cluster, you must check the status of each component. For details, see [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx). + +## Step 14. Check the status of your ScalarDL Auditor deployment + +After deploying ScalarDL Auditor in your AKS cluster, you must check the status of each component. For details, see [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx). + +## Step 15. Monitor your ScalarDL Ledger deployment + +After deploying ScalarDL Ledger in your AKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Step 16. Monitor your ScalarDL Auditor deployment + +After deploying ScalarDL Auditor in your AKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Remove ScalarDL Ledger and ScalarDL Auditor from AKS + +If you want to remove the environment that you created, please remove all the resources in reverse order from which you created them in. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnEKS.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnEKS.mdx new file mode 100644 index 00000000..79888023 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLAuditorOnEKS.mdx @@ -0,0 +1,101 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Deploy ScalarDL Ledger and ScalarDL Auditor on Amazon Elastic Kubernetes Service (EKS) + +This guide explains how to deploy ScalarDL Ledger and ScalarDL Auditor on Amazon Elastic Kubernetes Service (EKS). + +In this guide, you will create one of the following three environments in your AWS environment. To make Byzantine fault detection work properly, we recommend deploying ScalarDL Ledger and ScalarDL Auditor on different administrative domains (i.e., separate environments). + +* Use different AWS accounts (most recommended way) + + ![image](images/png/EKS_ScalarDL_Auditor_Multi_Account.drawio.png) + +* Use different Amazon Virtual Private Clouds (VPCs) (second recommended way) + + ![image](images/png/EKS_ScalarDL_Auditor_Multi_VPC.drawio.png) + +* Use different namespaces (third recommended way) + + ![image](images/png/EKS_ScalarDL_Auditor_Multi_Namespace.drawio.png) + +**Note:** This guide follows the second recommended way, "Use different VPCs." + +## Step 1. Subscribe to ScalarDL Ledger and ScalarDL Auditor in AWS Marketplace + +You must get the ScalarDL Ledger and ScalarDL Auditor container images from [AWS Marketplace](https://aws.amazon.com/marketplace/seller-profile?id=bd4cd7de-49cd-433f-97ba-5cf71d76ec7b) and subscribe to ScalarDL Ledger and ScalarDL Auditor. For details on how to subscribe to ScalarDL Ledger and ScalarDL Auditor in AWS Marketplace, see [Subscribe to Scalar products from AWS Marketplace](AwsMarketplaceGuide.mdx#subscribe-to-scalar-products-from-aws-marketplace). + +## Step 2. Create an EKS cluster for ScalarDL Ledger + +You must create an EKS cluster for the ScalarDL Ledger deployment. For details, see [Guidelines for creating an Amazon EKS cluster for Scalar products](CreateEKSClusterForScalarProducts.mdx). + +## Step 3. Create an EKS cluster for ScalarDL Auditor + +You must also create an EKS cluster for the ScalarDL Auditor deployment. For details, see [Guidelines for creating an Amazon EKS cluster for Scalar products](CreateEKSClusterForScalarProducts.mdx). + +## Step 4. Set up a database for ScalarDL Ledger + +You must prepare a database before deploying ScalarDL Ledger. Because ScalarDL Ledger uses ScalarDB internally to access databases, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) to see which types of databases ScalarDB supports. + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment on AWS](SetupDatabaseForAWS.mdx). + +## Step 5. Set up a database for ScalarDL Auditor + +You must also prepare a database before deploying ScalarDL Auditor. Because ScalarDL Auditor uses ScalarDB internally to access databases, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) to see which types of databases ScalarDB supports. + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment on AWS](SetupDatabaseForAWS.mdx). + +## Step 6. Create a bastion server for ScalarDL Ledger + +To execute some tools for deploying and managing ScalarDL Ledger on EKS, you must prepare a bastion server in the same VPC of the EKS cluster that you created in **Step 2**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 7. Create a bastion server for ScalarDL Auditor + +To execute some tools for deploying and managing ScalarDL Auditor on EKS, you must prepare a bastion server in the same VPC of the EKS cluster that you created in **Step 3**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 8. Create network peering between two EKS clusters + +To make ScalarDL work properly, ScalarDL Ledger and ScalarDL Auditor need to connect to each other. You must connect two VPCs by using [VPC peering](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html). For details, see [Configure network peering for ScalarDL Auditor mode](NetworkPeeringForScalarDLAuditor.mdx). + +## Step 9. Prepare custom values files for the Scalar Helm Charts for ScalarDL Ledger and ScalarDL Schema Loader + +To perform tasks, like accessing information in the database that you created in **Step 4**, you must configure custom values files for the Scalar Helm Charts for ScalarDL Ledger and ScalarDL Schema Loader (for Ledger) based on your environment. For details, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + +## Step 10. Deploy ScalarDL Ledger by using the Scalar Helm Chart + +Deploy ScalarDL Ledger in your EKS cluster by using the Helm Chart for ScalarDL Ledger. For details, see [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardl-ledger` command and deploying ScalarDL Ledger in the namespace by using the `-n scalardl-ledger` option with the `helm install` command. + +## Step 11. Prepare custom values files for the Scalar Helm Charts for both ScalarDL Auditor and ScalarDL Schema Loader + +To perform tasks, like accessing information in the database that you created in **Step 5**, you must configure custom values files for the Scalar Helm Charts for both ScalarDL Auditor and ScalarDL Schema Loader (for Auditor) based on your environment. For details, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + +## Step 12. Deploy ScalarDL Auditor by using the Scalar Helm Chart + +Deploy ScalarDL Auditor in your EKS cluster by using the Helm Chart for ScalarDL Auditor. For details , see [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardl-auditor` command and deploying ScalarDL Auditor in the namespace by using the `-n scalardl-auditor` option with the `helm install` command. + +## Step 13. Check the status of your ScalarDL Ledger deployment + +After deploying ScalarDL Ledger in your EKS cluster, you must check the status of each component. For details, see [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx) for more details. + +## Step 14. Check the status of your ScalarDL Auditor deployment + +After deploying ScalarDL Auditor on your EKS cluster, you need to check the status of each component. See [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx) for more details. + +## Step 15. Monitor your ScalarDL Ledger deployment + +After deploying ScalarDL Ledger in your EKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Step 16. Monitor your ScalarDL Auditor deployment + +After deploying ScalarDL Auditor in your EKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Remove ScalarDL Ledger and ScalarDL Auditor from EKS + +If you want to remove the environment you created, please remove all the resources in reverse order from which you created them in. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnAKS.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnAKS.mdx new file mode 100644 index 00000000..24268d57 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnAKS.mdx @@ -0,0 +1,53 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Deploy ScalarDL Ledger on Azure Kubernetes Service (AKS) + +This document explains how to deploy **ScalarDL Ledger** on Azure Kubernetes Service (AKS). + +In this guide, you will create the following environment in your Azure environment. + +![image](images/png/AKS_ScalarDL_Ledger.drawio.png) + +## Step 1. Get the ScalarDL Ledger container image + +You must get the ScalarDL Ledger container image. For details, see [How to get the container images of Scalar products](HowToGetContainerImages.mdx). + +## Step 2. Create an AKS cluster + +You must create an AKS cluster for the ScalarDL Ledger deployment. For details, see [Guidelines for creating an AKS cluster for Scalar products](CreateAKSClusterForScalarProducts.mdx). + +## Step 3. Set up a database for ScalarDL Ledger + +You must prepare a database before deploying ScalarDL Ledger. Because ScalarDL Ledger uses ScalarDB internally to access databases, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) to see which types of databases ScalarDB supports. + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment in Azure](SetupDatabaseForAzure.mdx). + +## Step 4. Create a bastion server + +To execute some tools for deploying and managing ScalarDL Ledger on AKS, you must prepare a bastion server in the same Azure Virtual Network (VNet) of the AKS cluster that you created in **Step 2**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 5. Prepare custom values files for the Scalar Helm Charts for both ScalarDL Ledger and ScalarDL Schema Loader + +To perform tasks, like accessing information in the database that you created in **Step 3**, you must configure custom values files for the Scalar Helm Charts for both ScalarDL Ledger and ScalarDL Schema Loader (for Ledger) based on your environment. For details, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + +## Step 6. Deploy ScalarDL Ledger by using the Scalar Helm Chart + +Deploy ScalarDL Ledger in your AKS cluster by using the Helm Chart for ScalarDL Ledger. For details, see [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardl-ledger` command and deploying ScalarDL Ledger in the namespace by using the `-n scalardl-ledger` option with the `helm install` command. + +## Step 7. Check the status your ScalarDL Ledger deployment + +After deploying ScalarDL Ledger in your AKS cluster, you must check the status of each component. For details, see [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx). + +## Step 8. Monitor your ScalarDL Ledger deployment + +After deploying ScalarDL Ledger in your AKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Remove ScalarDL Ledger from AKS + +If you want to remove the environment that you created, please remove all the resources in reverse order from which you created them in. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnEKS.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnEKS.mdx new file mode 100644 index 00000000..05b516b0 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ManualDeploymentGuideScalarDLOnEKS.mdx @@ -0,0 +1,53 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Deploy ScalarDL Ledger on Amazon Elastic Kubernetes Service (EKS) + +This document explains how to deploy **ScalarDL Ledger** on Amazon Elastic Kubernetes Service (EKS). + +In this guide, you will create the following environment in your AWS environment account. + +![image](images/png/EKS_ScalarDL_Ledger.drawio.png) + +## Step 1. Subscribe to ScalarDL Ledger in AWS Marketplace + +You must get the ScalarDL Ledger container image from [AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-3jdwfmqonx7a2) and subscribe to ScalarDL. For details on how to subscribe to ScalarDL Ledger in AWS Marketplace, see [Subscribe to Scalar products from AWS Marketplace](AwsMarketplaceGuide.mdx#subscribe-to-scalar-products-from-aws-marketplace). + +## Step 2. Create an EKS cluster + +You must create an EKS cluster for the ScalarDL Ledger deployment. For details, see [Guidelines for creating an Amazon EKS cluster for Scalar products](CreateEKSClusterForScalarProducts.mdx). + +## Step 3. Set up a database for ScalarDL Ledger + +You must prepare a database before deploying ScalarDL Ledger. Because ScalarDL Ledger uses ScalarDB internally to access databases, refer to [ScalarDB Supported Databases](https://scalardb.scalar-labs.com/docs/latest/requirements#databases) to see which types of databases ScalarDB supports. + +For details on setting up a database, see [Set up a database for ScalarDB/ScalarDL deployment on AWS](SetupDatabaseForAWS.mdx). + +## Step 4. Create a bastion server + +To execute some tools for deploying and managing ScalarDL Ledger on EKS, you must prepare a bastion server in the same Amazon Virtual Private Cloud (VPC) of the EKS cluster you created in **Step 2**. For details, see [Create a Bastion Server](CreateBastionServer.mdx). + +## Step 5. Prepare custom values files for the Scalar Helm Charts for both ScalarDL Ledger and ScalarDL Schema Loader + +To perform tasks, like accessing information in the database that you created in **Step 3**, you must configure custom values files for the Scalar Helm Charts for both ScalarDL Ledger and ScalarDL Schema Loader (for Ledger) based on your environment. For details, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + +## Step 6. Deploy ScalarDL Ledger by using the Scalar Helm Chart + +Deploy ScalarDL Ledger in your EKS cluster by using the Helm Chart for ScalarDL Ledger. For details, see [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx). + +**Note:** We recommend creating a dedicated namespace by using the `kubectl create ns scalardl-ledger` command and deploying ScalarDL Ledger in the namespace by using the `-n scalardl-ledger` option with the `helm install` command. + +## Step 7. Check the status of your ScalarDL Ledger deployment + +After deploying ScalarDL Ledger in your EKS cluster, you must check the status of each component. For details, see [Components to Regularly Check When Running in a Kubernetes Environment](RegularCheck.mdx). + +## Step 8. Monitor your ScalarDL Ledger deployment + +After deploying ScalarDL Ledger in your EKS cluster, we recommend monitoring the deployed components and collecting their logs, especially in production. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +## Remove ScalarDL Ledger from EKS + +If you want to remove the environment that you created, please remove all the resources in reverse order from which you created them in. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/NetworkPeeringForScalarDLAuditor.mdx b/versioned_docs/version-3.15/scalar-kubernetes/NetworkPeeringForScalarDLAuditor.mdx new file mode 100644 index 00000000..a6425cf9 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/NetworkPeeringForScalarDLAuditor.mdx @@ -0,0 +1,57 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Configure Network Peering for ScalarDL Auditor Mode + +This document explains how to connect multiple private networks for ScalarDL Auditor mode to perform network peering. For ScalarDL Auditor mode to work properly, you must connect ScalarDL Ledger to ScalarDL Auditor. + +## What network you must connect + +To make ScalarDL Auditor mode (Byzantine fault detection) work properly, you must connect three private networks. + +* [ScalarDL Ledger network] ↔ [ScalarDL Auditor network] +* [ScalarDL Ledger network] ↔ [application (client) network] +* [ScalarDL Auditor network] ↔ [application (client) network] + +## Network requirements + +### IP address ranges + +To avoid conflicting IP addresses between the private networks, you must have private networks with different IP address ranges. For example: + +* **Private network for ScalarDL Ledger:** 10.1.0.0/16 +* **Private network for ScalarDL Auditor:** 10.2.0.0/16 +* **Private network for application (client):** 10.3.0.0/16 + +### Connections + +The default network ports for connecting ScalarDL Ledger, ScalarDL Auditor, and the application (client) by default are as follows. You must allow these connections between each private network. + +* **ScalarDL Ledger** + * **50051/TCP:** Accept requests from an application (client) and ScalarDL Auditor via Scalar Envoy. + * **50052/TCP:** Accept privileged requests from an application (client) and ScalarDL Auditor via Scalar Envoy. +* **ScalarDL Auditor** + * **40051/TCP:** Accept requests from an application (client) and ScalarDL Ledger via Scalar Envoy. + * **40052/TCP:** Accept privileged requests from an application (client) and ScalarDL Ledger via Scalar Envoy. +* **Scalar Envoy** (used with ScalarDL Ledger and ScalarDL Auditor) + * **50051/TCP:** Accept requests for ScalarDL Ledger from an application (client) and ScalarDL Auditor. + * **50052/TCP:** Accept privileged requests for ScalarDL Ledger from an application (client) and ScalarDL Auditor. + * **40051/TCP:** Accept requests for ScalarDL Auditor from an application (client) and ScalarDL Ledger. + * **40052/TCP:** Accept privileged requests for ScalarDL Auditor from an application (client) and ScalarDL Ledger. + +Note that, if you change the listening port for ScalarDL in the configuration file (ledger.properties or auditor.properties) from the default, you must allow the connections by using the port that you configured. + +## Private-network peering + +For details on how to connect private networks in each cloud, see official documents. + +### Amazon VPC peering + +For details on how to peer virtual private clouds (VPCs) in an Amazon Web Services (AWS) environment, see the official documentation from Amazon at [Create a VPC peering connection](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html). + +### Azure VNet peering + +For details on how to peer virtual networks in an Azure environment, see the official documentation from Microsoft at [Virtual network peering](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview). diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDBCluster.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDBCluster.mdx new file mode 100644 index 00000000..2a51f739 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDBCluster.mdx @@ -0,0 +1,153 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Production checklist for ScalarDB Cluster + +This checklist provides recommendations when deploying ScalarDB Cluster in a production environment. + +## Before you begin + +In this checklist, we assume that you are deploying ScalarDB Cluster on a managed Kubernetes cluster, which is recommended. + +## Production checklist: ScalarDB Cluster + +The following is a checklist of recommendations when setting up ScalarDB Cluster in a production environment. + +### Number of pods and Kubernetes worker nodes + +To ensure that the Kubernetes cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardb-cluster-custom-values-indirect-mode.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different availability zones (AZs), you can withstand an AZ failure. + +::: + +### Worker node specifications + +From the perspective of commercial licenses, resources for one pod running ScalarDB Cluster are limited to 2vCPU / 4GB memory. In addition, some pods other than ScalarDB Cluster pods exist on the worker nodes. + +In other words, the following components could run on one worker node: + +* ScalarDB Cluster pod (2vCPU / 4GB) +* Envoy proxy (if you use `indirect` client mode or use a programming language other than Java) +* Your application pods (if you choose to run your application's pods on the same worker node) +* Monitoring components (if you deploy monitoring components such `kube-prometheus-stack`) +* Kubernetes components + +:::note + +You do not need to deploy an Envoy pod when using `direct-kubernetes` mode. + +::: + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [Number of pods and Kubernetes worker nodes](ProductionChecklistForScalarDBCluster.mdx#number-of-pods-and-kubernetes-worker-nodes). + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum for a production environment. You should also consider the resources of the Kubernetes cluster (for example, the number of worker nodes, vCPUs per node, memories per node, ScalarDB Cluster pods, and pods for your application), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node to decide on the worker node resources. + +### Network + +You should create the Kubernetes cluster on a private network since ScalarDB Cluster does not provide any services to users directly via internet access. We recommend accessing ScalarDB Cluster via a private network from your applications. + +### Monitoring and logging + +You should monitor the deployed components and collect their logs. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +### Backup and restore + +You should enable the automatic backup feature and point-in-time recovery (PITR) feature in the backend database. For details, see [Set up a database for ScalarDB/ScalarDL deployment](SetupDatabase.mdx). + +## Production checklist: Client applications that access ScalarDB Cluster + +The following is a checklist of recommendations when setting up a client application that accesses ScalarDB Cluster in a production environment. + +### Client mode (Java client library only) + +When using Java for your application, you can use an official Java client library. In this case, you can choose one of the two client modes: [`direct-kubernetes mode`](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#direct-kubernetes-client-mode) or [`indirect mode`](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#indirect-client-mode). + +From the perspective of performance, we recommend using `direct-kubernetes` mode. To use `direct-kubernetes` mode, you must deploy your application pods on the same Kubernetes cluster as ScalarDB Cluster pods. In this case, you don't need to deploy Envoy pods. + +If you can't deploy your Java application pods on the same Kubernetes cluster as ScalarDB Cluster pods for some reason, you must use `indirect` mode. In this case, you must deploy Envoy pods. + +:::note + +The client mode configuration is dedicated to the Java client library. If you use a programming language other than Java for your application (essentially, if you use the [gRPC API](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-grpc-api-guide) or [gRPC SQL API](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide) directly from the programming language), no such configuration exists. In this case, you must deploy Envoy pods. + +::: + +### Transaction manager configuration (Java client library only) + +The client application must always access the database through ScalarDB Cluster. To ensure requests are running properly, check the properties file for your client application and confirm that `scalar.db.transaction_manager=cluster` is configured when using the CRUD API. + +#### Recommended for production environments + +```mermaid +flowchart LR + app["App
ScalarDB Cluster Library with gRPC"] + server["ScalarDB Cluster
ScalarDB Library with
Consensus Commit"] + db[(Underlying storage or database)] + app --> server --> db +``` + +#### Not recommended for production environments (for testing purposes only) + +```mermaid +flowchart LR + app["App
ScalarDB Cluster Library with
Consensus Commit"] + db[(Underlying storage or database)] + app --> db +``` + +### SQL connection configuration (Java client library only) + +The client application must always access the database through ScalarDB Cluster. To ensure requests are running properly, check the properties file for your client application and confirm that `scalar.db.sql.connection_mode=cluster` is configured when using the SQL API. + +#### Recommended for production environments + +```mermaid +flowchart LR + app["App
ScalarDB SQL Library (Cluster mode)"] + server["ScalarDB Cluster
ScalarDB Library with
Consensus Commit"] + db[(Underlying storage or database)] + app --> server --> db +``` + +#### Not recommended for production environments (for testing purposes only) + +```mermaid +flowchart LR + app["App
ScalarDB SQL Library (Direct mode)"] + db[(Underlying storage or database)] + app --> db +``` + +### Deployment of the client application when using `direct-kubernetes` client mode (Java client library only) + +If you use [`direct-kubernetes` client mode](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api#direct-kubernetes-client-mode), you must deploy your client application on the same Kubernetes cluster as the ScalarDB Cluster deployment. + +Also, when using `direct-kubernetes` client mode, you must deploy additional Kubernetes resources to make your client application work properly. For details, see [Deploy your client application on Kubernetes with `direct-kubernetes` mode](../helm-charts/how-to-deploy-scalardb-cluster.mdx#deploy-your-client-application-on-kubernetes-with-direct-kubernetes-mode). + +### Transaction handling (Java client library and gRPC API) + +You must make sure that your application always runs [`commit()`](https://scalardb.scalar-labs.com/docs/latest/api-guide#commit-a-transaction) or [`rollback()`](https://scalardb.scalar-labs.com/docs/latest/api-guide#roll-back-or-abort-a-transaction) after you [`begin()`](https://scalardb.scalar-labs.com/docs/latest/api-guide#begin-or-start-a-transaction) a transaction. If the application does not run `commit()` or `rollback()`, your application might experience unexpected issues or read inconsistent data from the backend database. + +:::note + +If you use the [gRPC API](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-grpc-api-guide) or [SQL gRPC API](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide), your application should call a `Commit` or `Rollback` service after you call a `Begin` service to begin a transaction. + +::: + +### Exception handling (Java client library and gRPC API) + +You must make sure that your application handles transaction exceptions. For details, see the document for the API that you are using: + +* [Handle exceptions (Transactional API)](https://scalardb.scalar-labs.com/docs/latest/api-guide#handle-exceptions). +* [Handle exceptions (two-phase commit transactions API)](https://scalardb.scalar-labs.com/docs/latest/two-phase-commit-transactions#handle-exceptions) +* [Execute transactions (ScalarDB SQL API)](https://scalardb.scalar-labs.com/docs/latest/scalardb-sql/sql-api-guide#execute-transactions) +* [Handle SQLException (ScalarDB JDBC)](https://scalardb.scalar-labs.com/docs/latest/scalardb-sql/jdbc-guide#handle-sqlexception) +* [Error handling (ScalarDB Cluster gRPC API)](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-grpc-api-guide#error-handling-1) +* [Error handling (ScalarDB Cluster SQL gRPC API)](https://scalardb.scalar-labs.com/docs/latest/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide#error-handling-1) diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLAuditor.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLAuditor.mdx new file mode 100644 index 00000000..2e2a6885 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLAuditor.mdx @@ -0,0 +1,172 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Production checklist for ScalarDL Auditor + +This checklist provides recommendations when deploying ScalarDL Auditor in a production environment. + +## Before you begin + +In this checklist, we assume that you are deploying ScalarDL Auditor on a managed Kubernetes cluster, which is recommended. + +## Production checklist: ScalarDL Auditor + +The following is a checklist of recommendations when setting up ScalarDL Auditor in a production environment. + +### ScalarDL availability + +To ensure that the Kubernetes cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-audit-custom-values.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different availability zones (AZs), you can withstand an AZ failure. + +::: + +### Resources + +From the perspective of commercial licenses, resources for one pod running ScalarDL Auditor are limited to 2vCPU / 4GB memory. In addition to the ScalarDL Auditor pod, Kubernetes could deploy some of the following components to each worker node: + +* ScalarDL Auditor pod (2vCPU / 4GB) +* Envoy proxy +* Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) +* Kubernetes components + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [ScalarDL availability](#scalardl-availability). + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum environment for production. You should also consider the resources of the Kubernetes cluster (for example, the number of worker nodes, vCPUs per node, memory per node, and ScalarDL Auditor pods), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Network + +You should create the Kubernetes cluster on a private network since ScalarDL Auditor does not provide any services to users directly via internet access. We recommend accessing ScalarDL Auditor via a private network from your applications. + +### Monitoring and logging + +You should monitor the deployed components and collect their logs. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +### Backup and restore + +You should enable the automatic backup feature and point-in-time recovery (PITR) feature in the backend database. For details, see [Set up a database for ScalarDB/ScalarDL deployment](SetupDatabase.mdx). + +### ScalarDL Auditor deployment + +For Byzantine fault detection in ScalarDL to work properly, do not deploy ScalarDL Auditor pods on the same Kubernetes clusters as the ScalarDL Ledger deployment. Instead, you must deploy ScalarDL Auditor pods in an environment other than the administrative domain (other than the Kubernetes cluster) for the ScalarDL Ledger deployment. + +#### Required for production environments + +```mermaid +graph LR + subgraph "ScalarDL" + subgraph "Administrative domain 1" + subgraph "Kubernetes cluster for Ledger" + B-1[ScalarDL Ledger] + end + end + subgraph "Administrative domain 2" + subgraph "Kubernetes cluster for Auditor" + C-1[ScalarDL Auditor] + end + end + end +``` + +#### Not recommended for production environments (for testing purposes only) + +```mermaid +graph LR + subgraph "Kubernetes cluster" + direction LR + A-1[ScalarDL Ledger] + A-2[ScalarDL Auditor] + end +``` + +### Connection between ScalarDL Ledger and ScalarDL Auditor + +For ScalarDL Auditor mode to work properly, you must allow the connection between ScalarDL Ledger and ScalarDL Auditor. + +```mermaid +graph LR + subgraph "Kubernetes cluster for Ledger" + A-1[ScalarDL Ledger] + end + subgraph "Kubernetes cluster for Auditor" + B-1[ScalarDL Auditor] + end + A-1 --- B-1 +``` + +ScalarDL uses the following ports for the connections between ScalarDL Ledger and ScalarDL Auditor. You must allow these connections between ScalarDL Ledger and ScalarDL Auditor: + +* ScalarDL Ledger + * 50051/TCP + * 50052/TCP +* ScalarDL Auditor + * 40051/TCP + * 40052/TCP + +### Private key and certificate + +When you use PKI for authentication, you must make sure that private keys and certificates that you register to ScalarDL Ledger and ScalaDL Auditor match the following requirements: + +```console +Algorithm : ECDSA +Hash function : SHA256 +Curve parameter : P-256 +``` + +For details, see [How to get a certificate](https://scalardl.scalar-labs.com/docs/latest/ca/caclient-getting-started). + +## Production checklist: Client applications that access ScalarDL Auditor + +The following is a checklist of recommendations when setting up a client application that accesses ScalarDL Auditor in a production environment. + +### Client application deployment + +For Byzantine fault detection in ScalarDL to work properly, do not deploy your application pods on the same Kubernetes clusters as the ScalarDL deployment. Instead, you must deploy your application in an environment other than the administrative domain (other than the Kubernetes cluster) for the ScalarDL deployment. + +#### Required for production environments + +```mermaid +graph LR + subgraph "Administrative domain 1" + subgraph "Another environment" + A-1[User application] + end + end + subgraph "ScalarDL" + subgraph "Administrative domain 2" + subgraph "Kubernetes cluster for Ledger" + B-1[ScalarDL Ledger] + end + end + subgraph "Administrative domain 3" + subgraph "Kubernetes cluster for Auditor" + C-1[ScalarDL Auditor] + end + end + end + A-1 --> B-1 + A-1 --> C-1 +``` + +#### Not recommended for production environments (for testing purposes only) + +```mermaid +graph LR + subgraph "Kubernetes cluster" + direction LR + A-1[User application] + A-2[ScalarDL Ledger] + A-3[ScalarDL Auditor] + end + A-1 --> A-2 + A-1 --> A-3 +``` + +### Client application checklist + +You must also make sure that you satisfy the [Production checklist: Client applications that access ScalarDL Ledger](ProductionChecklistForScalarDLLedger.mdx#production-checklist-client-applications-that-access-scalardl-ledger). diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLLedger.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLLedger.mdx new file mode 100644 index 00000000..2a3bc14a --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarDLLedger.mdx @@ -0,0 +1,158 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Production checklist for ScalarDL Ledger + +This checklist provides recommendations when deploying ScalarDL Ledger in a production environment. + +## Before you begin + +In this checklist, we assume that you are deploying ScalarDL Ledger on a managed Kubernetes cluster, which is recommended. + +## Production checklist: ScalarDL Ledger + +The following is a checklist of recommendations when setting up ScalarDL Ledger in a production environment. + +### ScalarDL availability + +To ensure that the Kubernetes cluster has high availability, you should use at least three worker nodes and deploy at least three pods spread across the worker nodes. You can see the [sample configurations](https://github.com/scalar-labs/scalar-kubernetes/blob/master/conf/scalardl-custom-values.yaml) of `podAntiAffinity` for making three pods spread across the worker nodes. + +:::note + +If you place the worker nodes in different availability zones (AZs), you can withstand an AZ failure. + +::: + +### Resources + +From the perspective of commercial licenses, resources for one pod running ScalarDL Ledger are limited to 2vCPU / 4GB memory. In addition to the ScalarDL Ledger pod, Kubernetes could deploy some of the following components to each worker node: + +* ScalarDL Ledger pod (2vCPU / 4GB) +* Envoy proxy +* Monitoring components (if you deploy monitoring components such as `kube-prometheus-stack`) +* Kubernetes components + +With this in mind, you should use a worker node that has at least 4vCPU / 8GB memory resources and use at least three worker nodes for availability, as mentioned in [ScalarDL availability](#scalardl-availability). + +However, three nodes with at least 4vCPU / 8GB memory resources per node is the minimum environment for production. You should also consider the resources of the Kubernetes cluster (for example, the number of worker nodes, vCPUs per node, memory per node, and ScalarDL Ledger pods), which depend on your system's workload. In addition, if you plan to scale the pods automatically by using some features like [Horizontal Pod Autoscaling (HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), you should consider the maximum number of pods on the worker node when deciding the worker node resources. + +### Network + +You should create the Kubernetes cluster on a private network since ScalarDL Ledger does not provide any services to users directly via internet access. We recommend accessing ScalarDL Ledger via a private network from your applications. + +### Monitoring and logging + +You should monitor the deployed components and collect their logs. For details, see [Monitoring Scalar products on a Kubernetes cluster](K8sMonitorGuide.mdx) and [Collecting logs from Scalar products on a Kubernetes cluster](K8sLogCollectionGuide.mdx). + +### Backup and restore + +You should enable the automatic backup feature and point-in-time recovery (PITR) feature in the backend database. For details, see [Set up a database for ScalarDB/ScalarDL deployment](SetupDatabase.mdx). + +## Production checklist: Client applications that access ScalarDL Ledger + +The following is a checklist of recommendations when setting up a client application that accesses ScalarDL Ledger in a production environment. + +### Client application deployment + +For Byzantine fault detection in ScalarDL to work properly, do not deploy your application pods on the same Kubernetes clusters as the ScalarDL Ledger deployment. Instead, you must deploy your application in an environment other than the administrative domain (other than the Kubernetes cluster) for the ScalarDL Ledger deployment. + +#### Required for production environments + +```mermaid +graph LR + subgraph "Administrative domain 1" + subgraph "Another environment" + A-1[User application] + end + end + subgraph "Administrative domain 2" + subgraph "Kubernetes cluster" + B-1[ScalarDL Ledger] + end + end + A-1 --> B-1 +``` + +#### Not recommended for production environments (for testing purposes only) + +```mermaid +graph LR + subgraph "Kubernetes cluster" + direction LR + A-1[User application] --> A-2[ScalarDL Ledger] + end +``` + +### Contract and function + +To check if your contract and function follow the guidelines, see the following: + +* [A Guide on How to Write a Good Contract for ScalarDL](https://scalardl.scalar-labs.com/docs/latest/how-to-write-contract) +* [A Guide on How to Write Function for ScalarDL](https://scalardl.scalar-labs.com/docs/latest/how-to-write-function) + +### Contract versioning + +After you register a contract, you cannot overwrite that existing contract. So, you should consider the versioning of contracts. We recommend one of the following two methods. + +#### Versioning by using `Class Name` + +```console +Contract ID : FooV1 +Binary Name : com.example.contract.FooV1 +Class file (Class Name) : src/main/java/com/example/contract/FooV1.class +--- +Contract ID : FooV2 +Binary Name : com.example.contract.FooV2 +Class file (Class Name) : src/main/java/com/example/contract/FooV2.class +``` + +#### Versioning by using `Package Name` + +```console +Contract ID : FooV3 +Binary Name : com.example.contract.v3.Foo +Class file (Class Name) : src/main/java/com/example/contract/v3/Foo.class +--- +Contract ID : FooV4 +Binary Name : com.example.contract.v4.Foo +Class file (Class Name) : src/main/java/com/example/contract/v4/Foo.class +``` + +### Contract limitations + +If the binary name, package name, and class name are different when you register the contract, you cannot execute that contract after registering it. + +#### Binary name and class name are different (you cannot execute this contract) + +```console +Contract ID : FooV5 +Binary Name : com.example.contract.FooV5 +Class file (Class Name) : src/main/java/com/example/contract/FooV6.class +``` + +#### Binary name and package name are different (you cannot execute this contract) + +```console +Contract ID : FooV7 +Binary Name : com.example.contract.v7.Foo +Class file (Class Name) : src/main/java/com/example/contract/v8/Foo.class +``` + +### Private key and certificate + +When you use PKI for authentication, you must make sure that private keys and certificates that you register to ScalarDL Ledger match the following requirements: + +```console +Algorithm : ECDSA +Hash function : SHA256 +Curve parameter : P-256 +``` + +For details, see [How to get a certificate](https://scalardl.scalar-labs.com/docs/latest/ca/caclient-getting-started). + +### Exception handling + +You must make sure that your application handles exceptions. For details, see [A Guide on How to Handle Errors in ScalarDL](https://scalardl.scalar-labs.com/docs/latest/how-to-write-applications#handle-errors). diff --git a/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarProducts.mdx b/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarProducts.mdx new file mode 100644 index 00000000..0779599a --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/ProductionChecklistForScalarProducts.mdx @@ -0,0 +1,14 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Production checklist for Scalar products + +To make your deployment ready for production, refer to the following: + +* [Production checklist for ScalarDB Cluster](ProductionChecklistForScalarDBCluster.mdx) +* [Production checklist for ScalarDL Ledger](ProductionChecklistForScalarDLLedger.mdx) +* [Production checklist for ScalarDL Auditor](ProductionChecklistForScalarDLAuditor.mdx) diff --git a/versioned_docs/version-3.15/scalar-kubernetes/RegularCheck.mdx b/versioned_docs/version-3.15/scalar-kubernetes/RegularCheck.mdx new file mode 100644 index 00000000..497546ec --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/RegularCheck.mdx @@ -0,0 +1,95 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Components to Regularly Check When Running in a Kubernetes Environment + +Most of the components deployed by manual deployment guides are self-healing with the help of the managed Kubernetes services and Kubernetes self-healing capability. There are also configured alerts that occur when some unexpected behavior happens. Thus, there shouldn't be so many things to do day by day for the deployment of Scalar products on the managed Kubernetes cluster. However, it is recommended to check the status of a system on a regular basis to see if everything is working fine. Here is the list of things you might want to do on a regular basis. + +## Kubernetes resources + +### Check if Pods are all healthy statues + +Please check the Kubernetes namespaces: + +* `default` (or specified namespace when you deploy Scalar products) for the Scalar product deployment +* `monitoring` for the Prometheus Operator and Loki + +What to check: + +* `STATUS` is all `Running` +* Pods are evenly distributed on the different nodes + +```console +kubectl get pod -o wide -n +``` + +You should see the following output: + +```console +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +scalardb-7876f595bd-2jb28 1/1 Running 0 2m35s 10.244.2.6 k8s-worker2 +scalardb-7876f595bd-rfvk6 1/1 Running 0 2m35s 10.244.1.8 k8s-worker +scalardb-7876f595bd-xfkv4 1/1 Running 0 2m35s 10.244.3.8 k8s-worker3 +scalardb-envoy-84c475f77b-cflkn 1/1 Running 0 2m35s 10.244.1.7 k8s-worker +scalardb-envoy-84c475f77b-tzmc9 1/1 Running 0 2m35s 10.244.3.7 k8s-worker3 +scalardb-envoy-84c475f77b-vztqr 1/1 Running 0 2m35s 10.244.2.5 k8s-worker2 +``` + +```console +kubectl get pod -n monitoring -o wide +``` + +You should see the following output: + +```console +NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES +alertmanager-scalar-monitoring-kube-pro-alertmanager-0 2/2 Running 1 (11m ago) 12m 10.244.2.4 k8s-worker2 +prometheus-scalar-monitoring-kube-pro-prometheus-0 2/2 Running 0 12m 10.244.1.5 k8s-worker +scalar-logging-loki-0 1/1 Running 0 13m 10.244.2.2 k8s-worker2 +scalar-logging-loki-promtail-2c4k9 0/1 Running 0 13m 10.244.0.5 k8s-control-plane +scalar-logging-loki-promtail-8r48b 1/1 Running 0 13m 10.244.3.2 k8s-worker3 +scalar-logging-loki-promtail-b26c6 1/1 Running 0 13m 10.244.2.3 k8s-worker2 +scalar-logging-loki-promtail-sks56 1/1 Running 0 13m 10.244.1.2 k8s-worker +scalar-monitoring-grafana-77c4dbdd85-4mrn7 3/3 Running 0 12m 10.244.3.4 k8s-worker3 +scalar-monitoring-kube-pro-operator-7575dd8bbd-bxhrc 1/1 Running 0 12m 10.244.1.3 k8s-worker +``` + +### Check if Nodes are all healthy statuses + +What to check: + +* `STATUS` is all `Ready` + +```console +kubectl get nodes +``` + +You should see the following output: + +```console +NAME STATUS ROLES AGE VERSION +k8s-control-plane Ready control-plane 16m v1.25.3 +k8s-worker Ready 15m v1.25.3 +k8s-worker2 Ready 15m v1.25.3 +k8s-worker3 Ready 15m v1.25.3 +``` + +## Prometheus dashboard (Alerts of Scalar products) + +Access to the Prometheus dashboard according to the document [Monitoring Scalar products on the Kubernetes cluster](K8sMonitorGuide.mdx). In the **Alerts** tab, you can see the alert status. + +What to check: + +* All alerts are **green (Inactive)** + +If some issue is occurring, it shows you **red (Firing)** status. + +## Grafana dashboard (metrics of Scalar products) + +Access to the Grafana dashboard according to the document [Monitoring Scalar products on the Kubernetes cluster](K8sMonitorGuide.mdx). In the **Dashboards** tab, you can see the dashboard of Scalar products. In these dashboards, you can see some metrics of Scalar products. + +Those dashboards cannot address issues directly, but you can see changes from normal (e.g., increasing transaction errors) to get hints for investigating issues. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/RestoreDatabase.mdx b/versioned_docs/version-3.15/scalar-kubernetes/RestoreDatabase.mdx new file mode 100644 index 00000000..61a615e3 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/RestoreDatabase.mdx @@ -0,0 +1,160 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Restore databases in a Kubernetes environment + +This guide explains how to restore databases that ScalarDB or ScalarDL uses in a Kubernetes environment. Please note that this guide assumes that you are using a managed database from a cloud services provider as the backend database for ScalarDB or ScalarDL. + +## Procedure to restore databases + +1. Scale in ScalarDB or ScalarDL pods to **0** to stop requests to the backend databases. You can scale in the pods to **0** by using the `--set *.replicaCount=0` flag in the helm command. + * ScalarDB Server + ```console + helm upgrade scalar-labs/scalardb -n -f /path/to/ --set scalardb.replicaCount=0 + ``` + * ScalarDL Ledger + ```console + helm upgrade scalar-labs/scalardl -n -f /path/to/ --set ledger.replicaCount=0 + ``` + * ScalarDL Auditor + ```console + helm upgrade scalar-labs/scalardl-audit -n -f /path/to/ --set auditor.replicaCount=0 + ``` +2. Restore the databases by using the point-in-time recovery (PITR) feature. + + For details on how to restore the databases based on your managed database, please refer to the [Supplemental procedures to restore databases based on managed database](RestoreDatabase.mdx#supplemental-procedures-to-restore-databases-based-on-managed-database) section in this guide. + + If you are using NoSQL or multiple databases, you should specify the middle point of the pause duration period that you created when following the backup procedure in [Back up a NoSQL database in a Kubernetes environment](BackupNoSQL.mdx). +3. Update **database.properties**, **ledger.properties**, or **auditor.properties** based on the newly restored database. + + Because the PITR feature restores databases as another instance, you must update the endpoint information in the custom values file of ScalarDB or ScalarDL to access the newly restored databases. For details on how to configure the custom values file, see [Configure a custom values file for Scalar Helm Charts](../helm-charts/configure-custom-values-file.mdx). + + Please note that, if you are using Amazon DynamoDB, your data will be restored with another table name instead of another instance. In other words, the endpoint will not change after restoring the data. Instead, you will need to restore the data by renaming the tables in Amazon DynamoDB. For details on how to restore data with the same table name, please see the [Amazon DynamoDB](RestoreDatabase.mdx#amazon-dynamodb) section in this guide. +4. Scale out the ScalarDB or ScalarDL pods to **1** or more to start accepting requests from clients by using the `--set *.replicaCount=N` flag in the helm command. + * ScalarDB Server + ```console + helm upgrade scalar-labs/scalardb -n -f /path/to/ --set scalardb.replicaCount=3 + ``` + * ScalarDL Ledger + ```console + helm upgrade scalar-labs/scalardl -n -f /path/to/ --set ledger.replicaCount=3 + ``` + * ScalarDL Auditor + ```console + helm upgrade scalar-labs/scalardl-audit -n -f /path/to/ --set auditor.replicaCount=3 + ``` + +## Supplemental procedures to restore data based on managed database + +### Amazon DynamoDB + +When using the PITR feature, Amazon DynamoDB restores data with another table name. Therefore, you must follow additional steps to restore data with the same table name. + +#### Steps + +1. Create a backup. + 1. Select the middle point of the pause duration period as the restore point. + 2. Use PITR to restore table A to table B. + 3. Perform a backup of the restored table B. Then, confirm the backup is named appropriately for backup B. + 4. Remove table B. + + For details on how to restore DynamoDB tables by using PITR and how to perform a backup of DynamoDB tables manually, see the following official documentation from Amazon: + + * [Restoring a DynamoDB table to a point in time](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/PointInTimeRecovery.Tutorial.html) + * [Backing up a DynamoDB table](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Backup.Tutorial.html) + + You can do this **Create a backup** step as a part of backup operations in the [Back up a NoSQL database in a Kubernetes environment](BackupNoSQL.mdx#create-a-period-to-restore-data-and-perform-a-backup). + +2. Restore from the backup. + 1. Remove table A. + 2. Create a table named A by using backup B. + +3. Update the table configuration if necessary, depending on your environment. + + Some configurations, like autoscaling policies, are not set after restoring, so you may need to manually set those configurations depending on your needs. For details, see the official documentation from Amazon at [Backing up and restoring DynamoDB tables with DynamoDB: How it works](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CreateBackup.html). + + For example, if you are using ScalarDB Schema Loader or ScalarDL Schema Loader to create tables, autoscaling is enabled by default. Therefore, you will need to manually enable autoscaling for the restored tables in DynamoDB. For details on how to enable autoscaling in DynamoDB, see the official documentation from Amazon at [Enabling DynamoDB auto scaling on existing tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/AutoScaling.Console.html#AutoScaling.Console.ExistingTable). + + In addition, after restoring the databases, the PITR feature will be disabled and the read/write capacity mode is reset to the default value. If necessary, depending on your environment, you will need to manually set these configurations. For some configurations for restored tables, see [Set up a database for ScalarDB/ScalarDL deployment on AWS (Amazon DynamoDB)](SetupDatabaseForAWS.mdx#amazon-dynamodb). + +### Azure Cosmos DB for NoSQL + +When using the PITR feature, Azure Cosmos DB restores data by using another account. Therefore, you must update the endpoint configuration in the custom values file. + +#### Steps + +1. Restore the account. For details on how to restore an Azure Cosmos DB account by using PITR, see [Restore an Azure Cosmos DB account that uses continuous backup mode](https://learn.microsoft.com/en-us/azure/cosmos-db/restore-account-continuous-backup). + +2. Change the **default consistency level** for the restored account from the default value to **Strong**. For details on how to change this value, see the official documentation from Microsoft a [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +3. Update **database.properties** for ScalarDB Schema Loader or ScalarDL Schema Loader based on the newly restored account. + + ScalarDB implements the Cosmos DB adapter by using its stored procedures, which are installed when creating schemas by using ScalarDB Schema Loader or ScalarDL Schema Loader. However, the PITR feature in Cosmos DB does not restore stored procedures, so you will need to reinstall the required stored procedures for all tables after restoration. You can reinstall the required stored procedures by using the `--repair-all` option in ScalarDB Schema Loader or ScalarDL Schema Loader. + * **ScalarDB tables:** For details on how to configure **database.properties** for ScalarDB Schema Loader, see [Configure ScalarDB for Cosmos DB for NoSQL](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb). + + * **ScalarDL tables:** For details on how to configure the custom values file for ScalarDL Schema Loader, see [Configure a custom values file for ScalarDL Schema Loader](../helm-charts/configure-custom-values-scalardl-schema-loader.mdx). + +4. Re-create the stored procedures by using the `--repair-all` flag in ScalarDB Schema Loader or ScalarDL Schema Loader as follows: + + * ScalarDB tables + ```console + java -jar scalardb-schema-loader-.jar --config /path/to/ -f /path/to/ [--coordinator] --repair-all + ``` + * ScalarDL Ledger tables + ```console + helm install repair-schema-ledger scalar-labs/schema-loading -n -f /path/to/ --set "schemaLoading.commandArgs={--repair-all}" + ``` + * ScalarDL Auditor tables + ```console + helm install repair-schema-auditor scalar-labs/schema-loading -n -f /path/to/ --set "schemaLoading.commandArgs={--repair-all}" + ``` + + For more details on repairing tables in ScalarDB Schema Loader, see [Repair tables](https://scalardb.scalar-labs.com/docs/latest/schema-loader#repair-tables). + +5. Update the table configuration if necessary, depending on your environment. For some configurations for restored accounts, see [Set up a database for ScalarDB/ScalarDL deployment on Azure (Azure Cosmos DB for NoSQL)](SetupDatabaseForAzure.mdx#azure-cosmos-db-for-nosql). + +### Amazon RDS + +When using the PITR feature, Amazon RDS restores data by using another database instance. Therefore, you must update the endpoint configuration in the custom values file. + +#### Steps + +1. Restore the database instance. For details on how to restore the Amazon RDS instance by using PITR, see the following official documentation from Amazon: + * [Restoring a DB instance to a specified time](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIT.html) + * [Restoring a Multi-AZ DB cluster to a specified time](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIT.MultiAZDBCluster.html) + +2. Update the table configuration if necessary, depending on your environment. For some configurations for the restored database instance, see [Set up a database for ScalarDB/ScalarDL deployment on AWS (Amazon RDS for MySQL, PostgreSQL, Oracle, and SQL Server)](SetupDatabaseForAWS.mdx#amazon-rds-for-mysql-postgresql-oracle-and-sql-server). + +### Amazon Aurora + +When using the PITR feature, Amazon Aurora restores data by using another database cluster. Therefore, you must update the endpoint configuration in the custom values file. + +#### Steps + +1. Restore the database cluster. For details on how to restore an Amazon Aurora cluster by using PITR. see the official documentation from Amazon at [Restoring a DB cluster to a specified time](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-pitr.html). + +2. Add a replica (reader) to make the database cluster a Multi-AZ cluster if necessary, depending on your environment. + + The PITR feature in Amazon Aurora cannot restore a database cluster by using a Multi-AZ configuration. If you want to restore the database cluster as a Multi-AZ cluster, you must add a reader after restoring the database cluster. For details on how to add a reader, see the official documentation from Amazon at [Adding Aurora Replicas to a DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-replicas-adding.html). + +3. Update the table configuration if necessary, depending on your environment. For some configurations for the restored database cluster, see [Set up a database for ScalarDB/ScalarDL deployment on AWS (Amazon Aurora MySQL and Amazon Aurora PostgreSQL)](SetupDatabaseForAWS.mdx#amazon-aurora-mysql-and-amazon-aurora-postgresql). + +### Azure Database for MySQL/PostgreSQL + +When using the PITR feature, Azure Database for MySQL/PostgreSQL restores data by using another server. Therefore, you must update the endpoint configuration in the custom values file. + +#### Steps + +1. Restore the database server. For details on how to restore an Azure Database for MySQL/PostgreSQL server by using PITR, see the following: + + * [Point-in-time restore of a Azure Database for MySQL Flexible Server using Azure portal](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/how-to-restore-server-portal) + * [Backup and restore in Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-backup-restore) + +2. Update the table configuration if necessary, depending on your environment. For some configurations for the restored database server, see the following: + + * [Set up a database for ScalarDB/ScalarDL deployment on Azure (Azure Database for MySQL)](SetupDatabaseForAzure.mdx#azure-database-for-mysql) + * [Set up a database for ScalarDB/ScalarDL deployment on Azure (Azure Database for PostgreSQL)](SetupDatabaseForAzure.mdx#azure-database-for-postgresql) diff --git a/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabase.mdx b/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabase.mdx new file mode 100644 index 00000000..3ffe0967 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabase.mdx @@ -0,0 +1,13 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Set up a database for ScalarDB/ScalarDL deployment + +This guide explains how to set up a database for ScalarDB/ScalarDL deployment on cloud services. + +* [Set up a database for ScalarDB/ScalarDL deployment on AWS](SetupDatabaseForAWS.mdx) +* [Set up a database for ScalarDB/ScalarDL deployment on Azure](SetupDatabaseForAzure.mdx) diff --git a/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabaseForAWS.mdx b/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabaseForAWS.mdx new file mode 100644 index 00000000..78c817fd --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabaseForAWS.mdx @@ -0,0 +1,182 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Set up a database for ScalarDB/ScalarDL deployment on AWS + +This guide explains how to set up a database for ScalarDB/ScalarDL deployment on AWS. + +## Amazon DynamoDB + +### Authentication method + +When you use DynamoDB, you must set `REGION`, `ACCESS_KEY_ID`, and `SECRET_ACCESS_KEY` in the ScalarDB/ScalarDL properties file as follows. + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=dynamo +``` + +Please refer to the following document for more details on the properties for DynamoDB. + +* [Configure ScalarDB for DynamoDB](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#configure-scalardb-2) + +### Required configuration/steps + +DynamoDB is available for use in AWS by default. You do not need to set up anything manually to use it. + +### Optional configurations/steps + +#### Enable point-in-time recovery (Recommended in the production environment) + +You can enable PITR as a backup/restore method for DynamoDB. If you use [ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader) for creating schema, it enables the PITR feature for tables by default. Please refer to the official document for more details. + +* [Point-in-time recovery for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/PointInTimeRecovery.html) + +It is recommended since the point-in-time recovery feature automatically and continuously takes backups so that you can reduce downtime (pause duration) for backup operations. Please refer to the following document for more details on how to backup/restore Scalar product data. + +* [Backup restore guide for Scalar products](BackupRestoreGuide.mdx) + +#### Configure monitoring (Recommended in the production environment) + +You can configure the monitoring and logging of DynamoDB using its native feature. Please refer to the official document for more details. + +* [Monitoring and logging](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/monitoring.html) + +It is recommended since the metrics and logs help you to investigate some issues in the production environment when they happen. + +#### Use VPC endpoint (Recommended in the production environment) + +// Note that We have not yet tested this feature with Scalar products. +// TODO: We need to test this feature with Scalar products. + +* [Using Amazon VPC endpoints to access DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/vpc-endpoints-dynamodb.html) + +It is recommended since the private internal connections not via WAN can make a system more secure. + +#### Configure Read/Write Capacity (Optional based on your environment) + +You can configure the **Read/Write Capacity** of DynamoDB tables based on your requirements. Please refer to the official document for more details on Read/Write Capacity. + +* [Read/write capacity mode](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html) + +You can configure Read/Write Capacity using ScalarDB/DL Schema Loader when you create a table. Please refer to the following document for more details on how to configure Read/Write Capacity (RU) using ScalarDB/DL Schema Loader. + +* [ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader) + +## Amazon RDS for MySQL, PostgreSQL, Oracle, and SQL Server + +### Authentication method + +When you use RDS, you must set `JDBC_URL`, `USERNAME`, and `PASSWORD` in the ScalarDB/ScalarDL properties file as follows. + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=jdbc +``` + +Please refer to the following document for more details on the properties for RDS (JDBC databases). + +* [Configure ScalarDB for JDBC databases](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### Required configuration/steps + +#### Create an RDS database instance + +You must create an RDS database instance. Please refer to the official document for more details. + +* [Configuring an Amazon RDS DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_RDS_Configuring.html) + +### Optional configurations/steps + +#### Enable automated backups (Recommended in the production environment) + +You can enable automated backups. Please refer to the official document for more details. + +* [Working with backups](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html) + +It is recommended since the automated backups feature enables a point-in-time recovery feature. It can recover data to a specific point in time. It can reduce downtime (pause duration) for backup operations when you use multi databases under Scalar products. Please refer to the following document for more details on how to backup/restore the Scalar product data. + +* [Backup restore guide for Scalar products](BackupRestoreGuide.mdx) + +#### Configure monitoring (Recommended in the production environment) + +You can configure the monitoring and logging of RDS using its native feature. Please refer to the official documents for more details. + +* [Monitoring metrics in an Amazon RDS instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Monitoring.html) +* [Monitoring events, logs, and streams in an Amazon RDS DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Monitor_Logs_Events.html) + +It is recommended since the metrics and logs help you to investigate some issues in the production environment when they happen. + +#### Disable public access (Recommended in the production environment) + +Public access is disabled by default. You can access the RDS database instance from the Scalar product pods on your EKS cluster as follows. + +* Create the RDS database instance on the same VPC as your EKS cluster. +* Connect the VPC for the RDS and the VPC for the EKS cluster for the Scalar product deployment using [VPC peering](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html). (// TODO: We need to test this feature with Scalar products.) + +It is recommended since the private internal connections not via WAN can make a system more secure. + +## Amazon Aurora MySQL and Amazon Aurora PostgreSQL + +### Authentication method + +When you use Amazon Aurora, you must set `JDBC_URL`, `USERNAME`, and `PASSWORD` in the ScalarDB/ScalarDL properties file as follows. + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=jdbc +``` + +Please refer to the following document for more details on the properties for Amazon Aurora (JDBC databases). + +* [Configure ScalarDB for JDBC databases](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### Required configuration/steps + +#### Create an Amazon Aurora DB cluster + +You must create an Amazon Aurora DB cluster. Please refer to the official document for more details. + +* [Configuring your Amazon Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraSettingUp.html) + +### Optional configurations/steps + +#### Configure backup configurations (Optional based on your environment) + +Amazon Aurora automatically gets a backup by default. You do not need to enable the backup feature manually. + +If you want to change some backup configurations like the backup retention period and backup window, you can configure them. Please refer to the official document for more details. + +* [Backing up and restoring an Amazon Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/BackupRestoreAurora.html) + +Please refer to the following document for more details on how to backup/restore the Scalar product data. + +* [Backup restore guide for Scalar products](BackupRestoreGuide.mdx) + +#### Configure monitoring (Recommended in the production environment) + +You can configure the monitoring and logging of Amazon Aurora using its native feature. Please refer to the official documents for more details. + +* [Monitoring metrics in an Amazon Aurora cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/MonitoringAurora.html) +* [Monitoring events, logs, and streams in an Amazon Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_Monitor_Logs_Events.html) + +It is recommended since the metrics and logs help you to investigate some issues in the production environment when they happen. + +#### Disable public access (Recommended in the production environment) + +Public access is disabled by default. You can access the Amazon Aurora DB cluster from the Scalar product pods on your EKS cluster as follows. + +* Create the Amazon Aurora DB cluster on the same VPC as your EKS cluster. +* Connect the VPC for the Amazon Aurora DB cluster and the VPC for the EKS cluster for the Scalar product deployment using [VPC peering](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html). (// TODO: We need to test this feature with Scalar products.) + +It is recommended since the private internal connections not via WAN can make a system more secure. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabaseForAzure.mdx b/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabaseForAzure.mdx new file mode 100644 index 00000000..01ee90ad --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/SetupDatabaseForAzure.mdx @@ -0,0 +1,206 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Set up a database for ScalarDB/ScalarDL deployment on Azure + +This guide explains how to set up a database for ScalarDB/ScalarDL deployment on Azure. + +## Azure Cosmos DB for NoSQL + +### Authentication method + +When you use Cosmos DB for NoSQL, you must set `COSMOS_DB_URI` and `COSMOS_DB_KEY` in the ScalarDB/ScalarDL properties file as follows. + +```properties +scalar.db.contact_points= +scalar.db.password= +scalar.db.storage=cosmos +``` + +Please refer to the following document for more details on the properties for Cosmos DB for NoSQL. + +* [Configure ScalarDB for Cosmos DB for NoSQL](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### Required configuration/steps + +#### Create an Azure Cosmos DB account + +You must create an Azure Cosmos DB account with the NoSQL (core) API. You must set the **Capacity mode** as **Provisioned throughput** when you create it. Please refer to the official document for more details. + +* [Quickstart: Create an Azure Cosmos DB account, database, container, and items from the Azure portal](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal) + +#### Configure a default consistency configuration + +You must set the **Default consistency level** as **Strong**. Please refer to the official document for more details. + +* [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#config/ure-the-default-consistency-level) + +### Optional configurations/steps + +#### Configure backup configurations (Recommended in the production environment) + +You can configure **Backup modes** as **Continuous backup mode** for PITR. Please refer to the official document for more details. + +* [Backup modes](https://learn.microsoft.com/en-us/azure/cosmos-db/online-backup-and-restore#backup-modes) + +It is recommended since the continuous backup mode automatically and continuously gets backups so that we can reduce downtime (pause duration) for backup operations. Please refer to the following document for more details on how to backup/restore the Scalar product data. + +* [Backup restore guide for Scalar products](BackupRestoreGuide.mdx) + +#### Configure monitoring (Recommended in the production environment) + +You can configure the monitoring of Cosmos DB using its native feature. Please refer to the official document for more details. + +* [Monitor Azure Cosmos DB](https://learn.microsoft.com/en-us/azure/cosmos-db/monitor) + +It is recommended since the metrics and logs help you to investigate some issues in the production environment when they happen. + +#### Enable service endpoint (Recommended in the production environment) + +You can configure the Azure Cosmos DB account to allow access only from a specific subnet of a virtual network (VNet). Please refer to the official document for more details. + +* [Configure access to Azure Cosmos DB from virtual networks (VNet)](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-configure-vnet-service-endpoint) + +It is recommended since the private internal connections not via WAN can make a system more secure. + +#### Configure the Request Units (Optional based on your environment) + +You can configure the **Request Units** of Cosmos DB based on your requirements. Please refer to the official document for more details on the request units. + +* [Request Units in Azure Cosmos DB](https://learn.microsoft.com/en-us/azure/cosmos-db/request-units) + +You can configure Request Units using ScalarDB/DL Schema Loader when you create a table. Please refer to the following document for more details on how to configure Request Units (RU) using ScalarDB/DL Schema Loader. + +* [ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader) + +## Azure Database for MySQL + +### Authentication method + +When you use Azure Database for MySQL, you must set `JDBC_URL`, `USERNAME`, and `PASSWORD` in the ScalarDB/ScalarDL properties file as follows. + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=jdbc +``` + +Please refer to the following document for more details on the properties for Azure Database for MySQL (JDBC databases). + +* [Configure ScalarDB for JDBC databases](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### Required configuration/steps + +#### Create a database server + +You must create a database server. Please refer to the official document for more details. + +* [Quickstart: Use the Azure portal to create an Azure Database for MySQL Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/quickstart-create-server-portal) + +You can choose **Single Server** or **Flexible Server** for your deployment. However, Flexible Server is recommended in Azure. This document assumes that you use Flexible Server. Please refer to the official documents for more details on the deployment models. + +* [What is Azure Database for MySQL?](https://learn.microsoft.com/en-us/azure/mysql/single-server/overview#deployment-models) + +### Optional configurations/steps + +#### Configure backup configurations (Optional based on your environment) + +Azure Database for MySQL gets a backup by default. You do not need to enable the backup feature manually. + +If you want to change some backup configurations like the backup retention period, you can configure it. Please refer to the official document for more details. + +* [Backup and restore in Azure Database for MySQL Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/concepts-backup-restore) + +Please refer to the following document for more details on how to backup/restore the Scalar product data. + +* [Backup restore guide for Scalar products](BackupRestoreGuide.mdx) + +#### Configure monitoring (Recommended in the production environment) + +You can configure the monitoring of Azure Database for MySQL using its native feature. Please refer to the official document for more details. + +* [Monitor Azure Database for MySQL Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/concepts-monitoring) + +It is recommended since the metrics and logs help you to investigate some issues in the production environment when they happen. + +#### Disable public access (Recommended in the production environment) + +You can configure **Private access (VNet Integration)** as a **Connectivity method**. Please refer to the official document for more details. + +* [Connectivity and networking concepts for Azure Database for MySQL - Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/flexible-server/concepts-networking) + +You can access the database server from the Scalar product pods on your AKS cluster as follows. + +* Create the database server on the same VNet as your AKS cluster. +* Connect the VNet for the database server and the VNet for the AKS cluster for the Scalar product deployment using [Virtual network peering](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview). (// TODO: We need to test this feature with Scalar products.) + +It is recommended since the private internal connections not via WAN can make a system more secure. + +## Azure Database for PostgreSQL + +### Authentication method + +When you use Azure Database for PostgreSQL, you must set `JDBC_URL`, `USERNAME`, and `PASSWORD` in the ScalarDB/ScalarDL properties file as follows. + +```properties +scalar.db.contact_points= +scalar.db.username= +scalar.db.password= +scalar.db.storage=jdbc +``` + +Please refer to the following document for more details on the properties for Azure Database for PostgreSQL (JDBC databases). + +* [Configure ScalarDB for JDBC databases](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb#set-up-your-database-for-scalardb) + +### Required configuration/steps + +#### Create a database server + +You must create a database server. Please refer to the official document for more details. + +* [Quickstart: Create an Azure Database for PostgreSQL - Flexible Server in the Azure portal](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/quickstart-create-server-portal) + +You can choose **Single Server** or **Flexible Server** for your deployment. However, Flexible Server is recommended in Azure. This document assumes that you use Flexible Server. Please refer to the official documents for more details on the deployment models. + +* [What is Azure Database for PostgreSQL?](https://learn.microsoft.com/en-us/azure/postgresql/single-server/overview#deployment-models) + +### Optional configurations/steps + +#### Configure backup configurations (Optional based on your environment) + +Azure Database for PostgreSQL gets a backup by default. You do not need to enable the backup feature manually. + +If you want to change some backup configurations like the backup retention period, you can configure it. Please refer to the official document for more details. + +* [Backup and restore in Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-backup-restore) + +Please refer to the following document for more details on how to backup/restore the Scalar product data. + +* [Backup restore guide for Scalar products](BackupRestoreGuide.mdx) + +#### Configure monitoring (Recommended in the production environment) + +You can configure the monitoring of Azure Database for PostgreSQL using its native feature. Please refer to the official document for more details. + +* [Monitor metrics on Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-monitoring) + +It is recommended since the metrics and logs help you to investigate some issues in the production environment when they happen. + +#### Disable public access (Recommended in the production environment) + +You can configure **Private access (VNet Integration)** as a **Connectivity method**. Please refer to the official document for more details. + +* [Networking overview for Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-networking) + +You can access the database server from the Scalar product pods on your AKS cluster as follows. + +* Create the database server on the same VNet as your AKS cluster. +* Connect the VNet for the database server and the VNet for the AKS cluster for the Scalar product deployment using [Virtual network peering](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview). (// TODO: We need to test this feature with Scalar products.) + +It is recommended since the private internal connections not via WAN can make a system more secure. diff --git a/versioned_docs/version-3.15/scalar-kubernetes/alerts/Envoy.mdx b/versioned_docs/version-3.15/scalar-kubernetes/alerts/Envoy.mdx new file mode 100644 index 00000000..95183274 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/alerts/Envoy.mdx @@ -0,0 +1,153 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Envoy Alerts + +## EnvoyClusterDown + +This is the most critical alert and indicates that an Envoy cluster is not able to process requests. This alert should be handled with the highest priority. + +### Example Alert + +#### Firing + +``` +[FIRING:1] EnvoyClusterDown - critical +Alert: Envoy cluster is down - critical + Description: Envoy cluster is down, no resquest can be process + Details: + • alertname: EnvoyClusterDown + • deployment: prod-scalardl-envoy +``` + +#### Resolved + +``` +[RESOLVED] EnvoyClusterDown - critical +Alert: Envoy cluster is down - critical + Description: Envoy cluster is down, no resquest can be process + Details: + • alertname: EnvoyClusterDown + • deployment: prod-scalardl-envoy +``` + +### Action Needed + +* Check the number of replicas set `kubectl get deployments. prod-scalardl-envoy` +* Check the number of replicas set `kubectl describe deployments. prod-scalardl-envoy` +* Check nodes statuses with `kubectl get node -o wide` +* Check the log server to pinpoint the root cause of a failure with kubernetes logs on the monitor server `/log/kubernetes//-/kube.log` +* Check a cloud provider to see if there is any known issue. For example, you can check statues [here](https://status.azure.com/en-us/status) in Azure. + +## EnvoyClusterDegraded + +This alert lets you know if a kubernetes cluster cannot start envoy pods, which means that the cluster does not have enough resource or lost of one or many kubernetes nodes to run the deployment. + +### Example Alert + +#### Firing + +``` +[FIRING:1] EnvoyClusterDegraded - warning +Alert: Envoy cluster is running in a degraded mode - warning + Description: Envoy cluster is running in a degraded mode, some of the Envoy pods are not healthy + Details: + • alertname: EnvoyClusterDegraded + • deployment: prod-scalardl-envoy +``` + +#### Resolved + +``` +[RESOLVED] EnvoyClusterDegraded - warning +Alert: Envoy cluster is running in a degraded mode - warning + Description: Envoy cluster is running in a degraded mode, some of the Envoy pods are not healthy + Details: + • alertname: EnvoyClusterDegraded + • deployment: prod-scalardl-envoy +``` + +### Action Needed + +* Check the log server to pinpoint the root cause of a failure with kubernetes logs on the monitor server `/log/kubernetes//-/kube.log` or `kubectl logs prod-scalardl-envoy-xxxx-yyyy` +* Check kubernetes deployment with `kubectl describe deployments prod-scalardl-envoy` +* Check replica set with `kubectl get replicasets.apps` +* Check nodes statuses with `kubectl get node -o wide` +* Check a cloud provider to see if there is any known issue. For example, you can check statues [here](https://status.azure.com/en-us/status) in Azure. + +## EnvoyPodsPending + +This alert lets you know if a kubernetes cluster cannot start envoy pods, which means that the cluster does not have the enough resource. + +### Example Alert + +#### Firing + +``` +[FIRING:1] EnvoyPodsPending - warning +Alert: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default in pending status - warning + Description: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has been in pending status for more than 1 minute. + Details: + • alertname: EnvoyPodsPending + • deployment: prod-scalardl-envoy +``` + +#### Resolved + +``` +[RESOLVED:1] EnvoyPodsPending - warning +Alert: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default in pending status - warning + Description: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has been in pending status for more than 1 minute. + Details: + • alertname: EnvoyPodsPending + • deployment: prod-scalardl-envoy +``` + +### Action Needed + +* Check log server to pinpoint the root cause of a failure with kubernetes logs on the monitor server `/log/kube//*.log` +* Check a kubernetes deployment with `kubectl describe pod prod-scalardl-envoy-xxxx-yyyy` + +## EnvoyPodsError + +This alert lets you know if a kubernetes cluster cannot start envoy pods for one of the following reasons: + +* CrashLoopBackOff +* CreateContainerConfigError +* CreateContainerError +* ErrImagePull +* ImagePullBackOff +* InvalidImageName + +### Example Alert + +#### Firing + +``` +[FIRING:1] EnvoyPodsError - warning +Alert: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has an error status - warning + Description: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has been in pending status for more than 1 minutes. + Details: + • alertname: EnvoyPodsError + • deployment: prod-scalardl-envoy +``` + +#### Resolved + +``` +[RESOLVED:1] EnvoyPodsError - warning +Alert: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has an error status - warning + Description: Pod prod-scalardl-envoy-xxxx-yyyy in namespace default has been in pending status for more than 1 minutes. + Details: + • alertname: EnvoyPodsError + • deployment: prod-scalardl-envoy +``` + +### Action Needed + +* Check a kubernetes deployment with `kubectl describe pod prod-scalardl-envoy-xxxx-yyyy` +* Check the log server to pinpoint the root cause of a failure with kubernetes logs on the monitor server `/log/kubernetes//-/kube.log` diff --git a/versioned_docs/version-3.15/scalar-kubernetes/alerts/Ledger.mdx b/versioned_docs/version-3.15/scalar-kubernetes/alerts/Ledger.mdx new file mode 100644 index 00000000..2cefa7f0 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/alerts/Ledger.mdx @@ -0,0 +1,152 @@ +--- +tags: + - Enterprise +displayed_sidebar: docsEnglish +--- + +# Ledger Alerts + +## LedgerClusterDown + +This is the most critical alert and indicates that an Ledger cluster is not able to process requests. This alert should be handled with the highest priority. + +### Example Alert + +#### Firing + +``` +[FIRING:1] LedgerClusterDown - critical +Alert: Ledger cluster is down - critical + Description: Ledger cluster is down, no resquest can be process. + Details: + • alertname: LedgerClusterDown + • deployment: prod-scalardl-ledger +``` + +#### Resolved + +``` +[RESOLVED] LedgerClusterDown - critical +Alert: Ledger cluster is down - critical + Description: Ledger cluster is down, no resquest can be process. + Details: + • alertname: LedgerClusterDown + • deployment: prod-scalardl-ledger +``` + +### Action Needed + +* Check the number of replicas set `kubectl get deployments. prod-scalardl-ledger` +* Check the number of replicas set `kubectl describe deployments. prod-scalardl-ledger` +* Check nodes statuses with `kubectl get node -o wide` +* Check the log server to pinpoint the root cause of a failure with kubernetes logs on the monitor server `/log/kubernetes//-/kube.log` +* Check a cloud provider to see if there is any known issue. For example, you can check statues [here](https://status.azure.com/en-us/status) in Azure. + +## LedgerClusterDegraded + +This alert lets you know if a kubernetes cluster cannot start ledger pods, which means that the cluster does not have enough resource or lost of one or many kubernetes nodes to run the deployment. + +### Example Alert + +#### Firing + +``` +[FIRING:1] LedgerClusterDegraded - warning +Alert: Ledger cluster is running in a degraded mode - warning + Description: Ledger cluster is running in a degraded mode, some of the Ledger pods are not healthy. + Details: + • alertname: LedgerClusterDegraded + • deployment: prod-scalardl-ledger +``` + +#### Resolved + +``` +[RESOLVED] LedgerClusterDegraded - warning +Alert: Ledger cluster is running in a degraded mode - warning + Description: Ledger cluster is running in a degraded mode, some of the Ledger pods are not healthy. + Details: + • alertname: LedgerClusterDegraded + • deployment: prod-scalardl-ledger +``` + +### Action Needed + +* Check the log server to pinpoint the root cause of a failure with kubernetes logs on the monitor server `/log/kubernetes//-/kube.log` +* Check kubernetes deployment with `kubectl describe deployments prod-scalardl-ledger` +* Check replica set with `kubectl get replicasets.apps` +* Check nodes statuses with `kubectl get node -o wide` +* Check a cloud provider to see if there is any known issue. For example, you can check statues [here](https://status.azure.com/en-us/status) in Azure. + +## LedgerPodsPending + +This alert lets you know if a kubernetes cluster cannot start ledger pods, which means that the cluster does not have the enough resource. + +### Example Alert + +#### Firing + +``` +[FIRING:1] LedgerPodsPending - warning +Alert: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default in pending status - warning + Description: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has been in pending status for more than 1 minute. + Details: + • alertname: LedgerPodsPending + • deployment: prod-scalardl-ledger +``` + +#### Resolved + +``` +[RESOLVED:1] LedgerPodsPending - warning +Alert: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default in pending status - warning + Description: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has been in pending status for more than 1 minute. + Details: + • alertname: LedgerPodsPending + • deployment: prod-scalardl-ledger +``` + +### Action Needed + +* Check log server to pinpoint root cause of failure with the kubernetes logs on the monitor server `/log/kubernetes//-/kube.log` +* Check the kubernetes deployment with `kubectl describe pod prod-scalardl-ledger-xxxx-yyyy` + +## LedgerPodsError + +This alert lets you know if a kubernetes cluster cannot start ledger pods for one of the following reasons: + +* CrashLoopBackOff +* CreateContainerConfigError +* CreateContainerError +* ErrImagePull +* ImagePullBackOff +* InvalidImageName + +### Example Alert + +#### Firing + +``` +[FIRING:1] LedgerPodsError - warning +Alert: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has an error status - warning + Description: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has been in pending status for more than 1 minutes. + Details: + • alertname: LedgerPodsError + • deployment: prod-scalardl-ledger +``` + +#### Resolved + +``` +[RESOLVED:1] LedgerPodsError - warning +Alert: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has an error status - warning + Description: Pod prod-scalardl-ledger-xxxx-yyyy in namespace default has been in pending status for more than 1 minutes. + Details: + • alertname: LedgerPodsError + • deployment: prod-scalardl-ledger +``` + +### Action Needed + +* Check the kubernetes deployment with `kubectl describe pod prod-scalardl-ledger-xxxx-yyyy` +* Check log server to pinpoint root cause of failure with the kubernetes logs on the monitor server `/log/kubernetes//-/kube.log` diff --git a/versioned_docs/version-3.15/scalar-kubernetes/alerts/README.mdx b/versioned_docs/version-3.15/scalar-kubernetes/alerts/README.mdx new file mode 100644 index 00000000..6048b065 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-kubernetes/alerts/README.mdx @@ -0,0 +1,13 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Scalar Alerts + +This section covers the types of alerts and what actions need to be taken. + +* [Envoy Alerts](Envoy.mdx) +* [Ledger Alerts](Ledger.mdx) diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png new file mode 100644 index 00000000..5ceef088 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Indirect_Mode.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Indirect_Mode.drawio.png new file mode 100644 index 00000000..feef0d81 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Cluster_Indirect_Mode.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_In_Cluster.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_In_Cluster.drawio.png new file mode 100644 index 00000000..c6c9e06e Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_In_Cluster.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_Out_Cluster.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_Out_Cluster.drawio.png new file mode 100644 index 00000000..028fbe7c Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDB_Server_App_Out_Cluster.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Account.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Account.drawio.png new file mode 100644 index 00000000..76e1aa16 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Account.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Namespace.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Namespace.drawio.png new file mode 100644 index 00000000..026b4a2d Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_Namespace.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_VNet.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_VNet.drawio.png new file mode 100644 index 00000000..92eba96d Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Auditor_Multi_VNet.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Ledger.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Ledger.drawio.png new file mode 100644 index 00000000..9ee4fd22 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/AKS_ScalarDL_Ledger.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png new file mode 100644 index 00000000..00fef239 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Direct_Kubernetes_Mode.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Indirect_Mode.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Indirect_Mode.drawio.png new file mode 100644 index 00000000..db122e17 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Cluster_Indirect_Mode.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_In_Cluster.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_In_Cluster.drawio.png new file mode 100644 index 00000000..c49fbe4f Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_In_Cluster.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_Out_Cluster.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_Out_Cluster.drawio.png new file mode 100644 index 00000000..d8dcde16 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDB_Server_App_Out_Cluster.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Account.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Account.drawio.png new file mode 100644 index 00000000..1d9e7889 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Account.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Namespace.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Namespace.drawio.png new file mode 100644 index 00000000..bea249f3 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_Namespace.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_VPC.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_VPC.drawio.png new file mode 100644 index 00000000..30d5af46 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Auditor_Multi_VPC.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Ledger.drawio.png b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Ledger.drawio.png new file mode 100644 index 00000000..ce5fd7b5 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-kubernetes/images/png/EKS_ScalarDL_Ledger.drawio.png differ diff --git a/versioned_docs/version-3.15/scalar-licensing/index.mdx b/versioned_docs/version-3.15/scalar-licensing/index.mdx new file mode 100644 index 00000000..d6a813a6 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-licensing/index.mdx @@ -0,0 +1,65 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to Configure a Product License Key + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +To run Scalar products, you must create a `.properties` file and add your product license key and a certificate to the file. In your `.properties` file, copy one of the following configurations, based on the product you're using, and paste the contents in the `.properties` file, replacing `` with your license key. + +:::note + +If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). + +::: + +:::warning + +If you're using a trial license, ScalarDB must be connected to the Internet. An Internet connection is required to check if the trial license is valid and hasn't expired. + +::: + +## ScalarDB Enterprise Edition + + + + ```properties + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem=-----BEGIN CERTIFICATE-----\nMIICKzCCAdKgAwIBAgIIBXxj3s8NU+owCgYIKoZIzj0EAwIwbDELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMSMwIQYDVQQDExplbnRlcnByaXNlLnNjYWxhci1sYWJzLmNv\nbTAeFw0yMzExMTYwNzExNTdaFw0yNDAyMTUxMzE2NTdaMGwxCzAJBgNVBAYTAkpQ\nMQ4wDAYDVQQIEwVUb2t5bzERMA8GA1UEBxMIU2hpbmp1a3UxFTATBgNVBAoTDFNj\nYWxhciwgSW5jLjEjMCEGA1UEAxMaZW50ZXJwcmlzZS5zY2FsYXItbGFicy5jb20w\nWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATJx5gvAr+GZAHcBpUvDFDsUlFo4GNw\npRfsntzwStIP8ac3dew7HT4KbGBWei0BvIthleaqpv0AEP7JT6eYAkNvo14wXDAO\nBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG\nA1UdEwEB/wQCMAAwHQYDVR0OBBYEFMIe+XuuZcnDX1c3TmUPlu3kNv/wMAoGCCqG\nSM49BAMCA0cAMEQCIGGlqKpgv+KW+Z1ZkjfMHjSGeUZKBLwfMtErVyc9aTdIAiAy\nvsZyZP6Or9o40x3l3pw/BT7wvy93Jm0T4vtVQH6Zuw==\n-----END CERTIFICATE----- + ``` + + + ```properties + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem=-----BEGIN CERTIFICATE-----\nMIICKzCCAdKgAwIBAgIIBXxj3s8NU+owCgYIKoZIzj0EAwIwbDELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMSMwIQYDVQQDExplbnRlcnByaXNlLnNjYWxhci1sYWJzLmNv\nbTAeFw0yMzExMTYwNzExNTdaFw0yNDAyMTUxMzE2NTdaMGwxCzAJBgNVBAYTAkpQ\nMQ4wDAYDVQQIEwVUb2t5bzERMA8GA1UEBxMIU2hpbmp1a3UxFTATBgNVBAoTDFNj\nYWxhciwgSW5jLjEjMCEGA1UEAxMaZW50ZXJwcmlzZS5zY2FsYXItbGFicy5jb20w\nWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATJx5gvAr+GZAHcBpUvDFDsUlFo4GNw\npRfsntzwStIP8ac3dew7HT4KbGBWei0BvIthleaqpv0AEP7JT6eYAkNvo14wXDAO\nBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG\nA1UdEwEB/wQCMAAwHQYDVR0OBBYEFMIe+XuuZcnDX1c3TmUPlu3kNv/wMAoGCCqG\nSM49BAMCA0cAMEQCIGGlqKpgv+KW+Z1ZkjfMHjSGeUZKBLwfMtErVyc9aTdIAiAy\nvsZyZP6Or9o40x3l3pw/BT7wvy93Jm0T4vtVQH6Zuw==\n-----END CERTIFICATE----- + ``` + + + ```properties + scalar.db.cluster.node.licensing.license_key= + scalar.db.cluster.node.licensing.license_check_cert_pem=-----BEGIN CERTIFICATE-----\nMIICIzCCAcigAwIBAgIIKT9LIGX1TJQwCgYIKoZIzj0EAwIwZzELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMR4wHAYDVQQDExV0cmlhbC5zY2FsYXItbGFicy5jb20wHhcN\nMjMxMTE2MDcxMDM5WhcNMjQwMjE1MTMxNTM5WjBnMQswCQYDVQQGEwJKUDEOMAwG\nA1UECBMFVG9reW8xETAPBgNVBAcTCFNoaW5qdWt1MRUwEwYDVQQKEwxTY2FsYXIs\nIEluYy4xHjAcBgNVBAMTFXRyaWFsLnNjYWxhci1sYWJzLmNvbTBZMBMGByqGSM49\nAgEGCCqGSM49AwEHA0IABBSkIYAk7r5FRDf5qRQ7dbD3ib5g3fb643h4hqCtK+lC\nwM4AUr+PPRoquAy+Ey2sWEvYrWtl2ZjiYyyiZw8slGCjXjBcMA4GA1UdDwEB/wQE\nAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIw\nADAdBgNVHQ4EFgQUbFyOWFrsjkkOvjw6vK3gGUADGOcwCgYIKoZIzj0EAwIDSQAw\nRgIhAKwigOb74z9BdX1+dUpeVG8WrzLTIqdIU0w+9jhAueXoAiEA6cniJ3qsP4j7\nsck62kHnFpH1fCUOc/b/B8ZtfeXI2Iw=\n-----END CERTIFICATE----- + ``` + + + +## ScalarDB Analytics with Spark + + + + ```apacheconf + spark.sql.catalog.scalardb_catalog.license.key + spark.sql.catalog.scalardb_catalog.license.cert_pem -----BEGIN CERTIFICATE-----\nMIICKzCCAdKgAwIBAgIIBXxj3s8NU+owCgYIKoZIzj0EAwIwbDELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMSMwIQYDVQQDExplbnRlcnByaXNlLnNjYWxhci1sYWJzLmNv\nbTAeFw0yMzExMTYwNzExNTdaFw0yNDAyMTUxMzE2NTdaMGwxCzAJBgNVBAYTAkpQ\nMQ4wDAYDVQQIEwVUb2t5bzERMA8GA1UEBxMIU2hpbmp1a3UxFTATBgNVBAoTDFNj\nYWxhciwgSW5jLjEjMCEGA1UEAxMaZW50ZXJwcmlzZS5zY2FsYXItbGFicy5jb20w\nWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATJx5gvAr+GZAHcBpUvDFDsUlFo4GNw\npRfsntzwStIP8ac3dew7HT4KbGBWei0BvIthleaqpv0AEP7JT6eYAkNvo14wXDAO\nBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG\nA1UdEwEB/wQCMAAwHQYDVR0OBBYEFMIe+XuuZcnDX1c3TmUPlu3kNv/wMAoGCCqG\nSM49BAMCA0cAMEQCIGGlqKpgv+KW+Z1ZkjfMHjSGeUZKBLwfMtErVyc9aTdIAiAy\nvsZyZP6Or9o40x3l3pw/BT7wvy93Jm0T4vtVQH6Zuw==\n-----END CERTIFICATE----- + ``` + + + ```apacheconf + spark.sql.catalog.scalardb_catalog.license.key + spark.sql.catalog.scalardb_catalog.license.cert_pem -----BEGIN CERTIFICATE-----\nMIICIzCCAcigAwIBAgIIKT9LIGX1TJQwCgYIKoZIzj0EAwIwZzELMAkGA1UEBhMC\nSlAxDjAMBgNVBAgTBVRva3lvMREwDwYDVQQHEwhTaGluanVrdTEVMBMGA1UEChMM\nU2NhbGFyLCBJbmMuMR4wHAYDVQQDExV0cmlhbC5zY2FsYXItbGFicy5jb20wHhcN\nMjMxMTE2MDcxMDM5WhcNMjQwMjE1MTMxNTM5WjBnMQswCQYDVQQGEwJKUDEOMAwG\nA1UECBMFVG9reW8xETAPBgNVBAcTCFNoaW5qdWt1MRUwEwYDVQQKEwxTY2FsYXIs\nIEluYy4xHjAcBgNVBAMTFXRyaWFsLnNjYWxhci1sYWJzLmNvbTBZMBMGByqGSM49\nAgEGCCqGSM49AwEHA0IABBSkIYAk7r5FRDf5qRQ7dbD3ib5g3fb643h4hqCtK+lC\nwM4AUr+PPRoquAy+Ey2sWEvYrWtl2ZjiYyyiZw8slGCjXjBcMA4GA1UdDwEB/wQE\nAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIw\nADAdBgNVHQ4EFgQUbFyOWFrsjkkOvjw6vK3gGUADGOcwCgYIKoZIzj0EAwIDSQAw\nRgIhAKwigOb74z9BdX1+dUpeVG8WrzLTIqdIU0w+9jhAueXoAiEA6cniJ3qsP4j7\nsck62kHnFpH1fCUOc/b/B8ZtfeXI2Iw=\n-----END CERTIFICATE----- + ``` + + diff --git a/versioned_docs/version-3.15/scalar-manager/images/backup-and-restore-check-pauses.png b/versioned_docs/version-3.15/scalar-manager/images/backup-and-restore-check-pauses.png new file mode 100644 index 00000000..d4f63157 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-manager/images/backup-and-restore-check-pauses.png differ diff --git a/versioned_docs/version-3.15/scalar-manager/images/backup-and-restore-create-pauses.png b/versioned_docs/version-3.15/scalar-manager/images/backup-and-restore-create-pauses.png new file mode 100644 index 00000000..927f1910 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-manager/images/backup-and-restore-create-pauses.png differ diff --git a/versioned_docs/version-3.15/scalar-manager/images/dashboard-cluster.png b/versioned_docs/version-3.15/scalar-manager/images/dashboard-cluster.png new file mode 100644 index 00000000..cdc5c5ab Binary files /dev/null and b/versioned_docs/version-3.15/scalar-manager/images/dashboard-cluster.png differ diff --git a/versioned_docs/version-3.15/scalar-manager/images/dashboard-pod-list.png b/versioned_docs/version-3.15/scalar-manager/images/dashboard-pod-list.png new file mode 100644 index 00000000..ed247f0c Binary files /dev/null and b/versioned_docs/version-3.15/scalar-manager/images/dashboard-pod-list.png differ diff --git a/versioned_docs/version-3.15/scalar-manager/images/logs.png b/versioned_docs/version-3.15/scalar-manager/images/logs.png new file mode 100644 index 00000000..1127bd71 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-manager/images/logs.png differ diff --git a/versioned_docs/version-3.15/scalar-manager/images/metrics.png b/versioned_docs/version-3.15/scalar-manager/images/metrics.png new file mode 100644 index 00000000..e4f4d116 Binary files /dev/null and b/versioned_docs/version-3.15/scalar-manager/images/metrics.png differ diff --git a/versioned_docs/version-3.15/scalar-manager/images/metrics2.png b/versioned_docs/version-3.15/scalar-manager/images/metrics2.png new file mode 100644 index 00000000..6f76551b Binary files /dev/null and b/versioned_docs/version-3.15/scalar-manager/images/metrics2.png differ diff --git a/versioned_docs/version-3.15/scalar-manager/overview.mdx b/versioned_docs/version-3.15/scalar-manager/overview.mdx new file mode 100644 index 00000000..525b9306 --- /dev/null +++ b/versioned_docs/version-3.15/scalar-manager/overview.mdx @@ -0,0 +1,54 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# Scalar Manager Overview + +Scalar Manager is a centralized management and monitoring solution for ScalarDB within Kubernetes cluster environments. +It simplifies the operational tasks associated with these products by aggregating essential functionalities into a graphical user interface (GUI). + +## Why Scalar Manager? + +Before Scalar Manager was released, you would need to use various command-line tools and third-party solutions individually to manage and monitor ScalarDB deployments. +For example, `kubectl` is often used to check deployment status, the Prometheus stack for monitoring metrics, the Loki stack for log analysis, and Scalar's proprietary CLI tool for pausing ScalarDB to ensure transactional consistency between multiple databases. +This constellation of tools presented a steep learning curve and lacked a unified interface, resulting in inefficient workflows for performing routine management tasks or troubleshooting issues. + +Scalar Manager mitigates these pain points by aggregating essential functionalities into a single, user-friendly GUI. +With Scalar Manager, you can reduce the time and effort needed for management and monitoring, allowing you to focus on business development and operations. + +## Key features + +At its core, Scalar Manager provides the following features. + +### Centralized cluster visualization + +You can quickly gain real-time metrics about cluster health, pod logs, hardware usage, performance metrics like requests per second, and deep visibility into time-series data via the Grafana dashboards. + +![dashboard-cluster](images/dashboard-cluster.png) +![dashboard-pod-list](images/dashboard-pod-list.png) + +With the Grafana dashboards, you can also view pod logs and metrics in real-time or in time series. + +![logs](images/logs.png) +![metrics](images/metrics2.png) + +### Streamlined pausing job management + +You can execute or schedule pausing jobs to ensure transactional consistency, review and manage scheduled jobs, and monitor paused states within an intuitive GUI. + +![create-pauses](images/backup-and-restore-create-pauses.png) +![check-pauses](images/backup-and-restore-check-pauses.png) + +### User management + +Scalar Manager includes authentication capabilities, allowing for secure access control to your deployment. The system provides user management functionalities that enable administrators to create, modify, and remove user accounts through an intuitive interface. + +### Authentication and authorization + +By using the authorization feature, administrators can define and assign specific roles to users, controlling their access permissions within the Scalar Manager environment. This control ensures that users only have access to the functionalities relevant to their responsibilities. + +### Integrated authentication with Grafana + +Scalar Manager now offers seamless authentication integration between your Grafana instance and other components of the system. This single-sign-on capability eliminates the need for multiple authentication processes, streamlining the user experience and enhancing security by reducing credential management overhead. diff --git a/versioned_docs/version-3.15/scalardb-analytics-postgresql/getting-started.mdx b/versioned_docs/version-3.15/scalardb-analytics-postgresql/getting-started.mdx new file mode 100644 index 00000000..29e34ce5 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-analytics-postgresql/getting-started.mdx @@ -0,0 +1,98 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Analytics with PostgreSQL + +This document explains how to get started with ScalarDB Analytics with PostgreSQL. We assume that you have already installed ScalarDB Analytics with PostgreSQL and that all required services are running. If you don't have such an environment, please follow the instructions in [How to Install ScalarDB Analytics with PostgreSQL in Your Local Environment by Using Docker](./installation.mdx). Because ScalarDB Analytics with PostgreSQL executes queries via PostgreSQL, we also assume that you already have a `psql` client or another PostgreSQL client to send queries to PostgreSQL. + +## What is ScalarDB Analytics with PostgreSQL? + +ScalarDB, as a universal transaction manager, targets mainly transactional workloads and therefore supports limited subsets of relational queries. + +ScalarDB Analytics with PostgreSQL extends the functionality of ScalarDB to process analytical queries on ScalarDB-managed data by using PostgreSQL and its foreign data wrapper (FDW) extension. + +ScalarDB Analytics with PostgreSQL mainly consists of two components: PostgreSQL and Schema Importer. + +PostgreSQL runs as a service, accepting queries from users to process. FDW extensions are used to read data from the back-end storages that ScalarDB manages. Schema Importer is a tool to import the schema of the ScalarDB database into PostgreSQL so that users can see tables on the PostgreSQL side, which are identical to the tables on the ScalarDB side. + +## Set up a ScalarDB database + +First, you need one or more ScalarDB databases to run analytical queries with ScalarDB Analytics with PostgreSQL. If you have your own ScalarDB database, you can skip this section and use your database instead. If you use the [scalardb-samples/scalardb-analytics-postgresql-sample](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-analytics-postgresql-sample) project, you can set up a sample database by running the following command in the project directory. + +```console +docker compose run --rm schema-loader \ + -c /etc/scalardb.properties \ + --schema-file /etc/schema.json \ + --coordinator \ + --no-backup \ + --no-scaling +``` + +This command sets up [multiple storage instances](../multi-storage-transactions.mdx) that consist of DynamoDB, PostgreSQL, and Cassandra. Then, the command creates namespaces for `dynamons`, `postgresns`, and `cassandrans` that are mapped to those storages, creates tables for `dynamons.customer`, `postgresns.orders`, and `cassandrans.lineitem` by using [ScalarDB Schema Loader](https://scalardb.scalar-labs.com/docs/latest/schema-loader/). + +![Multi-storage overview](./images/multi-storage-overview.png) + +You can load sample data into the created tables by running the following command. + +```console +docker compose run --rm sample-data-loader +``` + +## Import the schemas from ScalarDB into PostgreSQL + +Next, let's import the schemas of the ScalarDB databases into PostgreSQL that processes analytical queries. ScalarDB Analytics with PostgreSQL provides a tool, Schema Importer, for this purpose. It'll get everything in place to run analytical queries for you. + +```console +docker compose run --rm schema-importer \ + import \ + --config /etc/scalardb.properties \ + --host analytics \ + --port 5432 \ + --database test \ + --user postgres \ + --password postgres \ + --namespace cassandrans \ + --namespace postgresns \ + --namespace dynamons \ + --config-on-postgres-host /etc/scalardb.properties +``` + +If you use your own ScalarDB database, you must replace the `--config` and `--config-on-postgres-host` options with your ScalarDB configuration file and the `--namespace` options with your ScalarDB namespaces to import. + +This creates tables (in precise, views) with the same names as the tables in the ScalarDB databases. In this example, the tables of `dynamons.customer`, `postgresns.orders`, and `cassandrans.lineitem` are created. The column definitions are also identical to the ScalarDB databases. These tables are [foreign tables](https://www.postgresql.org/docs/current/sql-createforeigntable.html) connected to the underlying storage of the ScalarDB databases using FDW. Therefore, you can equate those tables in PostgreSQL with the tables in the ScalarDB databases. + +![Imported schema](./images/imported-schema.png) + +## Run analytical queries + +Now, you have all tables to read the same data in the ScalarDB databases and can run any arbitrary analytical queries supported by PostgreSQL. To run queries, please connect to PostgreSQL with `psql` or other client. + +```console +psql -U postgres -h localhost test +Password for user postgres: + +> select c_mktsegment, count(*) from dynamons.customer group by c_mktsegment; + c_mktsegment | count +--------------+------- + AUTOMOBILE | 4 + BUILDING | 2 + FURNITURE | 1 + HOUSEHOLD | 2 + MACHINERY | 1 +(5 rows) +``` + +For details about the sample data and additional practical work, see the sample application page. + +## Caveats + +### Isolation level + +ScalarDB Analytics with PostgreSQL reads data with the **Read Committed** isolation level set. This isolation level ensures that the data you read has been committed in the past but does not guarantee that you can read consistent data at a particular point in time. + +### Write operations are not supported + +ScalarDB Analytics with PostgreSQL only supports read-only queries. `INSERT`, `UPDATE`, and other write operations are not supported. diff --git a/versioned_docs/version-3.15/scalardb-analytics-postgresql/images/imported-schema.png b/versioned_docs/version-3.15/scalardb-analytics-postgresql/images/imported-schema.png new file mode 100644 index 00000000..1cf8fea3 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-analytics-postgresql/images/imported-schema.png differ diff --git a/versioned_docs/version-3.15/scalardb-analytics-postgresql/images/multi-storage-overview.png b/versioned_docs/version-3.15/scalardb-analytics-postgresql/images/multi-storage-overview.png new file mode 100644 index 00000000..fc8df1cb Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-analytics-postgresql/images/multi-storage-overview.png differ diff --git a/versioned_docs/version-3.15/scalardb-analytics-postgresql/installation.mdx b/versioned_docs/version-3.15/scalardb-analytics-postgresql/installation.mdx new file mode 100644 index 00000000..ca3e82bf --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-analytics-postgresql/installation.mdx @@ -0,0 +1,61 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# How to Install ScalarDB Analytics with PostgreSQL in Your Local Environment by Using Docker + +This document explains how to set up a local environment that runs ScalarDB Analytics with PostgreSQL using the multi-storage back-end of Cassandra, PostgreSQL, and DynamoDB local server using [Docker Compose](https://docs.docker.com/compose/). + +## Prerequisites + +- [Docker Engine](https://docs.docker.com/engine/) and [Docker Compose](https://docs.docker.com/compose/). + +Follow the instructions on the Docker website according to your platform. + +## Step 1. Clone the `scalardb-samples` repository + +[scalardb-samples/scalardb-analytics-postgresql-sample](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-analytics-postgresql-sample) repository is a project containing a sample configuration to set up ScalarDB Analytics with PostgreSQL. + +Determine the location on your local machine where you want to run the scalardb-analytics-postgresql-sample app. Then, open Terminal, go to the location by using the `cd` command, and run the following commands: + +```console +git clone https://github.com/scalar-labs/scalardb-samples.git +cd scalardb-samples/scalardb-analytics-postgresql-sample +``` + +## Step 2. Start up the ScalarDB Analytics with PostgreSQL services + +The following command starts up the PostgreSQL instance that serves ScalarDB Analytics with PostgreSQL along with the back-end servers of Cassandra, PostgreSQL, and DynamoDB local in the Docker containers. When you first run the command, the required Docker images will be downloaded from the GitHub Container Registry. + +```console +docker-compose up +``` + +If you want to run the containers in the background, add the `-d` (--detach) option: + +```console +docker-compose up -d +``` + +If you already have your own ScalarDB database and want to use it as a back-end service, you can launch only the PostgreSQL instance without starting additional back-end servers in the container. + +```console +docker-compose up analytics +``` + +## Step 3. Run your analytical queries + +Now, you should have all the required services running. To run analytical queries, see [Getting Started with ScalarDB Analytics with PostgreSQL](./getting-started.mdx). + +## Step 4. Shut down the ScalarDB Analytics with PostgreSQL services + +To shut down the containers, do one of the following in Terminal, depending on how you: + +- If you started the containers in the foreground, press Ctrl+C where `docker-compose` is running. +- If you started the containers in the background, run the following command. + +```console +docker-compose down +``` diff --git a/versioned_docs/version-3.15/scalardb-analytics-postgresql/scalardb-fdw.mdx b/versioned_docs/version-3.15/scalardb-analytics-postgresql/scalardb-fdw.mdx new file mode 100644 index 00000000..d8583026 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-analytics-postgresql/scalardb-fdw.mdx @@ -0,0 +1,180 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# ScalarDB FDW + +ScalarDB FDW is a PostgreSQL extension that implements a foreign data wrapper (FDW) for [ScalarDB](https://www.scalar-labs.com/scalardb/). + +ScalarDB FDW uses the Java Native Interface to directly utilize ScalarDB as a library inside the FDW and read data from external databases via scan operations for ScalarDB. + +## Prerequisites + +You must have the following prerequisites set up in your environment. + +### JDK + +You must install a version of the Java Development Kit (JDK) that is compatible with ScalarDB. In addition, you must set the `JAVA_HOME` environment variable, which points to your JDK installation directory. + +Note that since these extensions use the Java Native Interface (JNI) internally, you must include the dynamic library of the Java virtual machine (JVM), such as `libjvm.so`, in the library search path. + +### PostgreSQL + +This extension supports PostgreSQL 13 or later. For details on how to install PostgreSQL, see the official documentation at [Server Administration](https://www.postgresql.org/docs/current/admin.html). + +## Build and installation + +You can build and install this extension by running the following command. + +```console +make install +``` + +### Common build errors + +This section describes some common build errors that you might encounter. + +#### ld: library not found for -ljvm + +Normally, the build script finds the path for `libjvm.so` and properly sets it as a library search path. However, if you encounter the error `ld: library not found for -ljvm`, please copy the `libjvm.so` file to the default library search path. For example: + +```console +ln -s //libjvm.so /usr/lib64/libjvm.so +``` + +## Usage + +This section provides a usage example and available options for FDW for ScalarDB. + +### Example + +The following example shows you how to install and create the necessary components, and then run a query by using the FDW extension. + +#### 1. Install the extension + +For details on how to install the extension, see the [Build and installation](#build-and-installation) section. + +#### 2. Create an extension + +To create an extension, run the following command: + +```sql +CREATE EXTENSION scalardb_fdw; +``` + +#### 3. Create a foreign server + +To create a foreign server, run the following command: + +```sql +CREATE SERVER scalardb FOREIGN DATA WRAPPER scalardb_fdw OPTIONS ( + config_file_path '/path/to/scalardb.properties' +); +``` + +#### 4. Create user mapping + +To create user mapping, run the following command: + +```sql +CREATE USER MAPPING FOR PUBLIC SERVER scalardb; +``` + +#### 5. Create a foreign table + +To create a foreign table, run the following command: + +```sql +CREATE FOREIGN TABLE sample_table ( + pk int, + ck1 int, + ck2 int, + boolean_col boolean, + bigint_col bigint, + float_col double precision, + double_col double precision, + text_col text, + blob_col bytea +) SERVER scalardb OPTIONS ( + namespace 'ns', + table_name 'sample_table' +); +``` + +#### 6. Run a query + +To run a query, run the following command: + +```sql +select * from sample_table; +``` + +### Available options + +You can set the following options for ScalarDB FDW objects. + +#### `CREATE SERVER` + +You can set the following options on a ScalarDB foreign server object: + +| Name | Required | Type | Description | +| ------------------ | -------- | -------- | --------------------------------------------------------------- | +| `config_file_path` | **Yes** | `string` | The path to the ScalarDB config file. | +| `max_heap_size` | No | `string` | The maximum heap size of JVM. The format is the same as `-Xmx`. | + +#### `CREATE USER MAPPING` + +Currently, no options exist for `CREATE USER MAPPING`. + +#### `CREATE FOREIGN SERVER` + +The following options can be set on a ScalarDB foreign table object: + +| Name | Required | Type | Description | +| ------------ | -------- | -------- | ---------------------------------------------------------------- | +| `namespace` | **Yes** | `string` | The name of the namespace of the table in the ScalarDB instance. | +| `table_name` | **Yes** | `string` | The name of the table in the ScalarDB instance. | + +### Data-type mapping + +| ScalarDB | PostgreSQL | +| -------- | ---------------- | +| BOOLEAN | boolean | +| INT | int | +| BIGINT | bigint | +| FLOAT | float | +| DOUBLE | double precision | +| TEXT | text | +| BLOB | bytea | + +## Testing + +This section describes how to test FDW for ScalarDB. + +### Set up a ScalarDB instance for testing + +Before testing FDW for ScalarDB, you must have a running ScalarDB instance that contains test data. You can set up the instance and load the test data by running the following commands: + +```console +./test/setup.sh +``` + +If you want to reset the instances, you can run the following command, then the above setup command again. + +```console +./test/cleanup.sh +``` + +### Run regression tests + +You can run regression tests by running the following command **after** you have installed the FDW extension. + +```console +make installcheck +``` + +## Limitations + +- This extension aims to enable analytical query processing on ScalarDB-managed databases. Therefore, this extension only supports reading data from ScalarDB. diff --git a/versioned_docs/version-3.15/scalardb-analytics-postgresql/schema-importer.mdx b/versioned_docs/version-3.15/scalardb-analytics-postgresql/schema-importer.mdx new file mode 100644 index 00000000..51457edc --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-analytics-postgresql/schema-importer.mdx @@ -0,0 +1,66 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# Schema Importer + +Schema Importer is a CLI tool for automatically configuring PostgreSQL. By using this tool, your PostgreSQL database can have identical database objects, such as namespaces and tables, as your ScalarDB instance. + +Schema Importer reads the ScalarDB configuration file, retrieves the schemas of the tables defined in ScalarDB, and creates the corresponding foreign data wrapper external tables and views in that order. For more information, refer to [Getting Started with ScalarDB Analytics with PostgreSQL](getting-started.mdx). + +## Build Schema Importer + +You can build Schema Importer by using [Gradle](https://gradle.org/). To build Schema Importer, run the following command: + +```console +./gradlew build +``` + +You may want to build a fat JAR file so that you can launch Schema Importer by using `java -jar`. To build the fat JAR, run the following command: + + ```console + ./gradlew shadowJar + ``` + +After you build the fat JAR, you can find the fat JAR file in the `app/build/libs/` directory. + +## Run Schema Importer + +To run Schema Importer by using the fat JAR file, run the following command: + +```console +java -jar +``` +Available options are as follows: + +| Name | Required | Description | Default | +| --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| `--config` | **Yes** | Path to the ScalarDB configuration file | | +| `--config-on-postgres-host` | No | Path to the ScalarDB configuration file on the PostgreSQL-running host | The same value as `--config` will be used. | +| `--namespace`, `-n` | **Yes** | Namespaces to import into the analytics instance. You can specify the `--namespace` option multiple times if you have two or more namespaces. | | +| `--host` | No | PostgreSQL host | localhost | +| `--port` | No | PostgreSQL port | 5432 | +| `--database` | No | PostgreSQL port | postgres | +| `--user` | No | PostgreSQL user | postgres | +| `--password` | No | PostgreSQL password | | +| `--debug` | No | Enable debug mode | | + + +## Test Schema Importer + +To test Schema Importer, run the following command: + +```console +./gradlew test +``` + +## Build a Docker image of Schema Importer + + +To build a Docker image of Schema Importer, run the following command, replacing `` with the tag version of Schema Importer that you want to use: + +```console +docker build -t ghcr.io/scalar-labs/scalardb-analytics-postgresql-schema-importer: -f ./app/Dockerfile . +``` diff --git a/versioned_docs/version-3.15/scalardb-analytics/README.mdx b/versioned_docs/version-3.15/scalardb-analytics/README.mdx new file mode 100644 index 00000000..fa416e71 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-analytics/README.mdx @@ -0,0 +1,20 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# ScalarDB Analytics + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +**ScalarDB Analytics** is the analytical component of ScalarDB. Similar to ScalarDB, it unifies diverse data sources - ranging from RDBMSs like PostgreSQL and MySQL to NoSQL databases such as Cassandra and DynamoDB - into a single logical database. While ScalarDB focuses on operational workloads with strong transactional consistency across multiple databases, ScalarDB Analytics is optimized for analytical workloads. It supports a wide range of queries, including complex joins, aggregations, and window functions. ScalarDB Analytics operates seamlessly on both ScalarDB-managed data sources and non-ScalarDB-managed ones, enabling advanced analytical queries across various datasets. + +The current version of ScalarDB Analytics leverages **Apache Spark** as its execution engine. It provides a unified view of ScalarDB-managed and non-ScalarDB-managed data sources by utilizing a Spark custom catalog. Using ScalarDB Analytics, you can treat tables from these data sources as native Spark tables. This allows you to execute arbitrary Spark SQL queries seamlessly. For example, you can join a table stored in Cassandra with a table in PostgreSQL to perform a cross-database analysis with ease. + + + +## Further reading + +* For tutorials on how to use ScalarDB Analytics by using a sample dataset and application, see [Getting Started with ScalarDB Analytics](../scalardb-samples/scalardb-analytics-spark-sample/README.mdx). +* For supported Spark and Scala versions, see [Version Compatibility of ScalarDB Analytics with Spark](./run-analytical-queries.mdx#version-compatibility) diff --git a/versioned_docs/version-3.15/scalardb-analytics/deployment.mdx b/versioned_docs/version-3.15/scalardb-analytics/deployment.mdx new file mode 100644 index 00000000..b1f5a54f --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-analytics/deployment.mdx @@ -0,0 +1,219 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# Deploy ScalarDB Analytics in Public Cloud Environments + +This guide explains how to deploy ScalarDB Analytics in a public cloud environment. ScalarDB Analytics currently uses Apache Spark as an execution engine and supports managed Spark services provided by public cloud providers, such as Amazon EMR and Databricks. + +## Supported managed Spark services and their application types + +ScalarDB Analytics supports the following managed Spark services and application types. + +| Public Cloud Service | Spark Driver | Spark Connect | JDBC | +| -------------------------- | ------------ | ------------- | ---- | +| Amazon EMR (EMR on EC2) | ✅ | ✅ | ❌ | +| Databricks | ✅ | ❌ | ✅ | + +## Configure and deploy + +Select your public cloud environment, and follow the instructions to set up and deploy ScalarDB Analytics. + + + + +

Use Amazon EMR

+ +You can use Amazon EMR (EMR on EC2) to run analytical queries through ScalarDB Analytics. For the basics to launch an EMR cluster, please refer to the [AWS EMR on EC2 documentation](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan.html). + +

ScalarDB Analytics configuration

+ +To enable ScalarDB Analytics, you need to add the following configuration to the Software setting when you launch an EMR cluster. Be sure to replace the content in the angle brackets: + +```json +[ + { + "Classification": "spark-defaults", + "Properties": { + "spark.jars.packages": "com.scalar-labs:scalardb-analytics-spark-all-_:", + "spark.sql.catalog.": "com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog", + "spark.sql.extensions": "com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions", + "spark.sql.catalog..license.cert_pem": "", + "spark.sql.catalog..license.key": "", + + // Add your data source configuration below + } + } +] +``` + +The following describes what you should change the content in the angle brackets to: + +- ``: The version of Spark. +- ``: The version of Scala used to build Spark. +- ``: The version of ScalarDB Analytics. +- ``: The name of the catalog. +- ``: The PEM encoded license certificate. +- ``: The license key. + +For more details, refer to [Set up ScalarDB Analytics in the Spark configuration](./run-analytical-queries.mdx#set-up-scalardb-analytics-in-the-spark-configuration). + +

Run analytical queries via the Spark driver

+ +After the EMR Spark cluster has launched, you can use ssh to connect to the primary node of the EMR cluster and run your Spark application. For details on how to create a Spark Driver application, refer to [Spark Driver application](./run-analytical-queries.mdx?spark-application-type=spark-driver-application#develop-a-spark-application). + +

Run analytical queries via Spark Connect

+ +You can use Spark Connect to run your Spark application remotely by using the EMR cluster that you launched. + +You first need to configure the Software setting in the same way as the [Spark Driver application](./run-analytical-queries.mdx?spark-application-type=spark-driver-application#develop-a-spark-application). You also need to set the following configuration to enable Spark Connect. + +
Allow inbound traffic for a Spark Connect server
+ +1. Create a security group to allow inbound traffic for a Spark Connect server. (Port 15001 is the default). +2. Allow the role of "Amazon EMR service role" to attach the security group to the primary node of the EMR cluster. +3. Add the security group to the primary node of the EMR cluster as "Additional security groups" when you launch the EMR cluster. + +
Launch the Spark Connect server via a bootstrap action
+ +1. Create a script file to launch the Spark Connect server as follows: + +```bash +#!/usr/bin/env bash + +set -eu -o pipefail + +cd /var/lib/spark + +sudo -u spark /usr/lib/spark/sbin/start-connect-server.sh --packages org.apache.spark:spark-connect_:,com.scalar-labs:scalardb-analytics-spark-all-_: +``` + +The following describes what you should change the content in the angle brackets to: + +- ``: The major and minor version of Scala that matches your Spark installation (such as 2.12 or 2.13) +- ``: The full version of Spark you are using (such as 3.5.3) +- ``: The major and minor version of Spark you are using (such as 3.5) +- ``: The version of ScalarDB Analytics + +2. Upload the script file to S3. +3. Allow the role of "EC2 instance profile for Amazon EMR" to access the uploaded script file in S3. +4. Add the uploaded script file to "Bootstrap actions" when you launch the EMR cluster. + +
Run analytical queries
+ +You can run your Spark application via Spark Connect from anywhere by using the remote URL of the Spark Connect server, which is `sc://:15001`. + +For details on how to create a Spark application by using Spark Connect, refer to [Spark Connect application](./run-analytical-queries.mdx?spark-application-type=spark-connect#develop-a-spark-application). + +
+ +

Use Databricks

+ +You can use Databricks to run analytical queries through ScalarDB Analytics. + +:::note + +Note that Databricks provides a modified version of Apache Spark, which works differently from the original Apache Spark. + +::: + +

Launch Databricks cluster

+ +ScalarDB Analytics works with all-purpose and jobs-compute clusters on Databricks. When you launch the cluster, you need to configure the cluster to enable ScalarDB Analytics as follows: + +1. Store the license certificate and license key in the cluster by using the Databricks CLI. + +```console +databricks secrets create-scope scalardb-analytics-secret # you can use any secret scope name +cat license_key.json | databricks secrets put-secret scalardb-analytics-secret license-key +cat license_cert.pem | databricks secrets put-secret scalardb-analytics-secret license-cert +``` + +:::note + +For details on how to install and use the Databricks CLI, refer to the [Databricks CLI documentation](https://docs.databricks.com/en/dev-tools/cli/index.html). + +::: + +2. Select "No isolation shared" for the cluster mode. (This is required. ScalarDB Analytics works only with this cluster mode.) +3. Select an appropriate Databricks runtime version that supports Spark 3.4 or later. +4. Configure "Advanced Options" > "Spark config" as follows, replacing `` with the name of the catalog that you want to use: + +``` +spark.sql.catalog. com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog +spark.sql.extensions com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions +spark.sql.catalog..license.key {{secrets/scalardb-analytics-secret/license-key}} +spark.sql.catalog..license.cert_pem {{secrets/scalardb-analytics-secret/license-pem}} +``` + +:::note + +You also need to configure the data source. For details, refer to [Set up ScalarDB Analytics in the Spark configuration](./run-analytical-queries.mdx#set-up-scalardb-analytics-in-the-spark-configuration). + +::: + +:::note + +If you specified different secret names in the previous step, be sure to replace the secret names in the configuration above. + +::: + +5. Add the library of ScalarDB Analytics to the launched cluster as a Maven dependency. For details on how to add the library, refer to the [Databricks cluster libraries documentation](https://docs.databricks.com/en/libraries/cluster-libraries.html). + +

Run analytical queries via the Spark Driver

+ +You can run your Spark application on the properly configured Databricks cluster with Databricks Notebook or Databricks Jobs to access the tables in ScalarDB Analytics. To run the Spark application, you can migrate your Pyspark, Scala, or Spark SQL application to Databricks Notebook, or use Databricks Jobs to run your Spark application. ScalarDB Analytics works with task types for Notebook, Python, JAR, and SQL. + +For more details on how to use Databricks Jobs, refer to the [Databricks Jobs documentation](https://docs.databricks.com/en/jobs/index.html) + +

Run analytical queries via the JDBC driver

+ +Databricks supports JDBC to run SQL jobs on the cluster. You can use this feature to run your Spark application in SQL with ScalarDB Analytics by configuring extra settings as follows: + +1. Download the ScalarDB Analytics library JAR file from the Maven repository. +2. Upload the JAR file to the Databricks workspace. +3. Add the JAR file to the cluster as a library, instead of the Maven dependency. +4. Create an init script as follows, replacing `` with the path to your JAR file in the Databricks workspace: + +```bash +#!/bin/bash + +# Target directories +TARGET_DIRECTORIES=("/databricks/jars" "/databricks/hive_metastore_jars") +JAR_PATH=" + +# Copy the JAR file to the target directories +for TARGET_DIR in "${TARGET_DIRECTORIES[@]}"; do + mkdir -p "$TARGET_DIR" + cp "$JAR_PATH" "$TARGET_DIR/" +done +``` + +5. Upload the init script to the Databricks workspace. +6. Add the init script to the cluster to "Advanced Options" > "Init scripts" when you launch the cluster. + +After the cluster is launched, you can get the JDBC URL of the cluster in the "Advanced Options" > "JDBC/ODBC" tab on the cluster details page. + +To connect to the Databricks cluster by using JDBC, you need to add the Databricks JDBC driver to your application dependencies. For example, if you are using Gradle, you can add the following dependency to your `build.gradle` file: + +```groovy +implementation("com.databricks:databricks-jdbc:0.9.6-oss") +``` + +Then, you can connect to the Databricks cluster by using JDBC with the JDBC URL (``), as is common with JDBC applications. + +```java +Class.forName("com.databricks.client.jdbc.Driver"); +String url = ""; +Connection conn = DriverManager.getConnection(url) +``` + +For more details on how to use JDBC with Databricks, refer to the [Databricks JDBC Driver documentation](https://docs.databricks.com/en/integrations/jdbc/index.html). + +
+
diff --git a/versioned_docs/version-3.15/scalardb-analytics/design.mdx b/versioned_docs/version-3.15/scalardb-analytics/design.mdx new file mode 100644 index 00000000..e1f99d07 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-analytics/design.mdx @@ -0,0 +1,391 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# ScalarDB Analytics Design + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +ScalarDB Analytics is the analytical component of ScalarDB. Similar to ScalarDB, it unifies diverse data sources—ranging from RDBMSs like PostgreSQL and MySQL to NoSQL databases like Cassandra and DynamoDB—into a single logical database. This enables you to perform analytical queries across multiple databases seamlessly. + +ScalarDB Analytics consists of two main components: a universal data catalog and a query engine: + +- **Universal data catalog.** The universal data catalog is a flexible metadata management system that handles multiple catalog spaces. Each catalog space provides an independent logical grouping of data sources and views, enabling organized management of diverse data environments. +- **Query engine.** The query engine executes queries against the universal data catalog. ScalarDB Analytics provides appropriate data connectors to interface with the underlying data sources. + +ScalarDB Analytics employs a decoupled architecture where the data catalog and query engine are separate components. This design allows for integration with various existing query engines through an extensible architecture. As a result, you can select different query engines to execute queries against the same data catalog based on your specific requirements. + +## Universal data catalog + +The universal data catalog is composed of several levels and is structured as follows: + +```mermaid +graph TD + C[Catalog] --> D[Data Source] + C[Catalog] --> D2[Data Source] + subgraph " " + D --> N[Namespace] + D --> N2[Namespace] + N --> T[Table] + N --> T2[Table] + T --> TC[Column] + T --> TC2[Column] + D2 + end + + C --> VN[View Namespace] + C --> VN2[View Namespace] + subgraph " " + VN --> V[View] + VN --> V2[View] + V --> VC[Column] + V --> VC2[Column] + VN2 + end +``` + +The following are definitions for those levels: + +- **Catalog** is a folder that contains all your data source information. For example, you might have one catalog called `analytics_catalog` for your analytics data and another called `operational_catalog` for your day-to-day operations. +- **Data source** represents each data source you connect to. For each data source, we store important information like: + - What kind of data source it is (PostgreSQL, Cassandra, etc.) + - How to connect to it (connection details and passwords) + - Special features the data source supports (like transactions) +- **Namespace** is like a subfolder within your data source that groups related tables together. In PostgreSQL these are called schemas, in Cassandra they're called keyspaces. You can have multiple levels of namespaces, similar to having folders within folders. +- **Table** is where your actual data lives. For each table, we keep track of: + - What columns it has + - What type of data each column can store + - Whether columns can be empty (null) +- **View namespace** is a special folder for views. Unlike regular namespaces that are tied to one data source, view namespaces can work with multiple data sources at once. +- **View** is like a virtual table that can: + - Show your data in a simpler way (like hiding technical columns in ScalarDB tables) + - Combine data from different sources using SQL queries + - Each view, like tables, has its own columns with specific types and rules about empty values. + +### Supported data types + +ScalarDB Analytics supports a wide range of data types across different data sources. The universal data catalog maps these data types to a common set of types to ensure compatibility and consistency across sources. The following list shows the supported data types in ScalarDB Analytics: + +- `BYTE` +- `SMALLINT` +- `INT` +- `BIGINT` +- `FLOAT` +- `DOUBLE` +- `DECIMAL` +- `TEXT` +- `BLOB` +- `BOOLEAN` +- `DATE` +- `TIME` +- `TIMESTAMP` +- `TIMESTAMPTZ` +- `DURATION` +- `INTERVAL` + +### Catalog information mappings by data source + +When registering a data source to ScalarDB Analytics, the catalog information of the data source, that is, namespaces, tables, and columns, are resolved and registered to the universal data catalog. To resolve the catalog information of the data source, a particular object on the data sources side are mapped to the universal data catalog object. This mapping is consists of two parts: catalog-level mappings and data-type mappings. In the following sections, we describe how ScalarDB Analytics maps the catalog level and data type from each data source into the universal data catalog. + +#### Catalog-level mappings + +The catalog-level mappings are the mappings of the namespace names, table names, and column names from the data sources to the universal data catalog. To see the catalog-level mappings in each data source, select a data source. + + + + The catalog information of ScalarDB is automatically resolved by ScalarDB Analytics. The catalog-level objects are mapped as follows: + + - The ScalarDB namespace is mapped to the namespace. Therefore, the namespace of the ScalarDB data source is always single level, consisting of only the namespace name. + - The ScalarDB table is mapped to the table. + - The ScalarDB column is mapped to the column. + + + + + The catalog information of PostgreSQL is automatically resolved by ScalarDB Analytics. The catalog-level objects are mapped as follows: + + - The PostgreSQL schema is mapped to the namespace. Therefore, the namespace of the PostgreSQL data source is always single level, consisting of only the schema name. + - Only user-defined schemas are mapped to namespaces. The following system schemas are ignored: + - `information_schema` + - `pg_catalog` + - The PostgreSQL table is mapped to the table. + - The PostgreSQL column is mapped to the column. + + + + The catalog information of MySQL is automatically resolved by ScalarDB Analytics. The catalog-level objects are mapped as follows: + + - The MySQL database is mapped to the namespace. Therefore, the namespace of the MySQL data source is always single level, consisting of only the database name. + - Only user-defined databases are mapped to namespaces. The following system databases are ignored: + - `mysql` + - `sys` + - `information_schema` + - `performance_schema` + - The MySQL table is mapped to the table. + - The MySQL column is mapped to the column. + + + + The catalog information of Oracle is automatically resolved by ScalarDB Analytics. The catalog-level objects are mapped as follows: + + - The Oracle schema is mapped to the namespace. Therefore, the namespace of the Oracle data source is always single level, consisting of only schema name. + - Only user-defined schemas are mapped to namespaces. The following system schemas are ignored: + - `ANONYMOUS` + - `APPQOSSYS` + - `AUDSYS` + - `CTXSYS` + - `DBSNMP` + - `DGPDB_INT` + - `DBSFWUSER` + - `DVF` + - `DVSYS` + - `GGSYS` + - `GSMADMIN_INTERNAL` + - `GSMCATUSER` + - `GSMROOTUSER` + - `GSMUSER` + - `LBACSYS` + - `MDSYS` + - `OJVMSYS` + - `ORDDATA` + - `ORDPLUGINS` + - `ORDSYS` + - `OUTLN` + - `REMOTE_SCHEDULER_AGENT` + - `SI_INFORMTN_SCHEMA` + - `SYS` + - `SYS$UMF` + - `SYSBACKUP` + - `SYSDG` + - `SYSKM` + - `SYSRAC` + - `SYSTEM` + - `WMSYS` + - `XDB` + - `DIP` + - `MDDATA` + - `ORACLE_OCM` + - `XS$NULL` + + + + The catalog information of SQL Server is automatically resolved by ScalarDB Analytics. The catalog-level objects are mapped as follows: + + - The SQL Server database and schema are mapped to the namespace together. Therefore, the namespace of the SQL Server data source is always two-level, consisting of the database name and the schema name. + - Only user-defined databases are mapped to namespaces. The following system databases are ignored: + - `sys` + - `guest` + - `INFORMATION_SCHEMA` + - `db_accessadmin` + - `db_backupoperator` + - `db_datareader` + - `db_datawriter` + - `db_ddladmin` + - `db_denydatareader` + - `db_denydatawriter` + - `db_owner` + - `db_securityadmin` + - Only user-defined schemas are mapped to namespaces. The following system schemas are ignored: + - `master` + - `model` + - `msdb` + - `tempdb` + - The SQL Server table is mapped to the table. + - The SQL Server column is mapped to the column. + + + + Since DynamoDB is schema-less, you need to specify the catalog information explicitly when registering a DynamoDB data source by using the following format JSON: + + ```json + { + "namespaces": [ + { + "name": "", + "tables": [ + { + "name": "", + "columns": [ + { + "name": "", + "type": "" + }, + ... + ] + }, + ... + ] + }, + ... + ] + } + ``` + + In the specified JSON, you can use any arbitrary namespace names, but the table names must match the table names in DynamoDB and column name and type must match field names and types in DynamoDB. + + + + +#### Data-type mappings + +The native data types of the underlying data sources are mapped to the data types in ScalarDB Analytics. To see the data-type mappings in each data source, select a data source. + + + + | **ScalarDB Data Type** | **ScalarDB Analytics Data Type** | + |:------------------------------|:---------------------------------| + | `BOOLEAN` | `BOOLEAN` | + | `INT` | `INT` | + | `BIGINT` | `BIGINT` | + | `FLOAT` | `FLOAT` | + | `DOUBLE` | `DOUBLE` | + | `TEXT` | `TEXT` | + | `BLOB` | `BLOB` | + | `DATE` | `DATE` | + | `TIME` | `TIME` | + | `TIMESTAMP` | `TIMESTAMP` | + | `TIMESTAMPTZ` | `TIMESTAMPTZ` | + + + | **PostgreSQL Data Type** | **ScalarDB Analytics Data Type** | + |:------------------------------|:---------------------------------| + | `integer` | `INT` | + | `bigint` | `BIGINT` | + | `real` | `FLOAT` | + | `double precision` | `DOUBLE` | + | `smallserial` | `SMALLINT` | + | `serial` | `INT` | + | `bigserial` | `BIGINT` | + | `char` | `TEXT` | + | `varchar` | `TEXT` | + | `text` | `TEXT` | + | `bpchar` | `TEXT` | + | `boolean` | `BOOLEAN` | + | `bytea` | `BLOB` | + | `date` | `DATE` | + | `time` | `TIME` | + | `time with time zone` | `TIME` | + | `time without time zone` | `TIME` | + | `timestamp` | `TIMESTAMP` | + | `timestamp with time zone` | `TIMESTAMPTZ` | + | `timestamp without time zone` | `TIMESTAMP` | + + + | **MySQL Data Type** | **ScalarDB Analytics Data Type** | + |:-----------------------|:---------------------------------| + | `bit` | `BOOLEAN` | + | `bit(1)` | `BOOLEAN` | + | `bit(x)` if *x >= 2* | `BLOB` | + | `tinyint` | `SMALLINT` | + | `tinyint(1)` | `BOOLEAN` | + | `boolean` | `BOOLEAN` | + | `smallint` | `SMALLINT` | + | `smallint unsigned` | `INT` | + | `mediumint` | `INT` | + | `mediumint unsigned` | `INT` | + | `int` | `INT` | + | `int unsigned` | `BIGINT` | + | `bigint` | `BIGINT` | + | `float` | `FLOAT` | + | `double` | `DOUBLE` | + | `real` | `DOUBLE` | + | `char` | `TEXT` | + | `varchar` | `TEXT` | + | `text` | `TEXT` | + | `binary` | `BLOB` | + | `varbinary` | `BLOB` | + | `blob` | `BLOB` | + | `date` | `DATE` | + | `time` | `TIME` | + | `datetime` | `TIMESTAMP` | + | `timestamp` | `TIMESTAMPTZ` | + + + | **Oracle Data Type** | **ScalarDB Analytics Data Type** | + |:-----------------------------------|:---------------------------------| + | `NUMBER` if *scale = 0* | `BIGINT` | + | `NUMBER` if *scale > 0* | `DOUBLE` | + | `FLOAT` if *precision ≤ 53* | `DOUBLE` | + | `BINARY_FLOAT` | `FLOAT` | + | `BINARY_DOUBLE` | `DOUBLE` | + | `CHAR` | `TEXT` | + | `NCHAR` | `TEXT` | + | `VARCHAR2` | `TEXT` | + | `NVARCHAR2` | `TEXT` | + | `CLOB` | `TEXT` | + | `NCLOB` | `TEXT` | + | `BLOB` | `BLOB` | + | `BOOLEAN` | `BOOLEAN` | + | `DATE` | `DATE` | + | `TIMESTAMP` | `TIMESTAMPTZ` | + | `TIMESTAMP WITH TIME ZONE` | `TIMESTAMPTZ` | + | `TIMESTAMP WITH LOCAL TIME ZONE` | `TIMESTAMP` | + | `RAW` | `BLOB` | + + + | **SQL Server Data Type** | **ScalarDB Analytics Data Type** | + |:---------------------------|:---------------------------------| + | `bit` | `BOOLEAN` | + | `tinyint` | `SMALLINT` | + | `smallint` | `SMALLINT` | + | `int` | `INT` | + | `bigint` | `BIGINT` | + | `real` | `FLOAT` | + | `float` | `DOUBLE` | + | `float(n)` if *n ≤ 24* | `FLOAT` | + | `float(n)` if *n ≥ 25* | `DOUBLE` | + | `binary` | `BLOB` | + | `varbinary` | `BLOB` | + | `char` | `TEXT` | + | `varchar` | `TEXT` | + | `nchar` | `TEXT` | + | `nvarchar` | `TEXT` | + | `ntext` | `TEXT` | + | `text` | `TEXT` | + | `date` | `DATE` | + | `time` | `TIME` | + | `datetime` | `TIMESTAMP` | + | `datetime2` | `TIMESTAMP` | + | `smalldatetime` | `TIMESTAMP` | + | `datetimeoffset` | `TIMESTAMPTZ` | + + + | **DynamoDB Data Type** | **ScalarDB Analytics Data Type** | + |:-------------------------|:---------------------------------| + | `Number` | `BYTE` | + | `Number` | `SMALLINT` | + | `Number` | `INT` | + | `Number` | `BIGINT` | + | `Number` | `FLOAT` | + | `Number` | `DOUBLE` | + | `Number` | `DECIMAL` | + | `String` | `TEXT` | + | `Binary` | `BLOB` | + | `Boolean` | `BOOLEAN` | + +:::warning + +It is important to ensure that the field values of `Number` types are parsable as a specified data type for ScalarDB Analytics. For example, if a column that corresponds to a `Number`-type field is specified as an `INT` type, its value must be an integer. If the value is not an integer, an error will occur when running a query. + +::: + + + + +## Query engine + +A query engine is an independent component along with the universal data catalog, which is responsible for executing queries against the data sources registered in the universal data catalog and returning the results to the user. ScalarDB Analytics does not currently provide a built-in query engine. Instead, it is designed to be integrated with existing query engines, normally provided as a plugin of the query engine. + +When you run a query, the ScalarDB Analytics query engine plugin works as follows: + +1. Fetches the catalog metadata by calling the universal data catalog API, like the data source location, the table object identifier, and the table schema. +2. Sets up the data source connectors to the data sources by using the catalog metadata. +3. Provides the query optimization information to the query engine based on the catalog metadata. +4. Reads the data from the data sources by using the data source connectors. + +ScalarDB Analytics manages these processes internally. You can simply run a query against the universal data catalog by using the query engine API in the same way that you would normally run a query. + +ScalarDB Analytics currently supports Apache Spark as its query engine. For details on how to use ScalarDB Analytics with Spark, see [Run Analytical Queries Through ScalarDB Analytics](./run-analytical-queries.mdx). diff --git a/versioned_docs/version-3.15/scalardb-analytics/run-analytical-queries.mdx b/versioned_docs/version-3.15/scalardb-analytics/run-analytical-queries.mdx new file mode 100644 index 00000000..d13b86cc --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-analytics/run-analytical-queries.mdx @@ -0,0 +1,454 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# Run Analytical Queries Through ScalarDB Analytics + +This guide explains how to develop ScalarDB Analytics applications. For details on the architecture and design, see [ScalarDB Analytics Design](./design.mdx) + +ScalarDB Analytics currently uses Spark as an execution engine and provides a Spark custom catalog plugin to provide a unified view of ScalarDB-managed and non-ScalarDB-managed data sources as Spark tables. This allows you to execute arbitrary Spark SQL queries seamlessly. + +## Preparation + +This section describes the prerequisites, setting up ScalarDB Analytics in the Spark configuration, and adding the ScalarDB Analytics dependency. + +### Prerequisites + +ScalarDB Analytics works with Apache Spark 3.4 or later. If you don't have Spark installed yet, please download the Spark distribution from [Apache's website](https://spark.apache.org/downloads.html). + +:::note + +Apache Spark are built with either Scala 2.12 or Scala 2.13. ScalarDB Analytics supports both versions. You need to be sure which version you are using so that you can select the correct version of ScalarDB Analytics later. You can refer to [Version Compatibility](#version-compatibility) for more details. + +::: + +### Set up ScalarDB Analytics in the Spark configuration + +The following sections describe all available configuration options for ScalarDB Analytics. These configurations control: + +- How ScalarDB Analytics integrates with Spark +- How data sources are connected and accessed +- How license information is provided + +For example configurations in a practical scenario, see [the sample application configuration](../scalardb-samples/scalardb-analytics-spark-sample/README.mdx#scalardb-analytics-configuration). + +#### Spark plugin configurations + +| Configuration Key | Required | Description | +|:-----------------|:---------|:------------| +| `spark.jars.packages` | No | A comma-separated list of Maven coordinates for the required dependencies. User need to include the ScalarDB Analytics package you are using, otherwise, specify it as the command line argument when running the Spark application. For details about the Maven coordinates of ScalarDB Analytics, refer to [Add ScalarDB Analytics dependency](#add-the-scalardb-analytics-dependency). | +| `spark.sql.extensions` | Yes | Must be set to `com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions`. | +| `spark.sql.catalog.` | Yes | Must be set to `com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog`. | + +You can specify any name for ``. Be sure to use the same catalog name throughout your configuration. + +#### License configurations + +| Configuration Key | Required | Description | +| :--------------------------------------------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------- | +| `spark.sql.catalog..license.key` | Yes | JSON string of the license key for ScalarDB Analytics | +| `spark.sql.catalog..license.cert_pem` | Yes | A string of PEM-encoded certificate of ScalarDB Analytics license. Either `cert_pem` or `cert_path` must be set. | +| `spark.sql.catalog..license.cert_path` | Yes | A path to the PEM-encoded certificate of ScalarDB Analytics license. Either `cert_pem` or `cert_path` must be set. | + +#### Data source configurations + +ScalarDB Analytics supports multiple types of data sources. Each type requires specific configuration parameters: + + + + +:::note + +ScalarDB Analytics supports ScalarDB as a data source. This table describes how to configure ScalarDB as a data source. + +::: + +| Configuration Key | Required | Description | +| :---------------------------------------------------------------------------- | :------- | :---------------------------------------------- | +| `spark.sql.catalog..data_source..type` | Yes | Always set to `scalardb` | +| `spark.sql.catalog..data_source..config_path` | Yes | The path to the configuration file for ScalarDB | + +:::tip + +You can use an arbitrary name for ``. + +::: + + + + +| Configuration Key | Required | Description | +| :------------------------------------------------------------------------- | :------- | :------------------------------------- | +| `spark.sql.catalog..data_source..type` | Yes | Always set to `mysql` | +| `spark.sql.catalog..data_source..host` | Yes | The host name of the MySQL server | +| `spark.sql.catalog..data_source..port` | Yes | The port number of the MySQL server | +| `spark.sql.catalog..data_source..username` | Yes | The username of the MySQL server | +| `spark.sql.catalog..data_source..password` | Yes | The password of the MySQL server | +| `spark.sql.catalog..data_source..database` | No | The name of the database to connect to | + +:::tip + +You can use an arbitrary name for ``. + +::: + + + + +| Configuration Key | Required | Description | +| :------------------------------------------------------------------------- | :------- | :--------------------------------------- | +| `spark.sql.catalog..data_source..type` | Yes | Always set to `postgresql` or `postgres` | +| `spark.sql.catalog..data_source..host` | Yes | The host name of the PostgreSQL server | +| `spark.sql.catalog..data_source..port` | Yes | The port number of the PostgreSQL server | +| `spark.sql.catalog..data_source..username` | Yes | The username of the PostgreSQL server | +| `spark.sql.catalog..data_source..password` | Yes | The password of the PostgreSQL server | +| `spark.sql.catalog..data_source..database` | Yes | The name of the database to connect to | + +:::tip + +You can use an arbitrary name for ``. + +::: + + + + +| Configuration Key | Required | Description | +| :----------------------------------------------------------------------------- | :------- | :------------------------------------ | +| `spark.sql.catalog..data_source..type` | Yes | Always set to `oracle` | +| `spark.sql.catalog..data_source..host` | Yes | The host name of the Oracle server | +| `spark.sql.catalog..data_source..port` | Yes | The port number of the Oracle server | +| `spark.sql.catalog..data_source..username` | Yes | The username of the Oracle server | +| `spark.sql.catalog..data_source..password` | Yes | The password of the Oracle server | +| `spark.sql.catalog..data_source..service_name` | Yes | The service name of the Oracle server | + +:::tip + +You can use an arbitrary name for ``. + +::: + + + + +| Configuration Key | Required | Description | +| :------------------------------------------------------------------------- | :------- | :----------------------------------------------------------------------------------------------------- | +| `spark.sql.catalog..data_source..type` | Yes | Always set to `sqlserver` or `mssql` | +| `spark.sql.catalog..data_source..host` | Yes | The host name of the SQL Server server | +| `spark.sql.catalog..data_source..port` | Yes | The port number of the SQL Server server | +| `spark.sql.catalog..data_source..username` | Yes | The username of the SQL Server server | +| `spark.sql.catalog..data_source..password` | Yes | The password of the SQL Server server | +| `spark.sql.catalog..data_source..database` | No | The name of the database to connect to | +| `spark.sql.catalog..data_source..secure` | No | Whether to use a secure connection to the SQL Server server. Set to `true` to use a secure connection. | + +:::tip + +You can use an arbitrary name for ``. + +::: + + + + +| Configuration Key | Required | Description | +|:---------------------------------------------------------------------------|:------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `spark.sql.catalog..data_source..type` | Yes | Always set to `dynamodb` | +| `spark.sql.catalog..data_source..region` | Either `region` or `endpoint` must be set | The AWS region of the DynamoDB instance | +| `spark.sql.catalog..data_source..endpoint` | Either `region` or `endpoint` must be set | The AWS endpoint of the DynamoDB instance | +| `spark.sql.catalog..data_source..schema` | Yes | A JSON object representing the schema of the catalog. For details on the format, see [Catalog-level mappings](./design.mdx#catalog-level-mappings). | + + +:::tip + +You can use an arbitrary name for ``. + +::: + + + + +#### Example configuration + +Below is an example configuration for ScalarDB Analytics that demonstrates how to set up a catalog named `scalardb` with multiple data sources: + +```conf +# Spark plugin configurations +spark.jars.packages com.scalar-labs:scalardb-analytics-spark-all-_: +spark.sql.extensions com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions +spark.sql.catalog.scalardb com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog + +# License configurations +spark.sql.catalog.scalardb.license.key +spark.sql.catalog.scalardb.license.cert_pem + +# Data source configurations +spark.sql.catalog.scalardb.data_source.scalardb.type scalardb +spark.sql.catalog.scalardb.data_source.scalardb.config_path /path/to/scalardb.properties + +spark.sql.catalog.scalardb.data_source.mysql_source.type mysql +spark.sql.catalog.scalardb.data_source.mysql_source.host localhost +spark.sql.catalog.scalardb.data_source.mysql_source.port 3306 +spark.sql.catalog.scalardb.data_source.mysql_source.username root +spark.sql.catalog.scalardb.data_source.mysql_source.password password +spark.sql.catalog.scalardb.data_source.mysql_source.database mydb +``` + +The following describes what you should change the content in the angle brackets to: + +- ``: The license key for ScalarDB Analytics +- ``: The PEM-encoded certificate of ScalarDB Analytics license +- ``: The major and minor version of Spark you are using (such as 3.4) +- ``: The major and minor version of Scala that matches your Spark installation (such as 2.12 or 2.13) +- ``: The version of ScalarDB Analytics + +### Add the ScalarDB Analytics dependency + +ScalarDB Analytics is hosted in the Maven Central Repository. The name of the package is `scalardb-analytics-spark-all-_:`, where: + +- ``: The major and minor version of Spark you are using (such as 3.4) +- ``: The major and minor version of Scala that matches your Spark installation (such as 2.12 or 2.13) +- ``: The version of ScalarDB Analytics + +For details about version compatibility, refer to [Version Compatibility](#version-compatibility). + +You can add this dependency to your project by configuring the build settings of your project. For example, if you are using Gradle, you can add the following to your `build.gradle` file: + +```groovy +dependencies { + implementation 'com.scalar-labs:scalardb-analytics-spark-all-_:' +} +``` + +:::note + +If you want bundle your application in a single fat JAR file by using plugins like Gradle Shadow plugin or Maven Shade plugin, you need to exclude ScalarDB Analytics from the fat JAR file by choosing the appropriate configuration, such as `provided` or `shadow`, depending on the plugin you are using. + +::: + +## Develop a Spark application + +In this section, you will learn how to develop a Spark application that uses ScalarDB Analytics in Java. + +There are three ways to develop Spark applications with ScalarDB Analytics: + +1. **Spark driver application**: A traditional Spark application that runs within the cluster +2. **Spark Connect application**: A remote application that uses the Spark Connect protocol +3. **JDBC application**: A remote application that uses the JDBC interface + +:::note + +Depending on your environment, you may not be able to use all the methods mentioned above. For details about supported features and deployment options, refer to [Supported managed Spark services and their application types](./deployment.mdx#supported-managed-spark-services-and-their-application-types). + +::: + +With all these methods, you can refer to tables in ScalarDB Analytics using the same table identifier format. For details about how ScalarDB Analytics maps catalog information from data sources, refer to [Catalog information mappings by data source](./design.mdx#catalog-information-mappings-by-data-source). + + + + +You can use a commonly used `SparkSession` class for ScalarDB Analytics. Additionally, you can use any type of cluster deployment that Spark supports, such as YARN, Kubernetes, standalone, or local mode. + +To read data from tables in ScalarDB Analytics, you can use the `spark.sql` or `spark.read.table` function in the same way as when reading a normal Spark table. + +First, you need to set up your Java project. For example, if you are using Gradle, you can add the following to your `build.gradle` file: + +```groovy +dependencies { + implementation 'com.scalar-labs:scalardb-analytics-spark-_:' +} +``` + +Below is an example of a Spark Driver application: + +```java +import org.apache.spark.sql.SparkSession; + +public class MyApp { + public static void main(String[] args) { + // Create a SparkSession + try (SparkSession spark = SparkSession.builder().getOrCreate()) { + // Read data from a table in ScalarDB Analytics + spark.sql("SELECT * FROM my_catalog.my_data_source.my_namespace.my_table").show(); + } + } +} +``` + +Then, you can build and run your application by using the `spark-submit` command. + +:::note + +You may need to build a fat JAR file for your application, as is usual for normal Spark applications. + +::: + +```console +spark-submit --class MyApp --master local[*] my-spark-application-all.jar +``` + +:::tip + +You can also use other CLI tools that Spark provides, such as `spark-sql` and `spark-shell`, to interact with ScalarDB Analytics tables. + +::: + + + + +You can use [Spark Connect](https://spark.apache.org/spark-connect/) to interact with ScalarDB Analytics. By using Spark Connect, you can access a remote Spark cluster and read data in the same way as a Spark Driver application. The following briefly describes how to use Spark Connect. + +First, you need to start a Spark Connect server in the remote Spark cluster by running the following command: + +```console +./sbin/start-connect-server.sh --packages org.apache.spark:spark-connect_:,com.scalar-labs:scalardb-analytics-spark-all-_: +``` + +The following describes what you should change the content in the angle brackets to: + +- ``: The major and minor version of Scala that matches your Spark installation (such as 2.12 or 2.13) +- ``: The full version of Spark you are using (such as 3.5.3) +- ``: The major and minor version of Spark you are using (such as 3.5) +- ``: The version of ScalarDB Analytics + +:::note + +The versions of the packages must match the versions of Spark and ScalarDB Analytics that you are using. + +::: + +You also need to include the Spark Connect client package in your application. For example, if you are using Gradle, you can add the following to your `build.gradle` file: + +```kotlin +implementation("org.apache.spark:spark-connect-client-jvm_2.12:3.5.3") +``` + +Then, you can write a Spark Connect client application to connect to the server and read data. + +```java +import org.apache.spark.sql.SparkSession; + +public class MyApp { + public static void main(String[] args) { + try (SparkSession spark = SparkSession.builder() + .remote("sc://:") + .getOrCreate()) { + + // Read data from a table in ScalarDB Analytics + spark.sql("SELECT * FROM my_catalog.my_data_source.my_namespace.my_table").show(); + } + } +} +``` + +You can run your Spark Connect client application as a normal Java application by running the following command: + +```console +java -jar my-spark-connect-client.jar +``` + +For details about how you can use Spark Connect, refer to the [Spark Connect documentation](https://spark.apache.org/docs/latest/spark-connect-overview.html). + + + + +Unfortunately, Spark Thrift JDBC server does not support the Spark features that are necessary for ScalarDB Analytics, so you cannot use JDBC to read data from ScalarDB Analytics in your Apache Spark environment. JDBC application is referred to here because some managed Spark services provide different ways to interact with a Spark cluster via the JDBC interface. For more details, refer to [Supported application types](./deployment.mdx#supported-managed-spark-services-and-their-application-types). + + + + +## Catalog information mapping + +ScalarDB Analytics manages its own catalog, containing data sources, namespaces, tables, and columns. That information is automatically mapped to the Spark catalog. In this section, you will learn how ScalarDB Analytics maps its catalog information to the Spark catalog. + +For details about how information in the raw data sources is mapped to the ScalarDB Analytics catalog, refer to [Catalog information mappings by data source](./design.mdx#catalog-information-mappings-by-data-source). + +### Catalog level mapping + +Each catalog level object in the ScalarDB Analytics catalog is mapped to a Spark catalog. The following table shows how the catalog levels are mapped: + +#### Data source tables + +Tables from data sources in the ScalarDB Analytics catalog are mapped to Spark tables. The following format is used to represent the identity of the Spark tables that correspond to ScalarDB Analytics tables: + +```console +... +``` + +The following describes what you should change the content in the angle brackets to: + +- ``: The name of the catalog. +- ``: The name of the data source. +- ``: The names of the namespaces. If the namespace names are multi-level, they are concatenated with a dot (`.`) as the separator. +- ``: The name of the table. + +For example, if you have a ScalarDB catalog named `my_catalog` that contains a data source named `my_data_source` and a schema named `my_schema`, you can refer to the table named `my_table` in that schema as `my_catalog.my_data_source.my_schema.my_table`. + +#### Views + +Views in ScalarDB Analytics are provided as tables in the Spark catalog, not views. The following format is used to represent the identity of the Spark tables that correspond to ScalarDB Analytics views: + +```console +.view.. +``` + +The following describes what you should change the content in the angle brackets to: + +- ``: The name of the catalog. +- ``: The names of the view namespaces. If the view namespace names are multi-level, they are concatenated with a dot (`.`) as the separator. +- ``: The name of the view. + +For example, if you have a ScalarDB catalog named `my_catalog` and a view namespace named `my_view_namespace`, you can refer to the view named `my_view` in that namespace as `my_catalog.view.my_view_namespace.my_view`. + +:::note + +`view` is prefixed to avoid conflicts with the data source table identifier. + +::: + +##### WAL-interpreted views + +As explained in [ScalarDB Analytics Design](./design.mdx), ScalarDB Analytics provides a functionality called WAL-interpreted views, which is a special type of views. These views are automatically created for tables of ScalarDB data sources to provide a user-friendly view of the data by interpreting WAL-metadata in the tables. + +Since the data source name and the namespace names of the original ScalarDB tables are used as the view namespace names for WAL-interpreted views, if you have a ScalarDB table named `my_table` in a namespace named `my_namespace` of a data source named `my_data_source`, you can refer to the WAL-interpreted view of the table as `my_catalog.view.my_data_source.my_namespace.my_table`. + +### Data-type mapping + +ScalarDB Analytics maps data types in its catalog to Spark data types. The following table shows how the data types are mapped: + +| ScalarDB Data Type | Spark Data Type | +| :----------------- | :----------------- | +| `BYTE` | `Byte` | +| `SMALLINT` | `Short` | +| `INT` | `Integer` | +| `BIGINT` | `Long` | +| `FLOAT` | `Float` | +| `DOUBLE` | `Double` | +| `DECIMAL` | `Decimal` | +| `TEXT` | `String` | +| `BLOB` | `Binary` | +| `BOOLEAN` | `Boolean` | +| `DATE` | `Date` | +| `TIME` | `TimestampNTZ` | +| `TIMESTAMP` | `TimestampNTZ` | +| `TIMESTAMPTZ` | `Timestamp` | +| `DURATION` | `CalendarInterval` | +| `INTERVAL` | `CalendarInterval` | + +## Version compatibility + +Since Spark and Scala may be incompatible among different minor versions, ScalarDB Analytics offers different artifacts for various Spark and Scala versions, named in the format `scalardb-analytics-spark-all-_`. Make sure that you select the artifact matching the Spark and Scala versions you're using. For example, if you're using Spark 3.5 with Scala 2.13, you must specify `scalardb-analytics-spark-all-3.5_2.13`. + +Regarding the Java version, ScalarDB Analytics supports Java 8 or later. + +The following is a list of Spark and Scalar versions supported by each version of ScalarDB Analytics. + +| ScalarDB Analytics Version | ScalarDB Version | Spark Versions Supported | Scala Versions Supported | Minimum Java Version | +|:---------------------------|:-----------------|:-------------------------|:-------------------------|:---------------------| +| 3.15 | 3.15 | 3.5, 3.4 | 2.13, 2.12 | 8 | +| 3.14 | 3.14 | 3.5, 3.4 | 2.13, 2.12 | 8 | +| 3.12 | 3.12 | 3.5, 3.4 | 2.13, 2.12 | 8 | diff --git a/versioned_docs/version-3.15/scalardb-benchmarks/README.mdx b/versioned_docs/version-3.15/scalardb-benchmarks/README.mdx new file mode 100644 index 00000000..010d3e9d --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-benchmarks/README.mdx @@ -0,0 +1,236 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Benchmarking Tools + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This tutorial describes how to run benchmarking tools for ScalarDB. Database benchmarking is helpful for evaluating how databases perform against a set of standards. + +## Benchmark workloads + +- TPC-C +- YCSB (Workloads A, C, and F) +- Multi-storage YCSB (Workloads C and F) + - This YCSB variant is for a multi-storage environment that uses ScalarDB. + - Workers in a multi-storage YCSB execute the same number of read and write operations in two namespaces: `ycsb_primary` and `ycsb_secondary`. + +## Prerequisites + +- One of the following Java Development Kits (JDKs): + - [Oracle JDK](https://www.oracle.com/java/technologies/downloads/) LTS version 8 + - [OpenJDK](https://openjdk.org/install/) LTS version 8 +- Gradle +- [Kelpie](https://github.com/scalar-labs/kelpie) + - Kelpie is a framework for performing end-to-end testing, such as system benchmarking and verification. Get the latest version from [Kelpie Releases](https://github.com/scalar-labs/kelpie), and unzip the archive file. +- A client to run the benchmarking tools +- A target database + - For a list of databases that ScalarDB supports, see [Databases](../requirements.mdx#databases). + +:::note + +Currently, only JDK 8 can be used when running the benchmarking tools. + +::: + +## Set up the benchmarking tools + +The following sections describe how to set up the benchmarking tools. + +### Clone the ScalarDB benchmarks repository + +Open **Terminal**, then clone the ScalarDB benchmarks repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-benchmarks +``` + +Then, go to the directory that contains the benchmarking files by running the following command: + +```console +cd scalardb-benchmarks +``` + +### Build the tools + +To build the benchmarking tools, run the following command: + +```console +./gradlew shadowJar +``` + +### Load the schema + +Before loading the initial data, the tables must be defined by using the [ScalarDB Schema Loader](../schema-loader.mdx). You can download the ScalarDB Schema Loader on the [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) page. Select the Schema Loader based on how you access ScalarDB: +- **Using the ScalarDB Core library (Community edition)?:** Choose `scalardb-schema-loader-.jar` for the version of ScalarDB that you're using. Then, save the `.jar` file in the `scalardb-benchmarks` root directory. +- **Using ScalarDB Cluster (Enterprise edition)?:** Choose `scalardb-cluster-schema-loader--all.jar` for the version of ScalarDB Cluster that you're using. Then, save the `.jar` file in the `scalardb-benchmarks` root directory. + +In addition, you need a properties file for accessing ScalarDB via the Java CRUD interface. For details about configuring the ScalarDB properties file, see [ScalarDB Configurations](../configurations.mdx) or [ScalarDB Cluster Client Configurations](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#client-configurations). + +After applying the schema and configuring the properties file, select a benchmark and follow the instructions to create the tables. + + + + To create tables for TPC-C benchmarking ([`tpcc-schema.json`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/tpcc-schema.json)), run the following command, replacing the contents in the angle brackets as described: + + ```console + java -jar scalardb-schema-loader-.jar --config -f tpcc-schema.json --coordinator + ``` + + If you are using ScalarDB Cluster, run the following command instead: + + ```console + java -jar scalardb-cluster-schema-loader--all.jar --config -f tpcc-schema.json --coordinator + ``` + + + To create tables for YCSB benchmarking ([`ycsb-schema.json`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/ycsb-schema.json)), run the following command, replacing the contents in the angle brackets as described: + + ```console + java -jar scalardb-schema-loader-.jar --config -f ycsb-schema.json --coordinator + ``` + + If you are using ScalarDB Cluster, run the following command instead: + + ```console + java -jar scalardb-cluster-schema-loader--all.jar --config -f ycsb-schema.json --coordinator + ``` + + + To create tables for multi-storage YCSB benchmarking ([`ycsb-multi-storage-schema.json`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/ycsb-multi-storage-schema.json)), run the following command, replacing the contents in the angle brackets as described: + + ```console + java -jar scalardb-schema-loader-.jar --config -f ycsb-multi-storage-schema.json --coordinator + ``` + + If you are using ScalarDB Cluster, run the following command instead: + + ```console + java -jar scalardb-cluster-schema-loader--all.jar --config -f ycsb-multi-storage-schema.json --coordinator + ``` + + + +### Prepare a benchmarking configuration file + +To run a benchmark, you must first prepare a benchmarking configuration file. The configuration file requires at least the locations of the workload modules to run and the database configuration. + +The following is an example configuration for running the TPC-C benchmark. The ScalarDB properties file specified for `config_file` should be the properties file that you created as one of the steps in [Load the schema](#load-the-schema). + +:::note + +Alternatively, instead of using the ScalarDB properties file, you can specify each database configuration item in the `.toml` file. If `config_file` is specified, all other configurations under `[database_config]` will be ignored even if they are uncommented. + +::: + +```toml +[modules] +[modules.preprocessor] +name = "com.scalar.db.benchmarks.tpcc.TpccLoader" +path = "./build/libs/scalardb-benchmarks-all.jar" +[modules.processor] +name = "com.scalar.db.benchmarks.tpcc.TpccBench" +path = "./build/libs/scalardb-benchmarks-all.jar" +[modules.postprocessor] +name = "com.scalar.db.benchmarks.tpcc.TpccReporter" +path = "./build/libs/scalardb-benchmarks-all.jar" + +[database_config] +config_file = "" +#contact_points = "localhost" +#contact_port = 9042 +#username = "cassandra" +#password = "cassandra" +#storage = "cassandra" +``` + +You can define parameters to pass to modules in the configuration file. For details, see the sample configuration files below and available parameters in [Common parameters](#common-parameters): + +- **TPC-C:** [`tpcc-benchmark-config.toml`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/tpcc-benchmark-config.toml) +- **YCSB:** [`ycsb-benchmark-config.toml`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/ycsb-benchmark-config.toml) +- **Multi-storage YCSB:** [`ycsb-multi-storage-benchmark-config.toml`](https://github.com/scalar-labs/scalardb-benchmarks/blob/master/ycsb-multi-storage-benchmark-config.toml) + +## Run a benchmark + +Select a benchmark, and follow the instructions to run the benchmark. + + + + To run the TPC-C benchmark, run the following command, replacing `` with the path to the Kelpie directory: + + ```console + //bin/kelpie --config tpcc-benchmark-config.toml + ``` + + + To run the YCSB benchmark, run the following command, replacing `` with the path to the Kelpie directory: + + ```console + //bin/kelpie --config ycsb-benchmark-config.toml + ``` + + + To run the multi-storage YCSB benchmark, run the following command, replacing `` with the path to the Kelpie directory: + + ```console + //bin/kelpie --config ycsb-multi-storage-benchmark-config.toml + ``` + + + +In addition, the following options are available: + +- `--only-pre`. Only loads the data. +- `--only-process`. Only runs the benchmark. +- `--except-pre` Runs a job without loading the data. +- `--except-process`. Runs a job without running the benchmark. + +## Common parameters + +| Name | Description | Default | +|:---------------|:--------------------------------------------------------|:----------| +| `concurrency` | Number of threads for benchmarking. | `1` | +| `run_for_sec` | Duration of benchmark (in seconds). | `60` | +| `ramp_for_sec` | Duration of ramp-up time before benchmark (in seconds). | `0` | + +## Workload-specific parameters + +Select a benchmark to see its available workload parameters. + + + + | Name | Description | Default | + |:-----------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------| + | `num_warehouses` | Number of warehouses (scale factor) for benchmarking. | `1` | + | `load_concurrency` | Number of threads for loading. | `1` | + | `load_start_warehouse` | Start ID of loading warehouse. This option can be useful with `--skip-item-load` when loading large-scale data with multiple clients or adding additional warehouses. | `1` | + | `load_end_warehouse` | End ID of loading warehouse. You can use either `--num-warehouses` or `--end-warehouse` to specify the number of loading warehouses. | `1` | + | `skip_item_load` | Whether or not to skip loading item table. | `false` | + | `use_table_index` | Whether or not to use a generic table-based secondary index instead of ScalarDB's secondary index. | `false` | + | `np_only` | Run benchmark with only new-order and payment transactions (50% each). | `false` | + | `rate_new_order` | Percentage of new-order transactions. When specifying this percentage based on your needs, you must specify the percentages for all other rate parameters. In that case, the total of all rate parameters must equal 100 percent. | N/A | + | `rate_payment` | Percentage of payment transactions. When specifying this percentage based on your needs, you must specify the percentages for all other rate parameters. In that case, the total of all rate parameters must equal 100 percent. | N/A | + | `rate_order_status` | Percentage of order-status transactions. When specifying this percentage based on your needs, you must specify the percentages for all other rate parameters. In that case, the total of all rate parameters must equal 100 percent. | N/A | + | `rate_delivery` | Percentage of delivery transactions. When specifying this percentage based on your needs, you must specify the percentages for all other rate parameters. In that case, the total of all rate parameters must equal 100 percent. | N/A | + | `rate_stock_level` | Percentage of stock-level transactions. When specifying this percentage based on your needs, you must specify the percentages for all other rate parameters. In that case, the total of all rate parameters must equal 100 percent. | N/A | + | `backoff` | Sleep time in milliseconds inserted after a transaction is aborted due to a conflict. | `0` | + + + | Name | Description | Default | + |:------------------------|:----------------------------------------------------------------------------------|:----------------------------------------------| + | `load_concurrency` | Number of threads for loading. | `1` | + | `load_batch_size` | Number of put records in a single loading transaction. | `1` | + | `load_overwrite` | Whether or not to overwrite when loading records. | `false` | + | `ops_per_tx` | Number of operations in a single transaction. | `2` (Workloads A and C)
`1` (Workload F) | + | `record_count` | Number of records in the target table. | `1000` | + | `use_read_modify_write` | Whether or not to use read-modify-writes instead of blind writes in Workload A. | `false`[^rmw] | + + [^rmw]: The default value is `false` for `use_read_modify_write` since Workload A doesn't assume that the transaction reads the original record first. However, if you're using Consensus Commit as the transaction manager, you must set `use_read_modify_write` to `true`. This is because ScalarDB doesn't allow a blind write for an existing record. +
+
diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/common-reference.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/common-reference.mdx new file mode 100644 index 00000000..a71540f7 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/common-reference.mdx @@ -0,0 +1,194 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster .NET Client SDK Reference + +This reference provides details on how the ScalarDB Cluster .NET Client SDK works. + +## Client configuration + +The client can be configured by using the following: + +- A settings file, like `appsettings.json` or a custom JSON file +- Environment variables +- The `ScalarDbOptions` object + +If you use the SDK with ASP.NET Core, you can configure an app in more ways. For details, see [Configuration in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-8.0). + +For a list of options that you can configure, see [Available options](common-reference.mdx#available-options). + +### Using a settings file + +The SDK supports both the standard `appsettings.json` and custom JSON setting files. To configure the client in a JSON file, add the `ScalarDbOptions` section and configure the options that you need. For example: + +```json +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053", + "HopLimit": 10 + } +} +``` + +Then, create a configured `TransactionFactory` object as follows: + +```c# +// If appsettings.json is used, call the Create() method without parameters. +var factory = TransactionFactory.Create(); + +// Or, if a custom file is used, call the Create() method that is passed in the path to the custom file as a parameter. +factory = TransactionFactory.Create("scalardb-options.json"); +``` + +If you use the SDK with ASP.NET Core, the settings from `appsettings.json` will be applied automatically when the registered transaction managers and/or `ScalarDbContext` are created. If you want to use a custom JSON file, add it to the configuration framework as follows: + +```c# +var builder = WebApplication.CreateBuilder(args); + +// ... + +builder.Configuration.AddJsonFile("scalardb-options.json"); +``` + +:::warning + +Because the custom JSON file is applied after all standard configuration providers, the values from the custom file will override values from other sources. + +::: + +### Using environment variables + +To configure the client to use environment variables, you can use the prefix `ScalarDbOptions__`. For example: + +```console +export ScalarDbOptions__Address="http://localhost:60053" +export ScalarDbOptions__HopLimit=10 +``` + +:::warning + +Values from environment variables will override values from settings files. + +::: + +### Using the `ScalarDbOptions` object + +You can configure the client at runtime by using the `ScalarDbOptions` object as follows: + +```c# +var options = new ScalarDbOptions() +{ + Address = "http://localhost:60053", + HopLimit = 10 +}; + +var factory = TransactionFactory.Create(options); +``` + +You can also initialize the `ScalarDbOptions` object with values from JSON files and/or environment variables, and then set any remaining values at runtime as follows: + +```c# +// If appsettings.json is used, call the Load() method without parameters. +var options = ScalarDbOptions.Load(); + +// Or, if a custom file is used, call the Load() method that is passed in the path to the custom file as a parameter. +options = ScalarDbOptions.Load("scalardb-options.json"); + +options.HopLimit = 10; + +var factory = TransactionFactory.Create(options); +``` + +If you use the SDK with ASP.NET Core, a lambda function of `AddScalarDb` and/or `AddScalarDbContext` can be used as follows: + +```c# +var builder = WebApplication.CreateBuilder(args); + +//... + +builder.Services.AddScalarDb(options => +{ + options.Address = "http://localhost:60053"; + options.HopLimit = 10; +}); + +builder.Services.AddScalarDbContext(options => +{ + options.Address = "http://localhost:60053"; + options.HopLimit = 10; +}); +``` + +By using this configuration, the `ScalarDbOptions` object that is passed to the lambda function (named `options` in the example above) is initialized with values from the JSON files, environment variables, and other sources. + +### Available options + +The following options are available: + +| Name | Description | Default | +|-----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------| +| `Address` | **Required:** Address of the cluster in the following format: `://:`. ``: `https` if wire encryption (TLS) is enabled; `http` otherwise. ``: The FQDN or the IP address of the cluster. ``: The port number (`60053` by default) of the cluster. | - | +| `HopLimit` | Number of hops for a request to the cluster. The purpose of `HopLimit` is to prevent infinite loops within the cluster. Each time a request is forwarded to another cluster node, `HopLimit` decreases by one. If `HopLimit` reaches zero, the request will be rejected. | `3` | +| `RetryCount` | How many times a client can try to connect to the cluster if it's unavailable. | `10` | +| `AuthEnabled` | Whether authentication and authorization are enabled. | `false` | +| `Username` | Username for authentication and authorization. | | +| `Password` | Password for authentication. If this isn't set, authentication is conducted without a password. | | +| `AuthTokenExpirationTime` | Time after which the authentication token should be refreshed. If the time set for `AuthTokenExpirationTime` is greater than the expiration time on the cluster, the authentication token will be refreshed when an authentication error is received. If the authentication token is successfully refreshed, the authentication error won't be propagated to the client code. Instead, the operation that has failed with the authentication error will be retried automatically. If more than one operation is running in parallel, all these operations will fail once with the authentication error before the authentication token is refreshed. | `00:00:00` (The authentication token expiration time received from the cluster is used.) | +| `TlsRootCertPem` | Custom CA root certificate (PEM data) for TLS communication. | | +| `TlsRootCertPath` | File path to the custom CA root certificate for TLS communication. | | +| `TlsOverrideAuthority` | Custom authority for TLS communication. This doesn't change what host is actually connected. This is mainly intended for testing. For example, you can specify the hostname presented in the cluster's certificate (the `scalar.db.cluster.node.tls.cert_chain_path` parameter of the cluster). If there's more than one hostname in the cluster's certificate, only the first hostname will be checked. | | +| `LogSensitiveData` | If set to `true`, information like username, password, and authentication token will be logged as is without masking when logging gRPC requests and responses. | `false` | +| `GrpcRequestTimeout` | Timeout for gRPC requests. Internally, the timeout's value is used to calculate and set a deadline for each gRPC request to the cluster. If the set deadline is exceeded, the request is cancelled and `DeadlineExceededException` is thrown. If the timeout is set to `0`, no deadline will be set. | `00:01:00` | +| `GrpcMaxReceiveMessageSize` | The maximum message size in bytes that can be received by the client. When set to `0`, the message size is unlimited. | `4 MB` | +| `GrpcMaxSendMessageSize` | The maximum message size in bytes that can be sent from the client. When set to `0`, the message size is unlimited. | `0` (Unlimited) | + +## How ScalarDB column types are converted to and from .NET types + +When using [LINQ](getting-started-with-linq.mdx#set-up-classes) or extension methods for the [Transactional API](getting-started-with-scalardb-tables-as-csharp-classes.mdx#create-classes-for-all-scalardb-tables), [SQL API](getting-started-with-distributed-sql-transactions.mdx#execute-sql-queries), or [Administrative API](getting-started-with-scalardb-tables-as-csharp-classes.mdx#use-the-administrative-api), a column's value received from the cluster is automatically converted to a corresponding .NET type. Likewise, a value of a .NET property is automatically converted to a corresponding cluster's type when an object is being saved to the cluster. + +In the following table, you can find how types are converted: + +| ScalarDB type | .NET type | C# alias | +|---------------|----------------------------|----------| +| TEXT | System.String | string | +| INT | System.Int32 | int | +| BIGINT | System.Int64 | long | +| FLOAT | System.Single | float | +| DOUBLE | System.Double | double | +| BOOLEAN | System.Boolean | bool | +| BLOB | Google.Protobuf.ByteString | | +| DATE | NodaTime.LocalDate | | +| TIME | NodaTime.LocalTime | | +| TIMESTAMP | NodaTime.LocalDateTime | | +| TIMESTAMPTZ | NodaTime.Instant | | + +:::note + +The ScalarDB Cluster .NET Client SDK uses [Google.Protobuf](https://www.nuget.org/packages/Google.Protobuf) for `BLOB` type and [NodaTime](https://www.nuget.org/packages/NodaTime) for time-related types. + +::: + +:::warning + +The precision of time-related types in .NET is greater than supported by ScalarDB. Therefore, you should be careful when saving time-related values received from external sources. The ScalarDB Cluster .NET Client SDK includes `WithScalarDbPrecision` extension methods that you can use to lower the precision of time-related values in the following manner: + +```c# +using ScalarDB.Client.Extensions; + +// ... + +var updatedAt = Instant.FromDateTimeUtc(DateTime.UtcNow) + .WithScalarDbPrecision(); + +// using NodaTime to get current instant +updatedAt = clockInstance.GetCurrentInstant() + .WithScalarDbPrecision(); +``` + +For details about value ranges and precision in ScalarDB, see [Data-type mapping between ScalarDB and other databases](../schema-loader.mdx#data-type-mapping-between-scalardb-and-other-databases). + +::: diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/exception-handling.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/exception-handling.mdx new file mode 100644 index 00000000..1767360f --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/exception-handling.mdx @@ -0,0 +1,175 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Exception Handling in the ScalarDB Cluster .NET Client SDK + +When executing a transaction, you will also need to handle exceptions properly. + +:::warning + +If you don't handle exceptions properly, you may face anomalies or data inconsistency. + +::: + +:::note + +The Transactional API is used in this example, but exceptions can be handled in the same way when using the SQL API or `ScalarDbContext`. + +::: + +The following sample code shows how to handle exceptions: + +```c# +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client; +using ScalarDB.Client.DataAnnotations; +using ScalarDB.Client.Exceptions; +using ScalarDB.Client.Extensions; + +var options = new ScalarDbOptions { Address = "http://:"}; + +var factory = TransactionFactory.Create(options); +using var manager = factory.GetTransactionManager(); + +var retryCount = 0; +TransactionException? lastException = null; + +while (true) +{ + if (retryCount++ > 0) + { + // Retry the transaction three times maximum in this sample code + if (retryCount > 3) + // Throw the last exception if the number of retries exceeds the maximum + throw lastException!; + + // Sleep 100 milliseconds before retrying the transaction in this sample code + await Task.Delay(100); + } + + // Begin a transaction + var tran = await manager.BeginAsync(); + try + { + // Execute CRUD operations in the transaction + var getKeys = new Dictionary { { nameof(Item.Id), 1 } }; + var result = await tran.GetAsync(getKeys); + + var scanKeys = new Dictionary { { nameof(Item.Id), 1 } }; + await foreach (var item in tran.ScanAsync(scanKeys, null)) + Console.WriteLine($"{item.Id}, {item.Name}, {item.Price}"); + + await tran.InsertAsync(new Item { Id = 1, Name = "Watermelon", Price = 4500 }); + await tran.DeleteAsync(new Item { Id = 1 }); + + // Commit the transaction + await tran.CommitAsync(); + + return; + } + catch (UnsatisfiedConditionException) + { + // You need to handle `UnsatisfiedConditionException` only if a mutation operation specifies + // a condition. This exception indicates the condition for the mutation operation is not met. + // InsertAsync/UpdateAsync implicitlly sets IfNotExists/IfExists condition + + try + { + await tran.RollbackAsync(); + } + catch (TransactionException ex) + { + // Rolling back the transaction failed. As the transaction should eventually recover, you + // don't need to do anything further. You can simply log the occurrence here + Console.WriteLine($"Rollback error: {ex}"); + } + + // You can handle the exception here, according to your application requirements + + return; + } + catch (UnknownTransactionStatusException) + { + // If you catch `UnknownTransactionStatusException` when committing the transaction, it + // indicates that the status of the transaction, whether it has succeeded or not, is + // unknown. In such a case, you need to check if the transaction is committed successfully + // or not and retry it if it failed. How to identify a transaction status is delegated to users + return; + } + catch (TransactionException ex) + { + // For other exceptions, you can try retrying the transaction. + + // For `TransactionConflictException` and `TransactionNotFoundException`, + // you can basically retry the transaction. However, for the other exceptions, + // the transaction may still fail if the cause of the exception is nontransient. + // In such a case, you will exhaust the number of retries and throw the last exception + + try + { + await tran.RollbackAsync(); + } + catch (TransactionException e) + { + // Rolling back the transaction failed. As the transaction should eventually recover, + // you don't need to do anything further. You can simply log the occurrence here + Console.WriteLine($"Rollback error: {e}"); + } + + lastException = ex; + } +} + +[Table("order_service.items")] +public class Item +{ + [PartitionKey] + [Column("item_id", Order = 0)] + public int Id { get; set; } + + [Column("name", Order = 1)] + public string Name { get; set; } = String.Empty; + + [Column("price", Order = 2)] + public int Price { get; set; } +} + +``` + +:::note + +In the sample code, the transaction is retried a maximum of three times and sleeps for 100 milliseconds before it is retried. You can choose a retry policy, such as exponential backoff, according to your application requirements. + +::: + +### Exception details + +The table below shows transaction exceptions that can occur when communicating with the cluster: + +| Exception | Operations | Description | +|-----------------------------------|--------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| AuthenticationErrorException | All | The authentication failed because of a wrong username and/or password when calling the cluster. | +| AuthorizationErrorException | Put, Insert, Update, Delete, Mutate, Execute, Administrative | The authorization failed because of a lack of permissions. | +| HopLimitExceededException | All | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| IllegalArgumentException | All | The argument in the request message is invalid. | +| IllegalStateException | All | The RPC was called in an invalid state. | +| InternalErrorException | All | The operation failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| TransactionConflictException | All except Begin, Join, Rollback | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| TransactionNotFoundException | All except Begin, Join | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| UnavailableException | All | ScalarDB Cluster is unavailable even after trying to connect multiple times. | +| UnknownTransactionStatusException | Commit | The status of the transaction is unknown (it is uncertain whether the transaction was successfully committed or not). In this situation, you need to check whether the transaction was successfully committed, and if not, to retry it. You are responsible for determining the transaction status. You may benefit from creating a transaction status table and updating it in conjunction with other application data. Doing so may help you determine the status of a transaction from the table itself. | +| UnsatisfiedConditionException | Put, Insert, Update, Delete, Mutate | The mutation condition is not satisfied. | + +If you encounter an exception, you should roll back the transaction, except in the case of `Begin`. After rolling back the transaction, you can retry the transaction from the beginning for the exceptions that can be resolved by retrying. + +Besides the exceptions listed above, you may encounter exceptions thrown by the gRPC library. In such cases, you can check the `RpcException` property for more information. + +Also, `ScalarDbContext` will throw a `TransactionException` type exception in the following cases: + +- If `BeginTransaction` or `JoinTransaction` were called when there was already an active transaction +- If `CommitTransaction` or `RollbackTransaction` were called without an active transaction +- If `PrepareTransaction` or `ValidateTransaction` were called without an active two-phase commit transaction diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-admin-api.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-admin-api.mdx new file mode 100644 index 00000000..c7a81560 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-admin-api.mdx @@ -0,0 +1,128 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with the Administrative API in the ScalarDB Cluster .NET Client SDK + +The ScalarDB Cluster .NET Client SDK supports the Administrative API of ScalarDB Cluster. By using this API, you can manage ScalarDB Cluster from .NET applications. + +:::note + +Although we recommend using asynchronous methods as in the following examples, you can use synchronous methods instead. + +::: + +## Install the SDK + +Install the same major and minor version of the [SDK](https://www.nuget.org/packages/ScalarDB.Client) as ScalarDB Cluster into the .NET project. You can do this by using the built-in NuGet package manager, replacing `.` with the version that you're using: + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## Create a settings file + +Create a `scalardb-options.json` file and add the following, replacing `` with the FQDN or the IP address, and `` with the port number (`60053` by default) of your cluster: + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +For details about settings files and other ways to configure the client, see [Client configuration](common-reference.mdx#client-configuration). + +## Get a transaction manager + +You need to get an object for interacting with the Administrative API. To get the object, you can use `TransactionFactory` as follows: + +```c# +// Pass the path to the settings file created in the previous step. +var factory = TransactionFactory.Create("scalardb-options.json"); + +using var admin = factory.GetTransactionAdmin(); +``` + +## Manage ScalarDB Cluster + +The following operations can be performed by using the ScalarDB Cluster .NET Client SDK. + +### Create a new namespace + +```c# +await admin.CreateNamespaceAsync("ns", ifNotExists: true); +``` + +### Drop a namespace + +```c# +await admin.DropNamespaceAsync("ns", ifExists: true); +``` + +### Check if a namespace exists + +```c# +var namespaceExists = await admin.IsNamespacePresentAsync("ns"); +``` + +### Create a new table + +```c# +// ... +using ScalarDB.Client.Builders.Admin; +using ScalarDB.Client.Core; + +// ... + +var tableMetadata = + new TableMetadataBuilder() + .AddPartitionKey("pk", DataType.Int) + .AddClusteringKey("ck", DataType.Double) + .AddSecondaryIndex("index", DataType.Float) + .AddColumn("ordinary", DataType.Text) + .Build(); + +await admin.CreateTableAsync("ns", "table_name", tableMetadata, ifNotExists: true); +``` + +### Drop a table + +```c# +await admin.DropTableAsync("ns", "table_name", ifExists: true); +``` + +### Checking if a table exists + +```c# +var tableExists = await admin.IsTablePresentAsync("ns", "table_name"); +``` + +### Get the names of existing tables + +```c# +var tablesList = await admin.GetTableNamesAsync("ns"); +``` + +### Create the Coordinator table + +```c# +await admin.CreateCoordinatorTablesAsync(); +``` + +### Drop the Coordinator table + +```c# +await admin.DropCoordinatorTablesAsync(); +``` + +### Check if the Coordinator table exist + +```c# +var exists = await admin.AreCoordinatorTablesPresentAsync(); +``` diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-aspnet-and-di.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-aspnet-and-di.mdx new file mode 100644 index 00000000..b3188720 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-aspnet-and-di.mdx @@ -0,0 +1,84 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ASP.NET Core and Dependency Injection in the ScalarDB Cluster .NET Client SDK + +The ScalarDB Cluster .NET Client SDK supports dependency injection (DI) in frameworks like ASP.NET Core. + +## Install the SDK + +Install the same major and minor version of the [SDK](https://www.nuget.org/packages/ScalarDB.Client) as ScalarDB Cluster into the .NET project. You can do this by using the built-in NuGet package manager, replacing `.` with the version that you're using: + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## Add client settings + +Add the `ScalarDbOptions` section to the `appsettings.json` file of your ASP.NET Core app, replacing `` with the FQDN or the IP address, and `` with the port number (`60053` by default) of your cluster: + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +For details about settings files and other ways to configure the client, see [Client configuration](common-reference.mdx#client-configuration). + +## Set up the transaction managers + +You can register the ScalarDB transaction managers in the DI container as follows: + +```c# +using ScalarDB.Client.Extensions; + +//... + +var builder = WebApplication.CreateBuilder(args); + +//... + +builder.Services.AddScalarDb(); +``` + +:::note + +The ScalarDB transaction managers will be registered as transient services. For details about service lifetimes, see [.NET dependency injection - Service lifetimes](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#service-lifetimes). + +::: + +After registering the transaction managers, they can be injected into the controller's constructor as follows: + +```c# +[ApiController] +public class OrderController: ControllerBase +{ + private readonly IDistributedTransactionManager _manager; + private readonly ISqlTransactionManager _sqlManager; + private readonly ITwoPhaseCommitTransactionManager _twoPhaseManager; + private readonly ISqlTwoPhaseCommitTransactionManager _sqlTwoPhaseManager; + private readonly IDistributedTransactionAdmin _admin; + + public OrderController(IDistributedTransactionManager manager, + ISqlTransactionManager sqlManager, + ITwoPhaseCommitTransactionManager twoPhaseManager, + ISqlTwoPhaseCommitTransactionManager sqlTwoPhaseManager, + IDistributedTransactionAdmin admin) + { + _manager = manager; + _sqlManager = sqlManager; + _twoPhaseManager = twoPhaseManager; + _sqlTwoPhaseManager = sqlTwoPhaseManager; + _admin = admin; + } +} +``` + +Although these examples are for WebApi projects, the examples will work in a similar way in GrpcService projects. diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-auth.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-auth.mdx new file mode 100644 index 00000000..196a2ac1 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-auth.mdx @@ -0,0 +1,67 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Authentication and Authorization by Using ScalarDB Cluster .NET Client SDK + +The ScalarDB Cluster .NET Client SDK supports [authentication and authorization](../scalardb-cluster/scalardb-auth-with-sql.mdx), which allows you to authenticate and authorize your requests to ScalarDB Cluster. + +## Install the SDK + +Install the same major and minor version of the [SDK](https://www.nuget.org/packages/ScalarDB.Client) as ScalarDB Cluster into the .NET project. You can do this by using the built-in NuGet package manager, replacing `.` with the version that you're using: + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## Set credentials in the settings file + +You need to set credentials in the settings file as follows, replacing the contents in the angle brackets as described: + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10, + "AuthEnabled": true, + "Username": "", + "Password": "" + } +} +``` + +For details about settings files and other ways to configure the client, see [Client configuration](common-reference.mdx#client-configuration). + +## Get a transaction manager + +You need to get a transaction manager or transaction admin object by using `TransactionFactory` as follows. Be sure to replace `` with `GetTransactionManager()`, `GetTwoPhaseCommitTransactionManager()`, `GetSqlTransactionManager()`, or `GetSqlTwoPhaseCommitTransactionManager()`. + +```c# +// Pass the path to the settings file. +var factory = TransactionFactory.Create("scalardb-options.json"); + +// To get a transaction manager +using var manager = factory.(); + +// To get a transaction admin +using var admin = factory.GetTransactionAdmin(); +``` + +A transaction manager or transaction admin object created from `TransactionFactory` with the provided credentials will automatically log in to ScalarDB Cluster and can communicate with it. + +## Wire encryption + +[Wire encryption](../scalardb-cluster/scalardb-auth-with-sql.mdx#wire-encryption) is also supported. It can be turned on by setting `Address` to the URL starting with `https` as follows: + +```json +{ + "ScalarDbOptions": { + "Address": "https://:" + } +} +``` + +For details about settings files and other ways to configure the client, see [Client configuration](common-reference.mdx#client-configuration). diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx new file mode 100644 index 00000000..628ea26d --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx @@ -0,0 +1,192 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Distributed SQL Transactions in the ScalarDB Cluster .NET Client SDK + +The ScalarDB Cluster .NET Client SDK supports the distributed SQL transaction functionality of ScalarDB Cluster. The SDK includes transaction and manager abstractions for easier communication within a cluster. + +:::note + +Although we recommend using asynchronous methods, as in the following examples, you can use synchronous methods instead. + +::: + +For details about distributed non-SQL transactions, see [Getting Started with Distributed Transactions in the ScalarDB Cluster .NET Client SDK](getting-started-with-distributed-transactions.mdx). + +## Install the SDK + +Install the same major and minor version of the [SDK](https://www.nuget.org/packages/ScalarDB.Client) as ScalarDB Cluster into the .NET project. You can do this by using the built-in NuGet package manager, replacing `.` with the version that you're using: + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## Create a settings file + +Create a `scalardb-options.json` file and add the following, replacing `` with the FQDN or the IP address, and `` with the port number (`60053` by default) of your cluster: + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +For details about settings files and other ways to configure the client, see [Client configuration](common-reference.mdx#client-configuration). + +## Get a transaction manager + +You need to get a transaction manager object for distributed SQL transactions. To get the transaction manager object, you can use `TransactionFactory` as follows: + +```c# +// Pass the path to the settings file created in the previous step. +var factory = TransactionFactory.Create("scalardb-options.json"); + +using var manager = factory.GetSqlTransactionManager(); +``` + +## Execute SQL queries + +To execute a SQL statement, you need an `ISqlStatement` object, which can be created by using a builder as follows: + +```c# +using ScalarDB.Client.Builders.Sql; + +// ... + +var sqlStatement = + new SqlStatementBuilder() + .SetSql("SELECT * FROM order_service.statements WHERE item_id = :item_id") + .AddParam("item_id", 2) + .Build(); +``` + +A single SQL statement can be executed directly by using the transaction manager as follows: + +```c# +var resultSet = await manager.ExecuteAsync(sqlStatement); +``` + +The result from the `ExecuteAsync` method will contain records received from the cluster. The value of the specific column can be retrieved in the following manner: + +```c# +foreach (var record in resultSet.Records) +{ + // Getting an integer value from the "item_id" column. + // If it fails, an exception will be thrown. + var itemId = record.GetValue("item_id"); + + // Trying to get a string value from the "order_id" column. + // If it fails, no exception will be thrown. + if (record.TryGetValue("order_id", out var orderId)) + Console.WriteLine($"order_id: {orderId}"); + + // Checking if the "count" column is null. + if (record.IsNull("count")) + Console.WriteLine("'count' is null"); +} +``` + +For details about which type should be used in `GetValue` and `TryGetValue`, see [How ScalarDB Column Types Are Converted to and from .NET Types](common-reference.mdx#how-scalardb-column-types-are-converted-to-and-from-net-types). + +## Execute SQL queries in a transaction + +To execute multiple SQL statements as part of a single transaction, you need a transaction object. + +You can create a transaction object by using the transaction manager as follows: + +```c# +var transaction = await manager.BeginAsync(); +``` + +You can also resume a transaction that has already been started as follows: + +```c# +var transaction = manager.Resume(transactionIdString); +``` + +:::note + +The `Resume` method doesn't have an asynchronous version because it only creates a transaction object. Because of this, resuming a transaction by using the wrong ID is possible. + +::: + +The transaction has the same `ExecuteAsync` method as the transaction manager. That method can be used to execute SQL statements. + +When a transaction is ready to be committed, you can call the `CommitAsync` method of the transaction as follows: + +```c# +await transaction.CommitAsync(); +``` + +To roll back the transaction, you can use the `RollbackAsync` method: + +```c# +await transaction.RollbackAsync(); +``` + +## Get Metadata + +You can retrieve ScalarDB's metadata with the Metadata property as follows: + +```c# +// namespaces, tables metadata +var namespaceNames = new List(); + +await foreach (var ns in manager.Metadata.GetNamespacesAsync()) +{ + namespaceNames.Add(ns.Name); + Console.WriteLine($"Namespace: {ns.Name}"); + + await foreach (var tbl in ns.GetTablesAsync()) + { + Console.WriteLine($" Table: {tbl.Name}"); + + Console.WriteLine($" Columns:"); + foreach (var col in tbl.Columns) + Console.WriteLine($" {col.Name} [{col.DataType}]"); + + Console.WriteLine($" PartitionKey:"); + foreach (var col in tbl.PartitionKey) + Console.WriteLine($" {col.Name}"); + + Console.WriteLine($" ClusteringKey:"); + foreach (var col in tbl.ClusteringKey) + Console.WriteLine($" {col.Name} [{col.ClusteringOrder}]"); + + Console.WriteLine($" Indexes:"); + foreach (var index in tbl.Indexes) + Console.WriteLine($" {index.ColumnName}"); + + Console.WriteLine(); + } +} + +// users metadata +await foreach (var user in manager.Metadata.GetUsersAsync()) +{ + Console.WriteLine($"User: {user.Name} [IsSuperuser: {user.IsSuperuser}]"); + + foreach (var nsName in namespaceNames) + { + Console.WriteLine($" Namespace: {nsName}"); + + Console.WriteLine($" Privileges:"); + foreach (var privilege in await user.GetPrivilegesAsync(nsName)) + Console.WriteLine($" {privilege}"); + } + + Console.WriteLine(); +} +``` + +:::note + +To use LINQ methods with `IAsyncEnumerable`, you can install [System.Linq.Async](https://www.nuget.org/packages/System.Linq.Async/) package. + +::: diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions.mdx new file mode 100644 index 00000000..30582abc --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions.mdx @@ -0,0 +1,329 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Distributed Transactions in the ScalarDB Cluster .NET Client SDK + +The ScalarDB Cluster .NET Client SDK supports the distributed transaction functionality of ScalarDB Cluster. The SDK includes transaction and manager abstractions for easier communication within a cluster. + +:::note + +Although we recommend using asynchronous methods as in the following examples, you can use synchronous versions instead. + +::: + +For details about distributed SQL transactions, see [Getting Started with Distributed SQL Transactions in the ScalarDB Cluster .NET Client SDK](getting-started-with-distributed-sql-transactions.mdx). + +## Install the SDK + +Install the same major and minor version of the [SDK](https://www.nuget.org/packages/ScalarDB.Client) as ScalarDB Cluster into the .NET project. You can do this by using the built-in NuGet package manager, replacing `.` with the version that you're using: + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## Create a settings file + +Create a `scalardb-options.json` file and add the following, replacing `` with the FQDN or the IP address, and `` with the port number (`60053` by default) of your cluster: + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +For details about settings files and other ways to configure the client, see [Client configuration](common-reference.mdx#client-configuration). + +## Get a transaction manager + +You need to get a transaction manager for distributed transactions. To get the transaction manager, you can use `TransactionFactory` as follows: + +```c# +// Pass the path to the settings file created in the previous step. +var factory = TransactionFactory.Create("scalardb-options.json"); + +using var manager = factory.GetTransactionManager(); +``` + +## Manage transactions + +To execute multiple CRUD operations as part of a single transaction, first, you need to begin a transaction. You can begin a transaction by using the transaction manager as follows: + +```c# +var transaction = await manager.BeginAsync(); +``` + +You can also resume a transaction that is already being executed as follows: + +```c# +var transaction = manager.Resume(transactionIdString); +``` + +:::note + +The `Resume` method doesn't have an asynchronous version because it only creates a transaction object. Because of this, resuming a transaction by using the wrong ID is possible. + +::: + +When a transaction is ready to be committed, you can call the `CommitAsync` method of the transaction as follows: + +```c# +await transaction.CommitAsync(); +``` + +To roll back the transaction, you can use the `RollbackAsync` method: + +```c# +await transaction.RollbackAsync(); +``` + +## Execute CRUD operations + +A transaction has `GetAsync`, `ScanAsync`, `InsertAsync`, `UpsertAsync`, `UpdateAsync`, `DeleteAsync`, and `MutateAsync` methods to execute CRUD operations against the cluster. As a parameter, these methods have an operation object. An operation object can be created by using the builders listed in this section. + +:::note + +CRUD operations can be executed in a one-shot transaction manner without needing to explicitly create a transaction. For that, a manager object has the same CRUD methods as a transaction object. + +::: + +To use builders, add the following namespace to the `using` section: + +```c# +using ScalarDB.Client.Builders; +``` + +:::note + +The cluster does not support parallel execution of commands inside one transaction, so make sure to use `await` for asynchronous methods. + +::: + +### `GetAsync` method example + +To retrieve a single record, you can use the `GetAsync` method as follows: + +```c# +var get = + new GetBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .SetProjections("item_id", "count") + .Build(); + +var getResult = await transaction.GetAsync(get); +``` + +It is possible to retrieve a record by using an index instead of a partition key. To do that, you need to set the type of operation to `GetWithIndex` as follows: + +```c# +// ... +using ScalarDB.Client.Core; + +// ... + +var get = + new GetBuilder() + // ... + .SetGetType(GetOperationType.GetWithIndex) + .AddPartitionKey("index_column", "1") + .Build(); +``` + +You can also specify arbitrary conditions that a retrieved record must meet, or it won't be returned. The conditions can be set as conjunctions of conditions as follows: + +```c# +var get = + new GetBuilder() + // ... + .AddConjunction(c => c.AddCondition("cost", 1000, Operator.LessThan)) + .AddConjunction(c => + { + c.AddCondition("cost", 10000, Operator.LessThan); + c.AddCondition("in_stock", true, Operator.Equal); + }) + .Build(); +``` + +In the above example, a record will be returned only if its `cost` is less than `1000`, or if its `cost` is less than `10000` and `in_stock` is true. + +#### Handle `IResult` objects + +The `GetAsync` and `ScanAsync` methods return `IResult` objects. An `IResult` object contains columns of the retrieved record. The value of the specific column can be retrieved in the following manner: + +```c# +// Getting an integer value from the "item_id" column. +// If it fails, an exception will be thrown. +var itemId = result.GetValue("item_id"); + +// Trying to get a string value from the "order_id" column. +// If it fails, no exception will be thrown. +if (result.TryGetValue("order_id", out var orderId)) + Console.WriteLine($"order_id: {orderId}"); + +// Checking if the "count" column is null. +if (result.IsNull("count")) + Console.WriteLine("'count' is null"); +``` + +For details about which type should be used in `GetValue` and `TryGetValue`, see [How ScalarDB Column Types Are Converted to and from .NET Types](common-reference.mdx#how-scalardb-column-types-are-converted-to-and-from-net-types). + +### `ScanAsync` method example + +To retrieve a range of records, you can use the `ScanAsync` method as follows: + +```c# +var scan = + new ScanBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddStartClusteringKey("item_id", 2) + .SetStartInclusive(true) + .AddEndClusteringKey("item_id", 8) + .SetEndInclusive(true) + .SetProjections("item_id", "count") + .Build(); + +var scanResult = await transaction.ScanAsync(scan); +``` + +It is possible to retrieve a record by using an index instead of a partition key. To do that, you need to set the type of operation to `ScanWithIndex` as follows: + +```c# +// ... +using ScalarDB.Client.Core; + +// ... + +var scan = + new ScanBuilder() + // ... + .SetScanType(ScanOperationType.ScanWithIndex) + .AddPartitionKey("index_column", "1") + .Build(); +``` + +The arbitrary conditions that a retrieved record must meet can also be set for a scan operation in the same way as for a [get operation](getting-started-with-distributed-transactions.mdx#getasync-method-example). + +### `InsertAsync` method example + +To insert a new record, you can use the `InsertAsync` method as follows: + +```c# +var insert = + new InsertBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .AddColumn("count", 11) + .Build(); + +await transaction.InsertAsync(insert); +``` + +### `UpsertAsync` method example + +To upsert a record (update an existing record or insert a new one), you can use the `UpsertAsync` method as follows: + +```c# +var upsert = + new UpsertBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .AddColumn("count", 11) + .Build(); + +await transaction.UpsertAsync(upsert); +``` + +### `UpdateAsync` method example + +To update an existing record, you can use the `UpdateAsync` method as follows: + +```c# +// ... +using ScalarDB.Client.Core; + +// ... + +var update = + new UpdateBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .AddColumn("count", 11) + .AddCondition("processed", false, Operator.Equal) + .Build(); + +await transaction.UpdateAsync(update); +``` + +### `DeleteAsync` method example + +To delete a record, you can use the `DeleteAsync` method as follows: + +```c# +// ... +using ScalarDB.Client.Core; + +// ... + +var delete = + new DeleteBuilder() + .SetNamespaceName("ns") + .SetTableName("statements") + .AddPartitionKey("order_id", "1") + .AddClusteringKey("item_id", 2) + .AddCondition("processed", false, Operator.Equal) + .Build(); + +await transaction.DeleteAsync(delete); +``` + +### `MutateAsync` method example + +The `MutateAsync` method allows you to execute more than one mutation operation in a single call to the cluster. You can do this in the following manner: + +```c# +// ... +using ScalarDB.Client.Core; + +// ... + +var mutations = new IMutation[] + { + new InsertBuilder() + // ... + .Build(), + new UpsertBuilder() + // ... + .Build(), + new UpdateBuilder() + // ... + .Build(), + new DeleteBuilder() + // ... + .Build() + }; + +await transaction.MutateAsync(mutations); +``` + +:::note + +To modify data by using the `InsertAsync`, `UpsertAsync`, `UpdateAsync`, `DeleteAsync`, or `MutateAsync` method, the data must be retrieved first by using the `GetAsync` or `ScanAsync` method. + +::: diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx new file mode 100644 index 00000000..5acee088 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx @@ -0,0 +1,369 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with LINQ in the ScalarDB Cluster .NET Client SDK + +The ScalarDB Cluster .NET Client SDK supports querying the cluster with LINQ and some Entity Framework-like functionality. + +:::note + +This SDK doesn't support [Entity Framework](https://learn.microsoft.com/en-us/ef/). Instead, this SDK implements functionality that is similar to Entity Framework. + +::: + +:::note + +SQL support must be enabled on the cluster to use LINQ. + +::: + +## Install the SDK + +Install the same major and minor version of the [SDK](https://www.nuget.org/packages/ScalarDB.Client) as ScalarDB Cluster into the .NET project. You can do this by using the built-in NuGet package manager, replacing `.` with the version that you're using: + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## Add client settings + +Add the `ScalarDbOptions` section to the `appsettings.json` file of your ASP.NET Core app, replacing `` with the FQDN or the IP address, and `` with the port number (`60053` by default) of your cluster: + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +For details about settings files and other ways to configure the client, see [Client configuration](common-reference.mdx#client-configuration). + +## Set up classes + +After confirming that SQL support is enabled, create a C# class for each ScalarDB table that you want to use. For example: + +```c# +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client.DataAnnotations; + +// ... + +[Table("ns.statements")] +public class Statement +{ + [PartitionKey] + [Column("statement_id", Order = 0)] + public int Id { get; set; } + + [SecondaryIndex] + [Column("order_id", Order = 1)] + public string OrderId { get; set; } = String.Empty; + + [SecondaryIndex] + [Column("item_id", Order = 2)] + public int ItemId { get; set; } + + [Column("count", Order = 3)] + public int Count { get; set; } +} + +[Table("order_service.items")] +public class Item +{ + [PartitionKey] + [Column("item_id", Order = 0)] + public int Id { get; set; } + + [Column("name", Order = 1)] + public string Name { get; set; } = String.Empty; + + [Column("price", Order = 2)] + public int Price { get; set; } +} +``` + +If a partition key, clustering key, or secondary index consists of more than one column, the `Order` property of `ColumnAttribute` will decide the order inside the key or index. + +For details about which types should be used for properties, see [How ScalarDB Column Types Are Converted to and from .NET Types](common-reference.mdx#how-scalardb-column-types-are-converted-to-and-from-net-types). + +Create a context class that has properties for all the tables you want to use. For example: + +```c# + public class MyDbContext: ScalarDbContext + { + public ScalarDbSet Statements { get; set; } + public ScalarDbSet Items { get; set; } + } +``` + +After all the classes are created, you need to register the created context in the dependency injection container. For example: + +```c# +using ScalarDB.Client.Extensions; + +//... + +var builder = WebApplication.CreateBuilder(args); + +//... + +builder.Services.AddScalarDbContext(); +``` + +:::note + +The context class will be registered as a transient service. For details about service lifetimes, see [.NET dependency injection - Service lifetimes](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#service-lifetimes). + +::: + +The context can be injected into the controller's constructor as follows: + +```c# +[ApiController] +public class OrderController: ControllerBase +{ + private readonly MyDbContext _myDbContext; + + public OrderController(MyDbContext myDbContext) + { + _myDbContext = myDbContext; + } +} +``` + +## Use LINQ to query properties + +After receiving `MyDbContext` in your controller, you can query its properties by using LINQ. For example: + +### Use query syntax + +```c# +from stat in _myDbContext.Statements +join item in _myDbContext.Items on stat.ItemId equals item.Id +where stat.Count > 2 && item.Name.Contains("apple") +orderby stat.Count descending, stat.ItemId +select new { item.Name, stat.Count }; +``` + +### Use method syntax + +```c# +_myDbContext.Statements + .Where(stat => stat.OrderId == "1") + .Skip(1) + .Take(2); +``` + +### Use the `First` method to get one `Statement` by its partition key + +```c# +_myDbContext.Statements.First(stat => stat.OrderId == "1"); +``` + +### Use the `DefaultIfEmpty` method to perform left outer join + +```c# +from stat in _myDbContext.Statements +join item in _myDbContext.Items on stat.ItemId equals item.Id into items +from i in items.DefaultIfEmpty() +select new { ItemName = i != null ? i.Name : "" } +``` + +The following methods are supported: + +- `Select` +- `Where` +- `Join` +- `GroupJoin` +- `First`/`FirstOrDefault` +- `Skip` +- `Take` +- `OrderBy`/`OrderByDescending` +- `ThenBy`/`ThenByDescending` + +The following `String` methods are supported inside the predicates of `Where` and `First`/`FirstOrDefault` methods: + +- `Contains` +- `StartsWith` +- `EndsWith` + +Unsupported LINQ methods can be used after the supported methods. For example: + +```c# +_myDbContext.Statements + .Where(stat => stat.OrderId == "1") // Will be executed remotely on the cluster. + .Distinct() // Will be executed locally in the app. + .Where(stat => stat.ItemId < 5); // Will be executed locally. +``` + +:::note + +If `Skip` is specified before `Take` or `First`/`FirstOrDefault`, the number that is passed to `Skip` will be added to the `LIMIT` number in the SQL query. By itself, `Skip` won't change the resulting SQL query. + +::: + +## Limitations when using LINQ against `ScalarDbSet{T}` objects + +- All method calls are supported inside `Select`. For example: + +```c# +.Select(stat => convertToSomething(stat.ItemId)) +//... +.Select(stat => stat.ItemId * getSomeNumber()) +``` + +- Method calls, except for calls against the querying object, are also supported inside `Where` and `First`/`FirstOrDefault`. For example: + +```c# +.Where(stat => stat.ItemId == getItemId()) // is OK +//... +.Where(stat => stat.ItemId.ToString() == "1") // is not supported +``` + +- All method calls are supported inside the result-selecting lambda of `Join` and `GroupJoin`. For example: + +```c# +.Join(_myDbContext.Items, + stat => stat.ItemId, + item => item.Id, + (stat, item) => new { ItemName = convertToSomething(item.Name), + ItemCount = stat.Count.ToString() }) +``` + +- Method calls are not supported inside the key-selecting lambdas of `Join` and `GroupJoin`. +- Custom equality comparers are not supported. The `comparer` argument in `Join` and `GroupJoin` methods will be ignored if the argument has been passed. +- More than one `from` directly in one query is not supported, except when the `DefaultIfEmpty` method is used to perform left outer join. Each subsequent `from` is considered to be a separate query. + +```c# +var firstQuery = from stat in _myDbContext.Statements + where stat.Count > 2 + select new { stat.Count }; + +var secondQuery = from item in _myDbContext.Items + where item.Price > 6 + select new { item.Name }; + +var finalQuery = from first in firstQuery + from second in secondQuery + select new { first.Count, second.Name }; + +// 1. firstQuery will be executed against the cluster. +// 2. secondQuery will be executed against the cluster for each object (row) from 1. +// 3. finalQuery will be executed locally with the results from 1 and 2. +var result = finalQuery.ToArray(); +``` + +- Method calls are not supported inside `OrderBy`/`OrderByDescending` or `ThenBy`/`ThenByDescending`. +- Only overloads of `Contains`, `StartsWith`, and `EndsWith` methods that have a single string argument are supported inside `Where` and `First`/`FirstOrDefault`. + +## Modify data in a cluster by using `ScalarDbContext` + +The properties of the class inherited from `ScalarDbContext` can be used to modify data. + +### Add a new object by using the `AddAsync` method + +```c# +var statement = new Statement + { + OrderId = "2", + ItemId = 4, + Count = 8 + }; +await _myDbContext.Statements.AddAsync(statement); +``` + +### Update an object by using the `UpdateAsync` method + +```c# +var statement = _myDbContext.Statements.First(stat => stat.Id == 1); + +// ... + +statement.Count = 10; +await _myDbContext.Statements.UpdateAsync(statement); +``` + +### Remove an object by using the `RemoveAsync` method + +```c# +var statement = _myDbContext.Statements.First(stat => stat.Id == 1); + +// ... + +await _myDbContext.Statements.RemoveAsync(statement); +``` + +## Manage transactions + +LINQ queries and `AddAsync`, `UpdateAsync`, and `RemoveAsync` methods can be executed without an explicitly started transaction. However, to execute multiple queries and methods as part of a single transaction, the transaction must be explicitly started and committed. `ScalarDbContext` supports both ordinary transactions and transactions with the two-phase commit interface in ScalarDB. + +### Begin a new transaction + +```c# +await _myDbContext.BeginTransactionAsync(); +``` + +### Begin a new transaction with the two-phase commit interface + +```c# +await _myDbContext.BeginTwoPhaseCommitTransactionAsync(); +``` + +### Get the ID of a currently active transaction + +```c# +var transactionId = _myDbContext.CurrentTransactionId; +``` + +### Join an existing transaction with the two-phase commit interface + +```c# +await _myDbContext.JoinTwoPhaseCommitTransactionAsync(transactionId); +``` + +### Resume an existing transaction + +```c# +await _myDbContext.ResumeTransaction(transactionId); +``` + +### Resume an existing transaction with the two-phase commit interface + +```c# +await _myDbContext.ResumeTwoPhaseCommitTransaction(transactionId); +``` + +:::note + +The `ResumeTransaction`/`ResumeTwoPhaseCommitTransaction` methods don't have asynchronous versions because they only initialize the transaction data in the `ScalarDbContext` inheriting object without querying the cluster. Because of this, resuming a transaction by using the wrong ID is possible. + +::: + +### Commit a transaction (ordinary or two-phase commit) + +```c# +await _myDbContext.CommitTransactionAsync(); +``` + +### Roll back a transaction (ordinary or two-phase commit) + +```c# +await _myDbContext.RollbackTransactionAsync(); +``` + +### Prepare a transaction with the two-phase commit interface for the commit + +```c# +await _myDbContext.PrepareTransactionAsync(); +``` + +### Validate a transaction with the two-phase commit interface before the commit + +```c# +await _myDbContext.ValidateTransactionAsync(); +``` diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-scalardb-tables-as-csharp-classes.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-scalardb-tables-as-csharp-classes.mdx new file mode 100644 index 00000000..3b6357ab --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-scalardb-tables-as-csharp-classes.mdx @@ -0,0 +1,204 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Tables as C# Classes in the ScalarDB Cluster .NET Client SDK + +The ScalarDB Cluster .NET Client SDK helps you write code to access a cluster by abstracting ScalarDB tables as C# objects. After defining a class that represents a table in the cluster, you can ensure that a column name or its type won't be mixed up when querying the cluster. In addition, if a table's structure changes, you can apply the changes to the code by using the refactoring feature in your IDE. + +:::note + +Although we recommend using asynchronous methods, as in the following examples, you can use synchronous methods instead. + +::: + +## Install the SDK + +Install the same major and minor version of the [SDK](https://www.nuget.org/packages/ScalarDB.Client) as ScalarDB Cluster into the .NET project. You can do this by using the built-in NuGet package manager, replacing `.` with the version that you're using: + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## Create classes for all ScalarDB tables + +To work with ScalarDB tables as C# objects, you must create a class for each table that you want to use. For example: + +```c# +using System.ComponentModel.DataAnnotations.Schema; +using ScalarDB.Client.DataAnnotations; + +// ... + +[Table("ns.statements")] +public class Statement +{ + [PartitionKey] + [Column("order_id", Order = 0)] + public string OrderId { get; set; } = String.Empty; + + [ClusteringKey] + [Column("item_id", Order = 1)] + public int ItemId { get; set; } + + [Column("count", Order = 2)] + public int Count { get; set; } +} +``` + +For details about which types should be used for properties, see [How ScalarDB Column Types Are Converted to and from .NET Types](common-reference.mdx#how-scalardb-column-types-are-converted-to-and-from-net-types). + +## Execute CRUD operations + +After creating a class for each table, you can use the classes as objects by using the generic `GetAsync`, `ScanAsync`, `InsertAsync`, `UpdateAsync`, `DeleteAsync`, `UpsertAsync`, or `MutateAsync` method of `ITransactionCrudOperable`. + +To use these generic methods, add the following namespace to the `using` section: + +```c# +using ScalarDB.Client.Extensions; +``` + +### Get one object by using the `GetAsync` method + +```c# +var keys = new Dictionary + { + { nameof(Statement.OrderId), "1" } + }; +var statement = await transaction.GetAsync(keys); + +Console.WriteLine($"ItemId: {statement.ItemId}, Count: {statement.Count}"); +``` + +### Get multiple objects by using the `ScanAsync` method + +```c# +var startKeys = new Dictionary + { + { nameof(Statement.OrderId), "1" }, + { nameof(Statement.ItemId), 3 } + }; +var endKeys = new Dictionary + { + { nameof(Statement.ItemId), 6} + }; + +await foreach (var s in transaction.ScanAsync(startKeys, endKeys)) + Console.WriteLine($"ItemId: {s.ItemId}, Count: {s.Count}"); +``` + +:::note + +To use LINQ methods with `IAsyncEnumerable`, you can install [System.Linq.Async](https://www.nuget.org/packages/System.Linq.Async/) package. + +::: + +### Insert a new object by using the `InsertAsync` method + +```c# +var statement = new Statement + { + OrderId = "2", + ItemId = 4, + Count = 8 + }; +await transaction.InsertAsync(statement); +``` + +### Update an object by using the `UpdateAsync` method + +```c# +// ... +statement.ItemId = 4; +statement.Count = 8; + +await transaction.UpdateAsync(statement); +``` + +### Delete an object by using the `DeleteAsync` method + +```c# +// ... +await transaction.DeleteAsync(statement); +``` + +### Upsert an object by using the `UpsertAsync` method + +```c# +var statement = new Statement + { + OrderId = "2", + ItemId = 4, + Count = 8 + }; +await transaction.UpsertAsync(statement); +``` + +### Upsert and delete multiple objects at once by using the `MutateAsync` method + +```c# +var statement = new Statement + { + OrderId = "2", + ItemId = 4, + Count = 16 + }; + +// ... + +await transaction.MutateAsync(objectsToUpsert: new[] { statement }, + objectsToDelete: new[] { statement2 }); +``` + +:::note + +To modify objects by using the `UpdateAsync`, `DeleteAsync`, `UpsertAsync`, or `MutateAsync` method, the objects must be retrieved first by using the `GetAsync` or `ScanAsync` method. + +::: + +## Use the Administrative API + +C# objects also can be used with the Administrative API. To use generic Administrative API methods, add the following namespace to the `using` section: + +```c# +using ScalarDB.Client.Extensions; +``` + +### Create a new namespace + +```c# +await admin.CreateNamespaceAsync(); +``` + +### Drop an existing namespace + +```c# +await admin.DropNamespaceAsync(); +``` + +### Check if a namespace exists + +```c# +var namespaceExists = await admin.IsNamespacePresentAsync(); +``` + +### Create a new table + +```c# +await admin.CreateTableAsync(); +``` + +### Drop an existing table + +```c# +await admin.DropTableAsync(); +``` + +### Check if a table exists + +```c# +var tableExists = await admin.IsTablePresentAsync(); +``` diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx new file mode 100644 index 00000000..7a684b2c --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx @@ -0,0 +1,142 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Distributed Transactions with a Two-Phase Commit Interface in the ScalarDB Cluster .NET Client SDK + +The ScalarDB Cluster .NET Client SDK supports transactions with the two-phase commit interface in ScalarDB. The SDK includes transaction and manager abstractions for enhanced communication within a cluster. + +:::note + +Although we recommend using asynchronous methods as in the following examples, you can use synchronous methods instead. + +::: + +## About transactions with the two-phase commit interface + +By using the SDK, you can execute transactions with the two-phase commit interface that span multiple applications. For example, if you have multiple microservices, you can create a transaction manager in each of them and execute a transaction that spans those microservices. + +In transactions with the two-phase commit interface, there are two roles—coordinator and a participant—that collaboratively execute a single transaction. + +The coordinator process first begins a transaction and sends the ID of the transaction to all the participants, and the participant processes join the transaction. After executing CRUD or SQL operations, the coordinator process and the participant processes commit the transaction by using the two-phase interface. + +## Install the SDK + +Install the same major and minor version of the [SDK](https://www.nuget.org/packages/ScalarDB.Client) as ScalarDB Cluster into the .NET project. You can do this by using the built-in NuGet package manager, replacing `.` with the version that you're using: + +```console +dotnet add package ScalarDB.Client --version '..*' +``` + +## Create a settings file + +Create a `scalardb-options.json` file and add the following, replacing `` with the FQDN or the IP address, and `` with the port number (`60053` by default) of your cluster: + +```json +{ + "ScalarDbOptions": { + "Address": "http://:", + "HopLimit": 10 + } +} +``` + +For details about settings files and other ways to configure the client, see [Client configuration](common-reference.mdx#client-configuration). + +## Get a transaction manager (for coordinator and participants) + +You need to get a transaction manager for distributed transactions with the two-phase commit interface. To get the transaction manager, you can use `TransactionFactory` as follows: + +```c# +// Pass the path to the settings file created in the previous step. +var factory = TransactionFactory.Create("scalardb-options.json"); + +using var manager = factory.GetTwoPhaseCommitTransactionManager(); +``` + +Alternatively, you can use SQL instead of CRUD operations for transactions with the two-phase commit interface by specifying the following transaction manager: + +```c# +using var manager = factory.GetSqlTwoPhaseCommitTransactionManager(); +``` + +## Begin a transaction (for coordinator) + +You can begin a transaction with the two-phase commit interface in the coordinator as follows: + +```c# +var transaction = await manager.BeginAsync(); +``` + +The ID of the started transaction can be obtained with the following code: + +```c# +var transactionId = transaction.Id; +``` + +## Join a transaction (for participants) + +You can join a transaction with the two-phase commit interface in a participant as follows: + +```c# +var transaction = await manager.JoinAsync(transactionId); +``` + +## Resume a transaction (for coordinator and participants) + +Usually, a transaction with the two-phase commit interface involves multiple request and response exchanges. In scenarios where you need to work with a transaction that has been begun or joined in the previous request, you can resume such transaction as follows: + +```c# +var transaction = manager.Resume(transactionId); +``` + +:::note + +The `Resume` method doesn't have an asynchronous version because it only creates a transaction object. Because of this, resuming a transaction by using the wrong ID is possible. + +::: + +## Roll back a transaction + +If a transaction fails to commit, you can roll back the transaction as follows: + +```c# +await transaction.RollbackAsync(); +``` + +## Commit a transaction (for coordinator and participants) + +After completing CRUD or SQL operations, you must commit the transaction. However, for transactions with the two-phase commit interface, you must prepare the transaction in the coordinator and all the participants first. + +```c# +await transaction.PrepareAsync(); +``` + +Next, depending on the concurrency control protocol, you may need to validate the transaction in the coordinator and all the participants as follows: + +```c# +await transaction.ValidateAsync(); +``` + +Finally, you can commit the transaction in the coordinator and all the participants as follows: + +```c# +await transaction.CommitAsync(); +``` + +If the coordinator or any of the participants failed to prepare or validate the transaction, you will need to call `RollbackAsync` in the coordinator and all the participants. + +In addition, if the coordinator and all the participants failed to commit the transaction, you will need to call `RollbackAsync` in the coordinator and all the participants. + +However, if the coordinator or only some of the participants failed to commit the transaction, the transaction will be regarded as committed as long as the coordinator or any one of the participants has succeeded in committing the transaction. + +## Execute CRUD operations + +The two-phase commit interface of the transaction has the same methods for CRUD operations as ordinary transactions. For details, see [Execute CRUD operations](getting-started-with-distributed-transactions.mdx#execute-crud-operations). + +## Execute SQL statements + +The two-phase commit interface of the SQL transaction has the same methods for executing SQL queries as ordinary SQL transactions. For details, see [Execute SQL queries](getting-started-with-distributed-sql-transactions.mdx#execute-sql-queries). diff --git a/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/index.mdx b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/index.mdx new file mode 100644 index 00000000..f2562631 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster-dotnet-client-sdk/index.mdx @@ -0,0 +1,22 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster .NET Client SDK Overview + +The ScalarDB Cluster .NET Client SDK enables applications to connect to ScalarDB Cluster by using gRPC. + +To use the ScalarDB Cluster .NET Client SDK, see the following getting started guides: + +* [Getting Started with Distributed Transactions](getting-started-with-distributed-transactions.mdx) +* [Getting Started with Distributed SQL Transactions](getting-started-with-distributed-sql-transactions.mdx) +* [Getting Started with the Administrative API](getting-started-with-admin-api.mdx) +* [Getting Started with ScalarDB Tables as C# Classes](getting-started-with-scalardb-tables-as-csharp-classes.mdx) +* [Getting Started with ASP.NET Core and Dependency Injection](getting-started-with-aspnet-and-di.mdx) +* [Getting Started with LINQ](getting-started-with-linq.mdx) +* [Getting Started with Distributed Transactions with a Two-Phase Commit Interface](getting-started-with-two-phase-commit-transactions.mdx) +* [Getting Started with Authentication and Authorization](getting-started-with-auth.mdx) +* [Exception Handling](exception-handling.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/authorize-with-abac.mdx b/versioned_docs/version-3.15/scalardb-cluster/authorize-with-abac.mdx new file mode 100644 index 00000000..7bffd58c --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/authorize-with-abac.mdx @@ -0,0 +1,27 @@ +--- +tags: + - Enterprise Premium Option + - Private Preview +displayed_sidebar: docsEnglish +--- + +# Control User Access in a Fine-Grained Manner + +:::info + +- This feature is currently available only to customers in Japan. If you're a customer in Japan, please see the Japanese version of this page. +- If you need more details about this feature in English, please [contact support](https://www.scalar-labs.com/support). + +::: + +ScalarDB Cluster can authorize users in a fine-grained manner with a mechanism called attributed-based access control (ABAC). This page explains how to use ABAC in ScalarDB Cluster. + +## What is ABAC? + +ABAC is a fine-grained access control mechanism in ScalarDB Cluster, allowing for record-level access control instead of just table-level access control, done through [simple authorization](./scalardb-auth-with-sql.mdx). With ABAC, a user can access a particular record only if the user's attributes and the record's attributes match. For example, you can restrict access to some highly confidential records to only users with the required privileges. This mechanism is also useful when multiple applications share the same table but need to access different segments based on their respective privileges. + +## Why use ABAC? + +Enterprise databases often provide row-level security or similar alternatives to allow for controlling access to rows in a database table. However, if a system comprises several databases, you need to configure each database one by one in the same way. If different kinds of databases are used, you have to configure each database by understanding the differences in the capabilities of each database. Such configuration causes too much burden and is error-prone. With ABAC, you can just configure it once, even though you manage several databases under ScalarDB. + +Row-level security features in most databases often require you to implement matching logic through functions like stored procedures. This can sometimes lead to writing lots of code to achieve the desired logic, which can become burdensome. In contrast, ABAC allows you to configure matching logic by using attributes known as tags. With ABAC, you only need to define these tags and assign them to users and records, eliminating the need for coding. Tags consist of several components that enable you to specify matching logic in a flexible and straightforward manner. diff --git a/versioned_docs/version-3.15/scalardb-cluster/compatibility.mdx b/versioned_docs/version-3.15/scalardb-cluster/compatibility.mdx new file mode 100644 index 00000000..0b469206 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/compatibility.mdx @@ -0,0 +1,48 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster Compatibility Matrix + +This document shows the compatibility of ScalarDB Cluster versions among client SDK versions. + +## ScalarDB Cluster compatibility with client SDKs + +| ScalarDB Cluster version | ScalarDB Cluster Java Client SDK version | ScalarDB Cluster .NET Client SDK version | +|:-------------------------|:-----------------------------------------|:-----------------------------------------| +| 3.15 | 3.9 - 3.15 | 3.12* - 3.15 | +| 3.14 | 3.9 - 3.14 | 3.12* - 3.14 | +| 3.13 | 3.9 - 3.13 | 3.12* - 3.13 | +| 3.12 | 3.9 - 3.12 | 3.12* | +| 3.11 | 3.9 - 3.11 | Not supported | +| 3.10 | 3.9 - 3.10 | Not supported | +| 3.9 | 3.9 | Not supported | + +\* This version is in private preview, which means that future versions might have backward-incompatible updates. + +:::note + +- You can consider the client tools (for example, [ScalarDB Cluster SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli) and [ScalarDB Cluster Schema Loader](developer-guide-for-scalardb-cluster-with-java-api.mdx#schema-loader-for-cluster)) to be the same as the ScalarDB Cluster Java Client SDK. In other words, you can apply the same compatibility rules to client tools as the ScalarDB Cluster Java Client SDK. +- When you access backend databases by using ScalarDB Data Loader, you must use a version of ScalarDB Data Loader that is compatible with the version of ScalarDB Cluster that you're using. In this case, the supported version of ScalarDB Data Loader is the same as the version of the ScalarDB Cluster Java Client SDK shown in the matrix above. Note that ScalarDB Data Loader doesn't access ScalarDB Cluster directly. +- If you use a new feature that ScalarDB Cluster provides in a new minor version, you may need to use the same or a later version of the client tools or re-create (or update) existing schemas. For details, please refer to the relevant documentation about each feature. + +::: + +## Version skew policy + +:::note + +Versions are expressed as `x.y.z`, where `x` represents the major version, `y` represents the minor version, and `z` represents the patch version. This format follows [Semantic Versioning](https://semver.org/). + +::: + +- If the **major** versions are different between ScalarDB Cluster and a client SDK, they are **not** compatible and are **not** supported. +- If the **major** versions are the same and the **minor** versions are different between ScalarDB Cluster and a client SDK, the version of ScalarDB Cluster must be greater than or equal to the client SDK version. For example: + - **Supported:** Combination of ScalarDB Cluster 3.13 and client SDK 3.11 + - **Not supported:** Combination of ScalarDB Cluster 3.11 and client SDK 3.13 +- If the **major** versions and the **minor** versions are the same, you can use different **patch** versions between ScalarDB Cluster and a client SDK. For example: + - **Supported:** Combination of ScalarDB Cluster 3.13.2 and client SDK 3.13.0 + - **Supported:** Combination of ScalarDB Cluster 3.13.0 and client SDK 3.13.2 diff --git a/versioned_docs/version-3.15/scalardb-cluster/deployment-patterns-for-microservices.mdx b/versioned_docs/version-3.15/scalardb-cluster/deployment-patterns-for-microservices.mdx new file mode 100644 index 00000000..d86a2d55 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/deployment-patterns-for-microservices.mdx @@ -0,0 +1,72 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster Deployment Patterns for Microservices + +When building microservice applications that use ScalarDB Cluster, there are two patterns you can choose for how to deploy ScalarDB Cluster: shared-cluster pattern and separated-cluster pattern. +This document first explains those patterns, how they differ, and the basic guidelines on which one to choose in which cases. + +Also, this document assumes that your microservice applications are created based on the database-per-service pattern, where each microservice manages its database, and a microservice needs to access another microservice's database via APIs between the microservices. + +## ScalarDB Cluster deployment patterns + +In the shared-cluster pattern, microservices share one ScalarDB Cluster instance, which is a cluster of ScalarDB Cluster nodes, in a system, so they access the same ScalarDB Cluster instance to interact with their databases. On the other hand, in the separated-cluster pattern, microservices use several ScalarDB Cluster instances. Typically, one microservice accesses one ScalarDB Cluster instance to interact with its database. + +The following diagram shows the patterns. (MS stands for microservice.) + +![ScalarDB Cluster deployment patterns for microservices.](images/scalardb-deployment-patterns.png) + +:::note + +You also need to manage the Coordinator table in either pattern in addition to the databases required for microservices. + +::: + +## Pros and cons + +One obvious difference is the amount of resources for ScalarDB Cluster instances. With the separated-cluster pattern, you need more resources to manage your applications. This also incurs more maintenance burden and costs. + +In addition, the ScalarDB Cluster APIs that you would need to use are different. Specifically, for the shared-cluster pattern, you need to use the [one-phase commit interface](../api-guide.mdx#transactional-api), where only one microservice needs to call `commit` to commit a transaction after microservices read and write records. For the separated-cluster pattern, you need to use the [two-phase commit interface](../two-phase-commit-transactions.mdx), where all the microservices first need to call `prepare` and then call `commit` if all the prepare calls are successful. Therefore, microservices with the separated-cluster pattern will likely be more complex than microservices with the shared-cluster pattern because they need to handle transactions and their errors in a more fine-grained manner. + +Moreover, the level of resource isolation is different. Microservices should be well-isolated for better maintainability and development efficiency, but the shared-cluster pattern brings weaker resource isolation. Weak resource isolation might also bring weak security. However, security risks can be mitigated by using the security features of ScalarDB Cluster, like authentication and authorization. + +Similarly, there is a difference in how systems are administrated. Specifically, in the shared-cluster pattern, a team must be tasked with managing a ScalarDB Cluster instance on behalf of the other teams. Typically, the central data team can manage it, but issues may arise if no such team exists. With the separated-cluster pattern, administration is more balanced but has a similar issue for the Coordinator table. The issue can be addressed by having a microservice for coordination and making a team manage the microservice. + +The following is a summary of the pros and cons of the patterns. + +### Shared-cluster pattern + +- **Pros:** + - Simple transaction and error handling because of the one-phase commit interface. (Backup operations for databases can also be simple.) + - Less resource usage because it uses one ScalarDB Cluster instance. +- **Cons:** + - Weak resource isolation between microservices. + - Unbalanced administration. (One team needs to manage a ScalarDB Cluster instance on behalf of the others.) + +### Separated-cluster pattern + +- **Pros:** + - Better resource isolation. + - More balanced administration. (A team manages one microservice and one ScalarDB Cluster instance. Also, a team must be tasked with managing the Coordinator table.) +- **Cons:** + - Complex transaction and error handling due to the two-phase commit interface. (Backup operations for databases can also be complex.) + - More resource usage because of several ScalarDB Cluster instances. + +## Which pattern to choose + +Using the shared-cluster pattern is recommended whenever possible. Although the shared-cluster pattern has some disadvantages, as described above, its simplicity and ease of management outweigh those disadvantages. Moreover, since ScalarDB Cluster stores all critical states in their underlying databases and does not hold any critical states in its memory, it can be seen as just a path to the databases. Therefore, we believe a system with the shared-cluster pattern still complies with the database-per-service pattern and does not violate the microservice philosophy much. + +If the cons of the shared-cluster pattern are not acceptable, you can still use the separated-cluster pattern. However, you should use that pattern only if you properly understand the mechanism and usage of the two-phase commit interface. Otherwise, you might face some issues, like database anomalies. + +## Limitations + +ScalarDB provides several APIs, such as CRUD, SQL, and Spring Data JDBC. Although the CRUD and SQL interfaces support both the shared-cluster and separated-cluster patterns, the Spring Data JDBC interface does not support the shared-cluster pattern. This is because its one-phase commit interface currently assumes an application is monolithic, where it is not divided into microservices that interact with each other. The Spring Data JDBC interface supports the two-phase commit interface and the separated-cluster pattern, just as the other APIs do. + +## See also + +- [Transactions with a Two-Phase Commit Interface](../two-phase-commit-transactions.mdx) + diff --git a/versioned_docs/version-3.15/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx b/versioned_docs/version-3.15/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx new file mode 100644 index 00000000..964f3316 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx @@ -0,0 +1,261 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Developer Guide for ScalarDB Cluster with the Java API + +ScalarDB Cluster provides a Java API for developing applications. +This document explains how to use the Java API. + +## Add ScalarDB Cluster Java Client SDK to your build + +The ScalarDB Cluster Java Client SDK is available in the [Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-cluster-java-client-sdk). + +To add a dependency on the ScalarDB Cluster Java Client SDK by using Gradle, use the following: + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' +} +``` + +To add a dependency by using Maven, use the following: + +```xml + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + +``` + +## Client modes + +The ScalarDB Cluster Java Client SDK supports two client modes: `indirect` and `direct-kubernetes`. The following describes the client modes. + +### `indirect` client mode + +This mode simply sends a request to any cluster node (typically via a load balancer, such as Envoy), and the cluster node receiving the request routes the request to the appropriate cluster node that has the transaction state. + +![ScalarDB Cluster architecture](images/indirect-client-mode.png) + +The advantage of this mode is that we can keep the client thin. +The disadvantage is that we need an additional hop to reach the correct cluster node, which may affect performance. + +You can use this connection mode even if your application is running on a different Kubernetes cluster and your application can't access the Kubernetes API and each cluster node. +If your application is running on the same Kubernetes cluster as your ScalarDB Cluster nodes, you can use the `direct-kubernetes` client mode. + +### `direct-kubernetes` client mode + +In this mode, the client uses the membership logic (using the Kubernetes API) and the distribution logic (consistent hashing algorithm) to find the right cluster node that has the transaction state. +The client then sends a request to the cluster node directly. + +![ScalarDB Cluster architecture](images/direct-kubernetes-client-mode.png) + +The advantage of this mode is that we can reduce the hop count to reach the proper cluster node, which will improve the performance. +The disadvantage of this mode is that we need to make the client fat because the client needs to have membership logic and request-routing logic. + +Since this connection mode needs to access the Kubernetes API and each cluster node, you can use this connection mode only if your application is running on the same Kubernetes cluster as your ScalarDB Cluster nodes. +If your application is running on a different Kubernetes cluster, use the `indirect` client mode. + +For details about how to deploy your application on Kubernetes with `direct-kubernetes` client mode, see [Deploy your client application on Kubernetes with `direct-kubernetes` mode](../helm-charts/how-to-deploy-scalardb-cluster.mdx#deploy-your-client-application-on-kubernetes-with-direct-kubernetes-mode). + +## ScalarDB Cluster Java API + +The ScalarDB Cluster Java Client SDK provides a Java API for applications to access ScalarDB Cluster. The following diagram shows the architecture of the ScalarDB Cluster Java API. + +``` + +------------------+ + | User/Application | + +------------------+ + ↓ Java API + +--------------+ + | ScalarDB API | + +--------------+ + ↓ gRPC + +------------------+ + | ScalarDB Cluster | + +------------------+ + ↓ DB vendor–specific protocol + +----+ + | DB | + +----+ +``` + +Using the ScalarDB Cluster Java API is almost the same as using the ScalarDB Java API except the client configurations and Schema Loader are different. +For details, see [ScalarDB Java API Guide](../api-guide.mdx). + +The following section describes the Schema Loader for ScalarDB Cluster. + +### Schema Loader for Cluster + +To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). +Using the Schema Loader for Cluster is basically the same as using the [ScalarDB Schema Loader](../schema-loader.mdx) except the name of the JAR file is different. +You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). +After downloading the JAR file, you can run Schema Loader for Cluster with the following command: + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config --schema-file --coordinator +``` + +You can also pull the Docker image from the [Scalar container registry](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-schema-loader) by running the following command, replacing the contents in the angle brackets as described: + +```console +docker run --rm -v :/scalardb.properties -v :/schema.json ghcr.io/scalar-labs/scalardb-cluster-schema-loader:3.15.4 --config /scalardb.properties --schema-file /schema.json --coordinator +``` + +## ScalarDB Cluster SQL + +ScalarDB Cluster SQL can be accessed via JDBC and Spring Data JDBC for ScalarDB in Java as follows: + +``` + +-----------------------------------------+ + | User/Application | + +-----------------------------------------+ + ↓ ↓ Java API +Java API ↓ +-------------------------------+ + (JDBC) ↓ | Spring Data JDBC for ScalarDB | + ↓ +-------------------------------+ ++----------------------------------------------+ +| ScalarDB JDBC (ScalarDB SQL) | ++----------------------------------------------+ + ↓ gRPC + +----------------------+ + | ScalarDB Cluster SQL | + +----------------------+ + ↓ DB vendor–specific protocol + +----+ + | DB | + +----+ +``` + +This section describes how to use ScalarDB Cluster SQL though JDBC and Spring Data JDBC for ScalarDB. + +### ScalarDB Cluster SQL via JDBC + +Using ScalarDB Cluster SQL via JDBC is almost the same using [ScalarDB JDBC](../scalardb-sql/jdbc-guide.mdx) except for how to add the JDBC driver to your project. + +In addition to adding the ScalarDB Cluster Java Client SDK as described in [Add ScalarDB Cluster Java Client SDK to your build](#add-scalardb-cluster-java-client-sdk-to-your-build), you need to add the following dependencies to your project: + +To add the dependencies on the ScalarDB Cluster JDBC driver by using Gradle, use the following: + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql-jdbc:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' +} +``` + +To add the dependencies by using Maven, use the following: + +```xml + + + com.scalar-labs + scalardb-sql-jdbc + 3.15.4 + + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + +``` + +Other than that, using ScalarDB Cluster SQL via JDBC is the same as using ScalarDB JDBC. +For details about ScalarDB JDBC, see [ScalarDB JDBC Guide](../scalardb-sql/jdbc-guide.mdx). + +### ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB + +Similar to ScalarDB Cluster SQL via JDBC, using ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB is almost the same as using [Spring Data JDBC for ScalarDB](../scalardb-sql/spring-data-guide.mdx) except for how to add it to your project. + +In addition to adding the ScalarDB Cluster Java Client SDK as described in [Add ScalarDB Cluster Java Client SDK to your build](#add-scalardb-cluster-java-client-sdk-to-your-build), you need to add the following dependencies to your project: + +To add the dependencies by using Gradle, use the following: + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql-spring-data:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' +} +``` + +To add the dependencies by using Maven, use the following: + +```xml + + + com.scalar-labs + scalardb-sql-spring-data + 3.15.4 + + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + +``` + +Other than that, using ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB is the same as using Spring Data JDBC for ScalarDB. +For details about Spring Data JDBC for ScalarDB, see [Guide of Spring Data JDBC for ScalarDB](../scalardb-sql/spring-data-guide.mdx). + +### SQL CLI + +Like other SQL databases, ScalarDB SQL also provides a CLI tool where you can issue SQL statements interactively in a command-line shell. + +You can download the SQL CLI for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can run the SQL CLI with the following command: + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config +``` + +You can also pull the Docker image from the [Scalar container registry](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-cluster-sql-cli) by running the following command, replacing the contents in the angle brackets as described: + +```console +docker run --rm -it -v :/scalardb-sql.properties ghcr.io/scalar-labs/scalardb-cluster-sql-cli:3.15.4 --config /scalardb-sql.properties +``` + +#### Usage + +You can see the CLI usage with the `-h` option as follows: + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar -h +Usage: scalardb-sql-cli [-hs] -c=PROPERTIES_FILE [-e=COMMAND] [-f=FILE] + [-l=LOG_FILE] [-o=] [-p=PASSWORD] + [-u=USERNAME] +Starts ScalarDB SQL CLI. + -c, --config=PROPERTIES_FILE + A configuration file in properties format. + -e, --execute=COMMAND A command to execute. + -f, --file=FILE A script file to execute. + -h, --help Display this help message. + -l, --log=LOG_FILE A file to write output. + -o, --output-format= + Format mode for result display. You can specify + table/vertical/csv/tsv/xmlattrs/xmlelements/json/a + nsiconsole. + -p, --password=PASSWORD A password to connect. + -s, --silent Reduce the amount of informational messages + displayed. + -u, --username=USERNAME A username to connect. +``` + +## Further reading + +If you want to use ScalarDB Cluster in programming languages other than Java, you can use the ScalarDB Cluster gRPC API. +For details about the ScalarDB Cluster gRPC API, refer to the following: + +* [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +* [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) + +JavaDocs are also available: + +* [ScalarDB Cluster Java Client SDK](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-java-client-sdk/3.15.4/index.html) +* [ScalarDB Cluster Common](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-common/3.15.4/index.html) +* [ScalarDB Cluster RPC](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-rpc/3.15.4/index.html) diff --git a/versioned_docs/version-3.15/scalardb-cluster/encrypt-data-at-rest.mdx b/versioned_docs/version-3.15/scalardb-cluster/encrypt-data-at-rest.mdx new file mode 100644 index 00000000..ea2389fa --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/encrypt-data-at-rest.mdx @@ -0,0 +1,325 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Encrypt Data at Rest + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This document explains how to encrypt data at rest in ScalarDB. + +## Overview + +ScalarDB can encrypt data stored through it. The encryption feature is similar to transparent data encryption (TDE) in major database systems; therefore, it is transparent to applications. ScalarDB encrypts data before writing it to the backend databases and decrypts it when reading from them. + +Currently, ScalarDB supports column-level encryption, allowing specific columns in a table to be encrypted. + +## Configurations + +To enable the encryption feature, you need to configure `scalar.db.cluster.encryption.enabled` to `true` in the ScalarDB Cluster node configuration file. + +| Name | Description | Default | +|----------------------------------------|-----------------------------------------|---------| +| `scalar.db.cluster.encryption.enabled` | Whether ScalarDB encrypts data at rest. | `false` | + +:::note + +Since encryption is transparent to the client, you don't need to change the client configuration. + +::: + +:::note + +If you enable the encryption feature, you will also need to set `scalar.db.cross_partition_scan.enabled` to `true` for the system namespace (`scalardb` by default) because it performs cross-partition scans internally. + +::: + +The other configurations depend on the encryption implementation you choose. Currently, ScalarDB supports the following encryption implementations: + +- HashiCorp Vault encryption +- Self-encryption + +The following sections explain how to configure each encryption implementation. + +### HashiCorp Vault encryption + +In HashiCorp Vault encryption, ScalarDB uses the [encryption as a service](https://developer.hashicorp.com/vault/tutorials/encryption-as-a-service/eaas-transit) of HashiCorp Vault to encrypt and decrypt data. In this implementation, ScalarDB delegates the management of encryption keys, as well as the encryption and decryption of data, to HashiCorp Vault. + +To use HashiCorp Vault encryption, you need to set the property `scalar.db.cluster.encryption.type` to `vault` in the ScalarDB Cluster node configuration file: + +| Name | Description | Default | +|-------------------------------------|-------------------------------------------------------------|---------| +| `scalar.db.cluster.encryption.type` | Should be set to `vault` to use HashiCorp Vault encryption. | | + +You also need to configure the following properties: + +| Name | Description | Default | +|------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------| +| `scalar.db.cluster.encryption.vault.key_type` | The key type. Currently, `aes128-gcm96`, `aes256-gcm96`, and `chacha20-poly1305` are supported. For details about the key types, see [Key types](https://developer.hashicorp.com/vault/docs/secrets/transit#key-types). | `aes128-gcm96` | +| `scalar.db.cluster.encryption.vault.associated_data_required` | Whether associated data is required for AEAD encryption. | `false` | +| `scalar.db.cluster.encryption.vault.address` | The address of the HashiCorp Vault server. | | +| `scalar.db.cluster.encryption.vault.token` | The token to authenticate with HashiCorp Vault. | | +| `scalar.db.cluster.encryption.vault.namespace` | The namespace of the HashiCorp Vault. This configuration is optional. | | +| `scalar.db.cluster.encryption.vault.transit_secrets_engine_path` | The path of the transit secrets engine. | `transit` | +| `scalar.db.cluster.encryption.vault.column_batch_size` | The number of columns to be included in a single request to the HashiCorp Vault server. | `64` | + +### Self-encryption + +In self-encryption, ScalarDB manages data encryption keys (DEKs) and performs encryption and decryption. ScalarDB generates a DEK for each table when creating the table and stores it in Kubernetes Secrets. + +To use self-encryption, you need to set the property `scalar.db.cluster.encryption.type` to `self` in the ScalarDB Cluster node configuration file: + +| Name | Description | Default | +|-------------------------------------|-------------------------------------------------|---------| +| `scalar.db.cluster.encryption.type` | Should be set to `self` to use self-encryption. | | + +You also need to configure the following properties: + +| Name | Description | Default | +|-------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| +| `scalar.db.cluster.encryption.self.key_type` | The key type. Currently, `AES128_GCM`, `AES256_GCM`, `AES128_EAX`, `AES256_EAX`, `AES128_CTR_HMAC_SHA256`, `AES256_CTR_HMAC_SHA256`, `CHACHA20_POLY1305`, and `XCHACHA20_POLY1305` are supported. For details about the key types, see [Choose a key type](https://developers.google.com/tink/aead#choose_a_key_type). | `AES128_GCM` | +| `scalar.db.cluster.encryption.self.associated_data_required` | Whether associated data is required for AEAD encryption. | `false` | +| `scalar.db.cluster.encryption.self.kubernetes.secret.namespace_name` | The namespace name of the Kubernetes Secrets. | `default` | +| `scalar.db.cluster.encryption.self.data_encryption_key_cache_expiration_time` | The expiration time of the DEK cache in milliseconds. | `60000` (60 seconds) | + +### Delete the DEK when dropping a table + +By default, ScalarDB does not delete the data encryption key (DEK) associated with a table when the table is dropped. However, you can configure ScalarDB to delete the DEK when dropping a table. To enable this, set the property `scalar.db.cluster.encryption.delete_data_encryption_key_on_drop_table.enabled` to `true` in the ScalarDB Cluster node configuration file: + +| Name | Description | Default | +|---------------------------------------------------------------------------------|------------------------------------------------------------------|---------| +| `scalar.db.cluster.encryption.delete_data_encryption_key_on_drop_table.enabled` | Whether to delete the DEK when dropping a table. | `false` | + +## Limitations + +There are some limitations to the encryption feature: + +- Primary-key columns (partition-key columns and clustering-key columns) cannot be encrypted. +- Secondary-index columns cannot be encrypted. +- Encrypted columns cannot be specified in the WHERE clauses or ORDER BY clauses. +- Encrypted columns are stored in the underlying database as the BLOB type, so encrypted columns that are larger than the maximum size of the BLOB type cannot be stored. For the maximum size of the BLOB type, see [Data-type mapping between ScalarDB and other databases](../schema-loader.mdx#data-type-mapping-between-scalardb-and-other-databases). + +## Wire encryption + +If you enable the encryption feature, enabling wire encryption to protect your data is strongly recommended, especially in production environments. For details about wire encryption, see [Encrypt Wire Communications](encrypt-wire-communications.mdx). + +## Tutorial - Encrypt data by configuring HashiCorp Vault encryption + +This tutorial explains how to encrypt data stored through ScalarDB by using HashiCorp Vault encryption. + +### Prerequisites + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This tutorial has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../requirements.mdx). + +::: + + + +### Step 1. Install HashiCorp Vault + +Install HashiCorp Vault by referring to the official HashiCorp documentation, [Install Vault](https://developer.hashicorp.com/vault/tutorials/getting-started/getting-started-install). + +### Step 2. Create the ScalarDB Cluster configuration file + +Create the following configuration file as `scalardb-cluster-node.properties`, replacing `` and `` with your ScalarDB license key and license check certificate values. For more information about the license key and certificate, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + +```properties +scalar.db.storage=jdbc +scalar.db.contact_points=jdbc:postgresql://postgresql:5432/postgres +scalar.db.username=postgres +scalar.db.password=postgres +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.cross_partition_scan.enabled=true +scalar.db.sql.enabled=true + +# Encryption configurations +scalar.db.cluster.encryption.enabled=true +scalar.db.cluster.encryption.type=vault +scalar.db.cluster.encryption.vault.address=http://vault:8200 +scalar.db.cluster.encryption.vault.token=root + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +### Step 3. Create the Docker Compose configuration file + +Create the following configuration file as `docker-compose.yaml`. + +```yaml +services: + vault: + container_name: "vault" + image: "hashicorp/vault:1.17.3" + ports: + - 8200:8200 + environment: + - VAULT_DEV_ROOT_TOKEN_ID=root + - VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200 + cap_add: + - IPC_LOCK + + postgresql: + container_name: "postgresql" + image: "postgres:15" + ports: + - 5432:5432 + environment: + - POSTGRES_PASSWORD=postgres + healthcheck: + test: ["CMD-SHELL", "pg_isready || exit 1"] + interval: 1s + timeout: 10s + retries: 60 + start_period: 30s + + scalardb-cluster-standalone: + container_name: "scalardb-cluster-node" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + ports: + - 60053:60053 + - 9080:9080 + volumes: + - ./scalardb-cluster-node.properties:/scalardb-cluster/node/scalardb-cluster-node.properties + depends_on: + postgresql: + condition: service_healthy +``` + +### Step 4. Start the HashiCorp Vault server + +Run the following command to start the HashiCorp Vault server in development mode. + +```console +docker compose up vault -d +``` + +Once the HashiCorp Vault server is running, set its environment variables by running the following commands. + +```console +export VAULT_ADDR="http://127.0.0.1:8200" +export VAULT_TOKEN=root +``` + +### Step 5. Enable the transit secrets engine on the HashiCorp Vault server + +Run the following command to enable the transit secrets engine on the HashiCorp Vault server. + +```console +vault secrets enable transit +``` + +### Step 6. Start PostgreSQL and ScalarDB Cluster + +Run the following command to start PostgreSQL and ScalarDB Cluster in standalone mode. + +```console +docker compose up postgresql scalardb-cluster-standalone -d +``` + +It may take a few minutes for ScalarDB Cluster to fully start. + +### Step 7. Connect to ScalarDB Cluster + +To connect to ScalarDB Cluster, this tutorial uses the SQL CLI, a tool for connecting to ScalarDB Cluster and executing SQL queries. You can download the SQL CLI from the [ScalarDB releases page](https://github.com/scalar-labs/scalardb/releases). + +Create a configuration file named `scalardb-cluster-sql-cli.properties`. This file will be used to connect to ScalarDB Cluster by using the SQL CLI. + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost +``` + +Then, start the SQL CLI by running the following command. + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +To begin, create the Coordinator tables required for ScalarDB transaction execution. + +```sql +CREATE COORDINATOR TABLES IF NOT EXISTS; +``` + +Now you're ready to use the database with the encryption feature enabled in ScalarDB Cluster. + +### Step 8. Create a table + +Before creating a table, you need to create a namespace. + +```sql +CREATE NAMESPACE ns; +``` + +Next, create a table. + +```sql +CREATE TABLE ns.tbl ( + id INT PRIMARY KEY, + col1 TEXT ENCRYPTED, + col2 INT ENCRYPTED, + col3 INT); +``` + +By using the `ENCRYPTED` keyword, the data in the specified columns will be encrypted. In this example, the data in `col1` and `col2` will be encrypted. + +### Step 9. Insert data into the table + +To insert data into the table, execute the following SQL query. + +```sql +INSERT INTO ns.tbl (id, col1, col2, col3) VALUES (1, 'data1', 123, 456); +``` + +To verify the inserted data, run the following SQL query. + +```sql +SELECT * FROM ns.tbl; +``` + +```console ++----+-------+------+------+ +| id | col1 | col2 | col3 | ++----+-------+------+------+ +| 1 | data1 | 123 | 456 | ++----+-------+------+------+ +``` + +### Step 10. Verify data encryption + +To verify that the data is encrypted, connect directly to PostgreSQL and check the data. + +:::warning + +Reading or writing data from the backend database directly is not supported in ScalarDB. In such a case, ScalarDB cannot guarantee data consistency. This guide accesses the backend database directly for testing purposes, however, you cannot do this in a production environment. + +::: + +Run the following command to connect to PostgreSQL. + +```console +docker exec -it postgresql psql -U postgres +``` + +Next, execute the following SQL query to check the data in the table. + +```sql +SELECT id, col1, col2, col3 FROM ns.tbl; +``` + +You should see a similar output as below, which confirms that the data in `col1` and `col2` are encrypted. + +```console + id | col1 | col2 | col3 +----+--------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------+------ + 1 | \x7661756c743a76313a6b6f76455062316a676e6a4a596b643743765539315a49714d625564545a61697152666c7967367837336e66 | \x7661756c743a76313a4b6244543162764678676d44424b526d7037794f5176423569616e615635304c473079664354514b3866513d | 456 +``` diff --git a/versioned_docs/version-3.15/scalardb-cluster/encrypt-wire-communications.mdx b/versioned_docs/version-3.15/scalardb-cluster/encrypt-wire-communications.mdx new file mode 100644 index 00000000..88dd7a97 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/encrypt-wire-communications.mdx @@ -0,0 +1,64 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Encrypt Wire Communications + +ScalarDB can encrypt wire communications by using Transport Layer Security (TLS). This document explains the configurations for wire encryption in ScalarDB. + +The wire encryption feature encrypts: + +* The communications between the ScalarDB Cluster node and clients. +* The communications between all the ScalarDB Cluster nodes (the cluster's internal communications). + +This feature uses TLS support in gRPC. For details, see the official gRPC [Security Policy](https://github.com/grpc/grpc-java/blob/master/SECURITY.md). + +:::note + +Enabling wire encryption between the ScalarDB Cluster nodes and the underlying databases in production environments is strongly recommended. For instructions on how to enable wire encryption between the ScalarDB Cluster nodes and the underlying databases, please refer to the product documentation for your underlying databases. + +::: + +## Configurations + +This section describes the available configurations for wire encryption. + +### Enable wire encryption in the ScalarDB Cluster nodes + +To enable wire encryption in the ScalarDB Cluster nodes, you need to set `scalar.db.cluster.tls.enabled` to `true`. + +| Name | Description | Default | +|---------------------------------|-------------------------------------------|---------| +| `scalar.db.cluster.tls.enabled` | Whether wire encryption (TLS) is enabled. | `false` | + +You also need to set the following configurations: + +| Name | Description | Default | +|-----------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `scalar.db.cluster.tls.ca_root_cert_pem` | The custom CA root certificate (PEM data) for TLS communication. | | +| `scalar.db.cluster.tls.ca_root_cert_path` | The custom CA root certificate (file path) for TLS communication. | | +| `scalar.db.cluster.tls.override_authority` | The custom authority for TLS communication. This doesn't change what host is actually connected. This is intended for testing, but may safely be used outside of tests as an alternative to DNS overrides. For example, you can specify the hostname presented in the certificate chain file that you set for `scalar.db.cluster.node.tls.cert_chain_path`. | | +| `scalar.db.cluster.node.tls.cert_chain_path` | The certificate chain file used for TLS communication. | | +| `scalar.db.cluster.node.tls.private_key_path` | The private key file used for TLS communication. | | + +To specify the certificate authority (CA) root certificate, you should set either `scalar.db.cluster.tls.ca_root_cert_pem` or `scalar.db.cluster.tls.ca_root_cert_path`. If you set both, `scalar.db.cluster.tls.ca_root_cert_pem` will be used. + +### Enable wire encryption on the client side + +To enable wire encryption on the client side by using the ScalarDB Cluster Java client SDK, you need to set `scalar.db.cluster.tls.enabled` to `true`. + +| Name | Description | Default | +|---------------------------------|-------------------------------------------|---------| +| `scalar.db.cluster.tls.enabled` | Whether wire encryption (TLS) is enabled. | `false` | + +You also need to set the following configurations: + +| Name | Description | Default | +|--------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `scalar.db.cluster.tls.ca_root_cert_pem` | The custom CA root certificate (PEM data) for TLS communication. | | +| `scalar.db.cluster.tls.ca_root_cert_path` | The custom CA root certificate (file path) for TLS communication. | | +| `scalar.db.cluster.tls.override_authority` | The custom authority for TLS communication. This doesn't change what host is actually connected. This is intended for testing, but may safely be used outside of tests as an alternative to DNS overrides. For example, you can specify the hostname presented in the certificate chain file that you set for `scalar.db.cluster.node.tls.cert_chain_path`. | | + +To specify the CA root certificate, you should set either `scalar.db.cluster.tls.ca_root_cert_pem` or `scalar.db.cluster.tls.ca_root_cert_path`. If you set both, `scalar.db.cluster.tls.ca_root_cert_pem` will be used. diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-dotnet.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-dotnet.mdx new file mode 100644 index 00000000..d06000d8 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-dotnet.mdx @@ -0,0 +1,439 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Cluster via .NET + +This tutorial describes how to create a sample application that uses [ScalarDB Cluster](./index.mdx) through the .NET API. + +## Overview + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit by using ScalarDB. + +:::note + +Since the focus of the sample application is to demonstrate using ScalarDB, application-specific error handling, authentication processing, and similar functions are not included in the sample application. For details about exception handling, see [Exception Handling in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/exception-handling.mdx). + +::: + +The following diagram shows the system architecture of the sample application: + +```mermaid +stateDiagram-v2 + state "Sample application using the .NET API" as SA + state "Kubernetes Cluster" as KC + state "Service (Envoy)" as SE + state "Pod" as P1 + state "Pod" as P2 + state "Pod" as P3 + state "Envoy" as E1 + state "Envoy" as E2 + state "Envoy" as E3 + state "Service (ScalarDB Cluster)" as SSC + state "ScalarDB Cluster" as SC1 + state "ScalarDB Cluster" as SC2 + state "ScalarDB Cluster" as SC3 + state "PostgreSQL" as PSQL + SA --> SE + state KC { + SE --> E1 + SE --> E2 + SE --> E3 + state P1 { + E1 --> SSC + E2 --> SSC + E3 --> SSC + } + SSC --> SC1 + SSC --> SC2 + SSC --> SC3 + state P2 { + SC1 --> PSQL + SC1 --> SC2 + SC1 --> SC3 + SC2 --> PSQL + SC2 --> SC1 + SC2 --> SC3 + SC3 --> PSQL + SC3 --> SC1 + SC3 --> SC2 + } + state P3 { + PSQL + } + } +``` + +### What you can do in this sample application + +The sample application supports the following types of transactions: + +- Get customer information. +- Place an order by using a line of credit. + - Checks if the cost of the order is below the customer's credit limit. + - If the check passes, records the order history and updates the amount the customer has spent. +- Get order information by order ID. +- Get order information by customer ID. +- Make a payment. + - Reduces the amount the customer has spent. + +## Prerequisites for this sample application + +- [.NET SDK 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [Set Up ScalarDB Cluster on Kubernetes by Using a Helm Chart](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +:::note + +.NET SDK 8.0 is the version used to create the sample application. For information about all supported versions, see [Requirements](../requirements.mdx#net) + +::: + +## Set up ScalarDB Cluster + +The following sections describe how to set up the sample e-commerce application. + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sample +``` + +### Update the referenced version of the ScalarDB.Client package + +To use ScalarDB Cluster, open `ScalarDbClusterSample.csproj` in your preferred text editor. Then, update the version of the referenced `ScalarDB.Client` package, replacing `.` with the version of the deployed ScalarDB Cluster: + +```xml + +``` + +### Modify `scalardb-options.json` + +You need to modify `scalardb-options.json` to connect to ScalarDB Cluster as well. But before doing so, you need to get the `EXTERNAL-IP` address of the Envoy service resource (`scalardb-cluster-envoy`). To get the service resource, run the following command: + +```console +kubectl get svc scalardb-cluster-envoy +``` + +You should see a similar output as below, with different values for `CLUSTER-IP`, `PORT(S)`, and `AGE`: + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +Open `scalardb-options.json` by running the following command: + +```console +vim scalardb-options.json +``` + +Then, modify `scalardb-options.json` as follows: + +```json +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053" + } +} +``` + +### Load the initial data + +Before running the sample application, you need to load the initial data by running the following command: + +```console +dotnet run LoadInitialData +``` + +#### Schema details + +Running the command above will also apply the schema. All the tables are created in the `sample` namespace. + +- `sample.customers`: a table that manages customer information + - `credit_limit`: the maximum amount of money that the lender will allow the customer to spend from their line of credit + - `credit_total`: the amount of money that the customer has spent from their line of credit +- `sample.orders`: a table that manages order information +- `sample.statements`: a table that manages order statement information +- `sample.items`: a table that manages information for items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/getting-started-ERD.png) + +#### Initial data + +After the initial data has loaded, the following records should be stored in the tables. + +**`sample.customers` table** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` table** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Execute transactions and retrieve data in the sample application + +The following sections describe how to execute transactions and retrieve data in the sample e-commerce application. + +### Get customer information + +Start with getting information about the customer whose ID is `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 0 +} +``` + +### Place an order + +Then, have customer ID `1` place an order for three apples and two oranges by running the following command: + +:::note + +The order format in this command is `dotnet run PlaceOrder :,:,..."`. + +::: + +```console +dotnet run PlaceOrder 1 1:3,2:2 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b" +} +``` + +### Check order details + +Check details about the order by running the following command, replacing `` with the UUID for the `order_id` that was shown after running the previous command: + +```console +dotnet run GetOrder +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`: + +```console +{ + "order": { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + } +} +``` + +### Place another order + +Place an order for one melon that uses the remaining amount in `credit_total` for customer ID `1` by running the following command: + +```console +dotnet run PlaceOrder 1 5:1 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8" +} +``` + +### Check order history + +Get the history of all orders for customer ID `1` by running the following command: + +```console +dotnet run GetOrders 1 +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`, which shows the history of all orders for customer ID `1`: + +```console +{ + "orders": [ + { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + }, + { + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8", + "timestamp": 1743143505436, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 5, + "item_name": "Melon", + "price": 3000, + "count": 1, + "total": 3000 + } + ], + "total": 3000 + } + ] +} +``` + +### Check credit total + +Get the credit total for customer ID `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output, which shows that customer ID `1` has reached their `credit_limit` in `credit_total` and cannot place anymore orders: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 10000 +} +``` + +Try to place an order for one grape and one mango by running the following command: + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +You should see a similar output as below, which shows that the order failed because the `credit_total` amount would exceed the `credit_limit` amount. + +```console +Unhandled exception: System.Exception: Credit limit exceeded (17500 > 10000) + at ScalarDbClusterSample.Sample.PlaceOrder(Int32 customerId, IReadOnlyDictionary`2 itemCounts) in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sample/Sample.cs:line 254 + at ScalarDbClusterSample.Commands.PlaceOrderCommand.<>c.<b__6_0>d.MoveNext() in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sample/Commands/PlaceOrderCommand.cs:line 47 +--- End of stack trace from previous location --- +... +``` + +### Make a payment + +To continue making orders, customer ID `1` must make a payment to reduce the `credit_total` amount. + +Make a payment by running the following command: + +```console +dotnet run Repayment 1 8000 +``` + +Then, check the `credit_total` amount for customer ID `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output, which shows that a payment was applied to customer ID `1`, reducing the `credit_total` amount: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 2000 +} +``` + +Now that customer ID `1` has made a payment, place an order for one grape and one melon by running the following command: + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "ecd68f46-e248-4f2e-b581-620e9019bf5b" +} +``` + +## See also + +For details about developing applications that use ScalarDB Cluster with the .NET API, refer to the following: + +- [ScalarDB Cluster .NET Client SDK Overview](../scalardb-cluster-dotnet-client-sdk/index.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx new file mode 100644 index 00000000..1234c270 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx @@ -0,0 +1,335 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Cluster GraphQL + +import JavadocLink from '/src/theme/JavadocLink.js'; + +This tutorial describes how to use ScalarDB Cluster GraphQL. + +## Prerequisites + +- One of the following Java Development Kits (JDKs): + - [Oracle JDK](https://www.oracle.com/java/technologies/downloads/) LTS version (8, 11, 17, or 21) + - [OpenJDK](https://openjdk.org/install/) LTS version (8, 11, 17, or 21) +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [Set Up ScalarDB Cluster on Kubernetes by Using a Helm Chart](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +## Sample application + +This tutorial illustrates the process of creating an electronic money application, where money can be transferred between accounts. + +The following diagram shows the system architecture of the sample application: + +``` + +----------------------------------------------------------------------------------------------------------------------------------------+ + | [Kubernetes Cluster] | + | | + | [Pod] [Pod] [Pod] | + | | + | +-------+ | + | +---> | Envoy | ---+ | + | | +-------+ | | + | | | | + +------------------------+ | +---------+ | +-------+ | +--------------------+ | + | Schema Loader | --+-> | Service | ---+---> | Envoy | ---+---------> | Service | ---+ | + | (indirect client mode) | | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | | + +------------------------+ | +---------+ | | +--------------------+ | +-----------------------+ | + | | +-------+ | | +---> | ScalarDB Cluster Node | ---+ | + | +---> | Envoy | ---+ | | +-----------------------+ | | + | +-------+ | | | | + | | | +-----------------------+ | +------------+ | + | +---+---> | ScalarDB Cluster Node | ---+---> | PostgreSQL | | + | | | +-----------------------+ | +------------+ | + | | | | | + | | | +-----------------------+ | | + | | +---> | ScalarDB Cluster Node | ---+ | + | | +-----------------------+ | + +------------+ | +----------------------------+ | | + | Browser | ------+---------------------------------------> | Service | ---+ | + | (GraphiQL) | | | (ScalarDB Cluster GraphQL) | | + +------------+ | +----------------------------+ | + | | + +----------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## Step 1. Create `schema.json` + +The following is a simple example schema. + +Create `schema.json`, and add the following to the file: + +```json +{ + "emoney.account": { + "transaction": true, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } +} +``` + +## Step 2. Create `database.properties` + +You need to create `database.properties` for the Schema Loader for ScalarDB Cluster. +But first, you need to get the `EXTERNAL-IP` address of the service resource of Envoy (`scalardb-cluster-envoy`). + +To see the `EXTERNAL-IP` address, run the following command: + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +Then, create `database.properties`, and add the following to the file: + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:localhost +``` + +To connect to ScalarDB Cluster, you need to specify `cluster` for the `scalar.db.transaction_manager` property. +In addition, you will use the `indirect` client mode and connect to the service resource of Envoy in this tutorial. +For details about the client modes, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +## Step 3. Load a schema + +To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). +Using the Schema Loader for Cluster is basically the same as using the [Schema Loader for ScalarDB](../schema-loader.mdx) except the name of the JAR file is different. +You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). +After downloading the JAR file, you can run the Schema Loader for Cluster with the following command: + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +``` + +## Step 4. Run operations from GraphiQL + +In ScalarDB Cluster, if the `scalar.db.graphql.graphiql` property is set to `true` (`true` is the default value), the GraphiQL IDE will be available. + +To get the `EXTERNAL-IP` address of the service resource of ScalarDB Cluster GraphQL (`scalardb-cluster-graphql`), run the following command: + +```console +kubectl get svc scalardb-cluster-graphql +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-graphql LoadBalancer 10.105.74.214 localhost 8080:30514/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`, and the endpoint URL of GraphiQL IDE is `http://localhost:8080/graphql`. +Opening that URL with your web browser will take you to the GraphiQL screen. + +Let's insert the first record. +In the left pane, paste the following mutation, then push the triangle-shaped `Execute Query` button at the top of the window. + +```graphql +mutation PutUser1 { + account_put(put: {key: {id: "user1"}, values: {balance: 1000}}) +} +``` + +ScalarDB GraphQL always runs queries with transactions. +The above query starts a new transaction, executes a ScalarDB Put command, and commits the transaction at the end of the execution. + +The following response from the GraphQL server will appear in the right pane: + +```json +{ + "data": { + "account_put": true + } +} +``` + +The `"data"` field contains the result of the execution. +This response shows the `account_put` field of the mutation was successful. +The result type of mutations is `Boolean!`, which indicates whether the operation succeeded or not. + +Next, let's get the record you just inserted. +Paste the following query next to the previous mutation in the left pane, and click the `Execute Query` button. +Since you don't delete the `mutation PutUser1` above, a pull-down menu will appear below the button, and you can choose which operation should be executed. Choose `GetUser1`, as shown below: + +```graphql +query GetUser1 { + account_get(get: {key: {id: "user1"}}) { + account { + id + balance + } + } +} +``` + +You should get the following result in the right pane: + +```json +{ + "data": { + "account_get": { + "account": { + "id": "user1", + "balance": 1000 + } + } + } +} +``` + +### Mappings between GraphQL API and ScalarDB Java API + +The automatically generated GraphQL schema defines queries, mutations, and object types for input/output to allow you to run CRUD operations for all the tables in the target namespaces. These operations are designed to match the ScalarDB APIs defined in the interface. + +Assuming you have an `account` table in a namespace, the following queries and mutations will be generated: + +| ScalarDB API | GraphQL root type | GraphQL field | +|--------------------------------------------------------|-------------------|------------------------------------------------------------------------------------| +| `get(Get get)` | `Query` | `account_get(get: account_GetInput!): account_GetPayload` | +| `scan(Scan scan)` | `Query` | `account_scan(scan: account_ScanInput!): account_ScanPayload` | +| `put(Put put)` | `Mutation` | `account_put(put: account_PutInput!): Boolean!` | +| `put(java.util.List puts)` | `Mutation` | `account_bulkPut(put: [account_PutInput!]!): Boolean!` | +| `delete(Delete delete)` | `Mutation` | `account_delete(delete: account_DeleteInput!): Boolean!` | +| `delete(java.util.List deletes)` | `Mutation` | `account_bulkDelete(delete: [account_DeleteInput!]!): Boolean!` | +| `mutate(java.util.List mutations)` | `Mutation` | `account_mutate(put: [account_PutInput!]delete: [account_DeleteInput!]): Boolean!` | + +Note that the `scan` field is not generated for a table with no clustering key. +This is the reason why the `account_scan` field is not available in this electronic money sample application. + +You can see all generated GraphQL types in GraphiQL's Documentation Explorer (the `< Docs` link at the top-left corner). + +## Step 5. Run a transaction across multiple requests from GraphiQL + +Let's run a transaction that spans multiple GraphQL requests. + +The generated schema provides the `@transaction` directive that allows you to identify transactions. +You can use this directive with both queries and mutations. + +Before starting a transaction, you need to insert the necessary record with the following mutation: + +```graphql +mutation PutUser2 { + account_put(put: {key: {id: "user2"}, values: {balance: 1000}}) +} +``` + +### Start a transaction before running an operation + +Running the following to add a `@transaction` directive with no arguments to a query or mutation directs the execution to start a new transaction: + +```graphql +query GetAccounts @transaction { + user1: account_get(get: {key: {id: "user1"}}) { + account { balance } + } + user2: account_get(get: {key: {id: "user2"}}) { + account { balance } + } +} +``` + +After running the above command, you will get a result with a transaction ID in the `extensions` field. +The `id` value in the extensions is the transaction ID in which the operation in the request was run. +In this case, the following is the new ID of the transaction just started by the request: + +```json +{ + "data": { + "user1": { + "account": { + "balance": 1000 + } + }, + "user2": { + "account": { + "balance": 1000 + } + } + }, + "extensions": { + "transaction": { + "id": "c88da8a6-a13f-4857-82fe-45f1ab4150f9" + } + } +} +``` + +### Run an operation in a continued transaction + +To run the next queries or mutations in the transaction you started, specify the transaction ID as the `id` argument of the `@transaction`. +The following example updates two accounts you retrieved in the previous example by transferring a balance from user1's account to user2's account in the same transaction: + +```graphql +mutation Transfer @transaction(id: "c88da8a6-a13f-4857-82fe-45f1ab4150f9") { + user1: account_put(put: {key: {id: "user1"}, values: {balance: 750}}) + user2: account_put(put: {key: {id: "user2"}, values: {balance: 1250}}) +} +``` + +Note that a transaction started with GraphQL has a timeout of 1 minute (by default) and will be aborted automatically if it exceeds the timeout. + +### Commit a transaction + +To commit the continued transaction, specify both the `id` and the `commit: true` flag as arguments of the `@transaction` directive: + +```graphql +query GetAndCommit @transaction(id: "c88da8a6-a13f-4857-82fe-45f1ab4150f9", commit: true) { + user1: account_get(get: {key: {id: "user1"}}) { + account { balance } + } + user2: account_get(get: {key: {id: "user2"}}) { + account { balance } + } +} +``` + +**Note:** If you specify a `commit: true` flag without an `id` argument like `@transaction(commit: true)`, a new transaction will start and be committed just for one operation. +This behavior is exactly the same as not specifying the `@transaction` directive, as seen in the above examples using GraphiQL. +In other words, you can omit the directive itself when `@transaction(commit: true)` is specified. + +### Abort or roll back a transaction + +If you need to abort or roll back a transaction explicitly, you can use the `abort` or `rollback` mutation fields interchangeably (both have the same effect and usage). +Note that you cannot mix these fields with any other operations, so you must specify only the `abort` or `rollback` mutation field as follows: + +```graphql +mutation AbortTx @transaction(id: "c88da8a6-a13f-4857-82fe-45f1ab4150f9") { + abort +} +``` + +Or: + +```graphql +mutation RollbackTx @transaction(id: "c88da8a6-a13f-4857-82fe-45f1ab4150f9") { + rollback +} +``` + +## See also + +For other ScalarDB Cluster tutorials, see the following: + +- [Getting Started with ScalarDB Cluster](getting-started-with-scalardb-cluster.mdx) +- [Getting Started with ScalarDB Cluster SQL via JDBC](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [Getting Started with Using Go for ScalarDB Cluster](getting-started-with-using-go-for-scalardb-cluster.mdx) +- [Getting Started with Using Python for ScalarDB Cluster](getting-started-with-using-python-for-scalardb-cluster.mdx) + +For details about developing applications that use ScalarDB Cluster with the Java API, refer to the following: + +- [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-dotnet.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-dotnet.mdx new file mode 100644 index 00000000..8e40f7b3 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-dotnet.mdx @@ -0,0 +1,439 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Cluster SQL via .NET + +This tutorial describes how to create a sample application that uses [ScalarDB Cluster](./index.mdx) SQL through the .NET API. + +## Overview + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit by using ScalarDB. + +:::note + +Since the focus of the sample application is to demonstrate using ScalarDB, application-specific error handling, authentication processing, and similar functions are not included in the sample application. For details about exception handling, see [Exception Handling in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/exception-handling.mdx). + +::: + +The following diagram shows the system architecture of the sample application: + +```mermaid +stateDiagram-v2 + state "Sample application using the .NET API" as SA + state "Kubernetes Cluster" as KC + state "Service (Envoy)" as SE + state "Pod" as P1 + state "Pod" as P2 + state "Pod" as P3 + state "Envoy" as E1 + state "Envoy" as E2 + state "Envoy" as E3 + state "Service (ScalarDB Cluster)" as SSC + state "ScalarDB Cluster" as SC1 + state "ScalarDB Cluster" as SC2 + state "ScalarDB Cluster" as SC3 + state "PostgreSQL" as PSQL + SA --> SE + state KC { + SE --> E1 + SE --> E2 + SE --> E3 + state P1 { + E1 --> SSC + E2 --> SSC + E3 --> SSC + } + SSC --> SC1 + SSC --> SC2 + SSC --> SC3 + state P2 { + SC1 --> PSQL + SC1 --> SC2 + SC1 --> SC3 + SC2 --> PSQL + SC2 --> SC1 + SC2 --> SC3 + SC3 --> PSQL + SC3 --> SC1 + SC3 --> SC2 + } + state P3 { + PSQL + } + } +``` + +### What you can do in this sample application + +The sample application supports the following types of transactions: + +- Get customer information. +- Place an order by using a line of credit. + - Checks if the cost of the order is below the customer's credit limit. + - If the check passes, records the order history and updates the amount the customer has spent. +- Get order information by order ID. +- Get order information by customer ID. +- Make a payment. + - Reduces the amount the customer has spent. + +## Prerequisites for this sample application + +- [.NET SDK 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [How to Deploy ScalarDB Cluster Locally](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +:::note + +.NET SDK 8.0 is the version used to create the sample application. For information about all supported versions, see [Requirements](../requirements.mdx#net) + +::: + +## Set up ScalarDB Cluster + +The following sections describe how to set up the sample e-commerce application. + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sql-sample +``` + +### Update the referenced version of the ScalarDB.Client package + +To use ScalarDB Cluster, open `ScalarDbClusterSample.csproj` in your preferred text editor. Then, update the version of the referenced `ScalarDB.Client` package, replacing `.` with the version of the deployed ScalarDB Cluster: + +```xml + +``` + +### Modify `scalardb-options.json` + +You need to modify `scalardb-options.json` to connect to ScalarDB Cluster as well. But before doing so, you need to get the `EXTERNAL-IP` address of the Envoy service resource (`scalardb-cluster-envoy`). To get the service resource, run the following command: + +```console +kubectl get svc scalardb-cluster-envoy +``` + +You should see a similar output as below, with different values for `CLUSTER-IP`, `PORT(S)`, and `AGE`: + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +Open `scalardb-options.json` by running the following command: + +```console +vim scalardb-options.json +``` + +Then, modify `scalardb-options.json` as follows: + +```json +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053" + } +} +``` + +### Load the initial data + +Before running the sample application, you need to load the initial data by running the following command: + +```console +dotnet run LoadInitialData +``` + +#### Schema details + +Running the command above will also apply the schema. All the tables are created in the `sample` namespace. + +- `sample.customers`: a table that manages customer information + - `credit_limit`: the maximum amount of money that the lender will allow the customer to spend from their line of credit + - `credit_total`: the amount of money that the customer has spent from their line of credit +- `sample.orders`: a table that manages order information +- `sample.statements`: a table that manages order statement information +- `sample.items`: a table that manages information for items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/getting-started-ERD.png) + +#### Initial data + +After the initial data has loaded, the following records should be stored in the tables. + +**`sample.customers` table** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` table** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Execute transactions and retrieve data in the sample application + +The following sections describe how to execute transactions and retrieve data in the sample e-commerce application. + +### Get customer information + +Start with getting information about the customer whose ID is `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 0 +} +``` + +### Place an order + +Then, have customer ID `1` place an order for three apples and two oranges by running the following command: + +:::note + +The order format in this command is `dotnet run PlaceOrder :,:,..."`. + +::: + +```console +dotnet run PlaceOrder 1 1:3,2:2 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b" +} +``` + +### Check order details + +Check details about the order by running the following command, replacing `` with the UUID for the `order_id` that was shown after running the previous command: + +```console +dotnet run GetOrder +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`: + +```console +{ + "order": { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + } +} +``` + +### Place another order + +Place an order for one melon that uses the remaining amount in `credit_total` for customer ID `1` by running the following command: + +```console +dotnet run PlaceOrder 1 5:1 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8" +} +``` + +### Check order history + +Get the history of all orders for customer ID `1` by running the following command: + +```console +dotnet run GetOrders 1 +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`, which shows the history of all orders for customer ID `1`: + +```console +{ + "orders": [ + { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + }, + { + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8", + "timestamp": 1743143505436, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 5, + "item_name": "Melon", + "price": 3000, + "count": 1, + "total": 3000 + } + ], + "total": 3000 + } + ] +} +``` + +### Check credit total + +Get the credit total for customer ID `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output, which shows that customer ID `1` has reached their `credit_limit` in `credit_total` and cannot place anymore orders: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 10000 +} +``` + +Try to place an order for one grape and one mango by running the following command: + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +You should see a similar output as below, which shows that the order failed because the `credit_total` amount would exceed the `credit_limit` amount. + +```console +Unhandled exception: System.Exception: Credit limit exceeded (17500 > 10000) + at ScalarDbClusterSqlSample.Sample.PlaceOrder(Int32 customerId, IReadOnlyDictionary`2 itemCounts) in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sql-sample/Sample.cs:line 237 + at ScalarDbClusterSqlSample.Commands.PlaceOrderCommand.<>c.<b__6_0>d.MoveNext() in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-sql-sample/Commands/PlaceOrderCommand.cs:line 47 +--- End of stack trace from previous location --- +... +``` + +### Make a payment + +To continue making orders, customer ID `1` must make a payment to reduce the `credit_total` amount. + +Make a payment by running the following command: + +```console +dotnet run Repayment 1 8000 +``` + +Then, check the `credit_total` amount for customer ID `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output, which shows that a payment was applied to customer ID `1`, reducing the `credit_total` amount: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 2000 +} +``` + +Now that customer ID `1` has made a payment, place an order for one grape and one melon by running the following command: + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "ecd68f46-e248-4f2e-b581-620e9019bf5b" +} +``` + +## See also + +For details about developing applications that use ScalarDB Cluster with the .NET API, refer to the following: + +- [ScalarDB Cluster .NET Client SDK Overview](../scalardb-cluster-dotnet-client-sdk/index.mdx) +- [Getting Started with Distributed SQL Transactions in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx new file mode 100644 index 00000000..d0910d07 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc.mdx @@ -0,0 +1,232 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Cluster SQL via JDBC + +This tutorial describes how to create a sample application by using ScalarDB Cluster SQL via JDBC. + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [Set Up ScalarDB Cluster on Kubernetes by Using a Helm Chart](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../requirements.mdx). + +::: + +## Sample application + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit by using ScalarDB JDBC. + +The following diagram shows the system architecture of the sample application: + +``` + +------------------------------------------------------------------------------------------------------------------------------+ + | [Kubernetes Cluster] | + | | + | [Pod] [Pod] [Pod] | + +------------------------+ | | + | SQL CLI | | +-------+ +-----------------------+ | + | (indirect client mode) | --+ | +---> | Envoy | ---+ +---> | ScalarDB Cluster Node | ---+ | + +------------------------+ | | | +-------+ | | +-----------------------+ | | + | | | | | | | + | | +---------+ | +-------+ | +--------------------+ | +-----------------------+ | +------------+ | + +--+-> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | ScalarDB Cluster Node | ---+---> | PostgreSQL | | + | | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | +-----------------------+ | +------------+ | + +------------------------+ | | +---------+ | | +--------------------+ | | | + | Sample application | | | | +-------+ | | +-----------------------+ | | + | with ScalarDB JDBC | --+ | +---> | Envoy | ---+ +---> | ScalarDB Cluster Node | ---+ | + | (indirect client mode) | | +-------+ +-----------------------+ | + +------------------------+ | | + +------------------------------------------------------------------------------------------------------------------------------+ +``` + +## Step 1. Clone the ScalarDB Samples repository + +```console +git clone https://github.com/scalar-labs/scalardb-samples.git +cd scalardb-samples/scalardb-sql-jdbc-sample +``` + +## Step 2. Modify `scalardb-sql.properties` + +You need to modify `scalardb-sql.properties` to connect to ScalarDB Cluster as well. +But before doing so, you need to get the `EXTERNAL-IP` address of the service resource of Envoy (`scalardb-cluster-envoy`) as follows: + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +Next, open `scalardb-sql.properties`: + +```console +vim scalardb-sql.properties +``` + +Then, modify `scalardb-sql.properties` as follows: + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost +``` + +To connect to ScalarDB Cluster, you need to specify `cluster` for the `scalar.db.sql.connection_mode` property. +In addition, you will use the `indirect` client mode and connect to the service resource of Envoy in this tutorial. +For details about the client modes, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +## Step 3. Load a schema + +To load a schema, you need to use [the SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli). You can download the SQL CLI from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can use SQL CLI for Cluster by running the following command: + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-sql.properties --file schema.sql +``` + +## Step 4. Load the initial data + +Before running the sample application, you need to load the initial data by running the following command: + +```console +./gradlew run --args="LoadInitialData" +``` + +After the initial data has loaded, the following records should be stored in the tables: + +- For the `sample.customers` table: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +- For the `sample.items` table: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Step 5. Run the sample application + +Let's start with getting information about the customer whose ID is `1`: + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 0} +... +``` + +Then, place an order for three apples and two oranges by using customer ID `1`. +Note that the order format is `:,:,...`: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +... +{"order_id": "454f9c97-f456-44fd-96da-f527187fe39b"} +... +``` + +You can see that running this command shows the order ID. + +Let's check the details of the order by using the order ID: + +```console +./gradlew run --args="GetOrder 454f9c97-f456-44fd-96da-f527187fe39b" +... +{"order": {"order_id": "454f9c97-f456-44fd-96da-f527187fe39b","timestamp": 1685602722821,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1, "name": "Apple", "price": 1000, "count": 3},{"item_id": 2, "name": "Orange", "price": 2000, "count": 2}],"total": 7000}} +... +``` + +Then, let's place another order and get the order history of customer ID `1`: + +```console +./gradlew run --args="PlaceOrder 1 5:1" +... +{"order_id": "3f40c718-59ec-48aa-a6fe-2fdaf12ad094"} +... +./gradlew run --args="GetOrders 1" +... +{"order": [{"order_id": "454f9c97-f456-44fd-96da-f527187fe39b","timestamp": 1685602722821,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1, "name": "Apple", "price": 1000, "count": 3},{"item_id": 2, "name": "Orange", "price": 2000, "count": 2}],"total": 7000},{"order_id": "3f40c718-59ec-48aa-a6fe-2fdaf12ad094","timestamp": 1685602811718,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5, "name": "Melon", "price": 3000, "count": 1}],"total": 3000}]} +... +``` + +This order history is shown in descending order by timestamp. + +The customer's current `credit_total` is `10000`. +Since the customer has now reached their `credit_limit`, which was shown when retrieving their information, they cannot place anymore orders. + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +java.lang.RuntimeException: Credit limit exceeded + at sample.Sample.placeOrder(Sample.java:184) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:32) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:8) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.command.SampleCommand.main(SampleCommand.java:35) +... +``` + +After making a payment, the customer will be able to place orders again. + +```console +./gradlew run --args="Repayment 1 8000" +... +./gradlew run --args="GetCustomerInfo 1" +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 2000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +{"order_id": "fb71279d-88ea-4974-a102-0ec4e7d65e25"} +... +``` + +## Source code of the sample application + +To learn more about ScalarDB Cluster SQL JDBC, you can check the [source code of the sample application](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sql-jdbc-sample/src/main/java/sample). + +## See also + +For other ScalarDB Cluster tutorials, see the following: + +- [Getting Started with ScalarDB Cluster](getting-started-with-scalardb-cluster.mdx) +- [Getting Started with ScalarDB Cluster GraphQL](getting-started-with-scalardb-cluster-graphql.mdx) +- [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [Getting Started with Using Go for ScalarDB Cluster](getting-started-with-using-go-for-scalardb-cluster.mdx) +- [Getting Started with Using Python for ScalarDB Cluster](getting-started-with-using-python-for-scalardb-cluster.mdx) + +For details about developing applications that use ScalarDB Cluster with the Java API, refer to the following: + +- [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-linq.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-linq.mdx new file mode 100644 index 00000000..40e243d0 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-linq.mdx @@ -0,0 +1,439 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Cluster SQL via .NET and LINQ + +This tutorial describes how to create a sample application that uses [ScalarDB Cluster](./index.mdx) SQL through LINQ. + +## Overview + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit by using ScalarDB. + +:::note + +Since the focus of the sample application is to demonstrate using ScalarDB, application-specific error handling, authentication processing, and similar functions are not included in the sample application. For details about exception handling, see [Exception Handling in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/exception-handling.mdx). + +::: + +The following diagram shows the system architecture of the sample application: + +```mermaid +stateDiagram-v2 + state "Sample application using the .NET API" as SA + state "Kubernetes Cluster" as KC + state "Service (Envoy)" as SE + state "Pod" as P1 + state "Pod" as P2 + state "Pod" as P3 + state "Envoy" as E1 + state "Envoy" as E2 + state "Envoy" as E3 + state "Service (ScalarDB Cluster)" as SSC + state "ScalarDB Cluster" as SC1 + state "ScalarDB Cluster" as SC2 + state "ScalarDB Cluster" as SC3 + state "PostgreSQL" as PSQL + SA --> SE + state KC { + SE --> E1 + SE --> E2 + SE --> E3 + state P1 { + E1 --> SSC + E2 --> SSC + E3 --> SSC + } + SSC --> SC1 + SSC --> SC2 + SSC --> SC3 + state P2 { + SC1 --> PSQL + SC1 --> SC2 + SC1 --> SC3 + SC2 --> PSQL + SC2 --> SC1 + SC2 --> SC3 + SC3 --> PSQL + SC3 --> SC1 + SC3 --> SC2 + } + state P3 { + PSQL + } + } +``` + +### What you can do in this sample application + +The sample application supports the following types of transactions: + +- Get customer information. +- Place an order by using a line of credit. + - Checks if the cost of the order is below the customer's credit limit. + - If the check passes, records the order history and updates the amount the customer has spent. +- Get order information by order ID. +- Get order information by customer ID. +- Make a payment. + - Reduces the amount the customer has spent. + +## Prerequisites for this sample application + +- [.NET SDK 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [How to Deploy ScalarDB Cluster Locally](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +:::note + +.NET SDK 8.0 is the version used to create the sample application. For information about all supported versions, see [Requirements](../requirements.mdx#net) + +::: + +## Set up ScalarDB Cluster + +The following sections describe how to set up the sample e-commerce application. + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-linq-sample +``` + +### Update the referenced version of the ScalarDB.Client package + +To use ScalarDB Cluster, open `ScalarDbClusterSample.csproj` in your preferred text editor. Then, update the version of the referenced `ScalarDB.Client` package, replacing `.` with the version of the deployed ScalarDB Cluster: + +```xml + +``` + +### Modify `scalardb-options.json` + +You need to modify `scalardb-options.json` to connect to ScalarDB Cluster as well. But before doing so, you need to get the `EXTERNAL-IP` address of the Envoy service resource (`scalardb-cluster-envoy`). To get the service resource, run the following command: + +```console +kubectl get svc scalardb-cluster-envoy +``` + +You should see a similar output as below, with different values for `CLUSTER-IP`, `PORT(S)`, and `AGE`: + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +Open `scalardb-options.json` by running the following command: + +```console +vim scalardb-options.json +``` + +Then, modify `scalardb-options.json` as follows: + +```json +{ + "ScalarDbOptions": { + "Address": "http://localhost:60053" + } +} +``` + +### Load the initial data + +Before running the sample application, you need to load the initial data by running the following command: + +```console +dotnet run LoadInitialData +``` + +#### Schema details + +Running the command above will also apply the schema. All the tables are created in the `sample` namespace. + +- `sample.customers`: a table that manages customer information + - `credit_limit`: the maximum amount of money that the lender will allow the customer to spend from their line of credit + - `credit_total`: the amount of money that the customer has spent from their line of credit +- `sample.orders`: a table that manages order information +- `sample.statements`: a table that manages order statement information +- `sample.items`: a table that manages information for items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/getting-started-ERD.png) + +#### Initial data + +After the initial data has loaded, the following records should be stored in the tables. + +**`sample.customers` table** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` table** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Execute transactions and retrieve data in the sample application + +The following sections describe how to execute transactions and retrieve data in the sample e-commerce application. + +### Get customer information + +Start with getting information about the customer whose ID is `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 0 +} +``` + +### Place an order + +Then, have customer ID `1` place an order for three apples and two oranges by running the following command: + +:::note + +The order format in this command is `dotnet run PlaceOrder :,:,..."`. + +::: + +```console +dotnet run PlaceOrder 1 1:3,2:2 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b" +} +``` + +### Check order details + +Check details about the order by running the following command, replacing `` with the UUID for the `order_id` that was shown after running the previous command: + +```console +dotnet run GetOrder +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`: + +```console +{ + "order": { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + } +} +``` + +### Place another order + +Place an order for one melon that uses the remaining amount in `credit_total` for customer ID `1` by running the following command: + +```console +dotnet run PlaceOrder 1 5:1 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8" +} +``` + +### Check order history + +Get the history of all orders for customer ID `1` by running the following command: + +```console +dotnet run GetOrders 1 +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`, which shows the history of all orders for customer ID `1`: + +```console +{ + "orders": [ + { + "order_id": "5a22150b-1944-403f-b02c-77183e705d1b", + "timestamp": 1743143358216, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 1, + "item_name": "Apple", + "price": 1000, + "count": 3, + "total": 3000 + }, + { + "item_id": 2, + "item_name": "Orange", + "price": 2000, + "count": 2, + "total": 4000 + } + ], + "total": 7000 + }, + { + "order_id": "79fcd778-94ba-4e8b-b993-cdb88a6186a8", + "timestamp": 1743143505436, + "customer_id": 1, + "customer_name": "Yamada Taro", + "statements": [ + { + "item_id": 5, + "item_name": "Melon", + "price": 3000, + "count": 1, + "total": 3000 + } + ], + "total": 3000 + } + ] +} +``` + +### Check credit total + +Get the credit total for customer ID `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output, which shows that customer ID `1` has reached their `credit_limit` in `credit_total` and cannot place anymore orders: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 10000 +} +``` + +Try to place an order for one grape and one mango by running the following command: + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +You should see a similar output as below, which shows that the order failed because the `credit_total` amount would exceed the `credit_limit` amount. + +```console +Unhandled exception: System.Exception: Credit limit exceeded (17500 > 10000) + at ScalarDbClusterLinqSample.Sample.PlaceOrder(Int32 customerId, IReadOnlyDictionary`2 itemCounts) in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Sample.cs:line 145 + at ScalarDbClusterLinqSample.Commands.PlaceOrderCommand.<>c.<b__6_0>d.MoveNext() in /scalar-labs/scalardb-samples/scalardb-dotnet-samples/scalardb-cluster-linq-sample/Commands/PlaceOrderCommand.cs:line 47 +--- End of stack trace from previous location --- +... +``` + +### Make a payment + +To continue making orders, customer ID `1` must make a payment to reduce the `credit_total` amount. + +Make a payment by running the following command: + +```console +dotnet run Repayment 1 8000 +``` + +Then, check the `credit_total` amount for customer ID `1` by running the following command: + +```console +dotnet run GetCustomerInfo 1 +``` + +You should see the following output, which shows that a payment was applied to customer ID `1`, reducing the `credit_total` amount: + +```console +{ + "id": 1, + "name": "Yamada Taro", + "credit_limit": 10000, + "credit_total": 2000 +} +``` + +Now that customer ID `1` has made a payment, place an order for one grape and one melon by running the following command: + +```console +dotnet run PlaceOrder 1 3:1,4:1 +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +{ + "order_id": "ecd68f46-e248-4f2e-b581-620e9019bf5b" +} +``` + +## See also + +For details about developing applications that use ScalarDB Cluster with the .NET API, refer to the following: + +- [ScalarDB Cluster .NET Client SDK Overview](../scalardb-cluster-dotnet-client-sdk/index.mdx) +- [Getting Started with LINQ in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx new file mode 100644 index 00000000..2fa48c23 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx @@ -0,0 +1,268 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB + +This tutorial describes how to create a sample application by using ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB. + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [Set Up ScalarDB Cluster on Kubernetes by Using a Helm Chart](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../requirements.mdx). + +::: + +## Sample application + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit by using Spring Data JDBC for ScalarDB. + +The following diagram shows the system architecture of the sample application: + +``` + +------------------------------------------------------------------------------------------------------------------------------+ + | [Kubernetes Cluster] | + | | + | [Pod] [Pod] [Pod] | + +------------------------+ | | + | SQL CLI | | +-------+ +-----------------------+ | + | (indirect client mode) | --+ | +---> | Envoy | ---+ +---> | ScalarDB Cluster Node | ---+ | + +------------------------+ | | | +-------+ | | +-----------------------+ | | + | | | | | | | + | | +---------+ | +-------+ | +--------------------+ | +-----------------------+ | +------------+ | + +--+-> | Service | ---+---> | Envoy | ---+---> | Service | ---+---> | ScalarDB Cluster Node | ---+---> | PostgreSQL | | + +------------------------+ | | | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | +-----------------------+ | +------------+ | + | Sample application | | | +---------+ | | +--------------------+ | | | + | with Spring Data JDBC | | | | +-------+ | | +-----------------------+ | | + | for ScalarDB | --+ | +---> | Envoy | ---+ +---> | ScalarDB Cluster Node | ---+ | + | (indirect client mode) | | +-------+ +-----------------------+ | + +------------------------+ | | + +------------------------------------------------------------------------------------------------------------------------------+ +``` + +## Step 1. Clone the ScalarDB Samples repository + +```console +git clone https://github.com/scalar-labs/scalardb-samples.git +cd scalardb-samples/spring-data-sample +``` + +## Step 2. Modify `scalardb-sql.properties` + +You need to modify `scalardb-sql.properties` to connect to ScalarDB Cluster as well. +But before doing so, you need to get the `EXTERNAL-IP` address of the service resource of Envoy (`scalardb-cluster-envoy`) as follows: + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +Next, open `scalardb-sql.properties`: + +```console +vim scalardb-sql.properties +``` + +Then, modify `scalardb-sql.properties` as follows: + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost +``` + +To connect to ScalarDB Cluster, you need to specify `cluster` for the `scalar.db.sql.connection_mode` property. +In addition, you will use the `indirect` client mode and connect to the service resource of Envoy in this tutorial. +For details about the client modes, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +## Step 3. Load a schema + +To load a schema, you need to use [the SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli). You can download the SQL CLI from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can use SQL CLI for Cluster by running the following command: + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-sql.properties --file schema.sql +``` + +## Step 4. Modify `application.properties` + +Then, you need to modify `application.properties` to connect to ScalarDB Cluster as well: + +```console +vim src/main/resources/application.properties +``` + +Similar to `scalardb-sql.properties`, you need to specify `cluster` for the `scalar.db.sql.connection_mode` property and use the `indirect` client mode. +To do so, modify `application.properties` as follows: + +```properties +spring.datasource.driver-class-name=com.scalar.db.sql.jdbc.SqlJdbcDriver +spring.datasource.url=jdbc:scalardb:\ +?scalar.db.sql.connection_mode=cluster\ +&scalar.db.sql.cluster_mode.contact_points=indirect:localhost\ +&scalar.db.consensus_commit.isolation_level=SERIALIZABLE\ +&scalar.db.sql.default_namespace_name=sample +``` + +## Step 5. Load the initial data + +Before running the sample application, you need to load the initial data by running the following command: + +```console +./gradlew run --args="LoadInitialData" +``` + +After the initial data has loaded, the following records should be stored in the tables: + +- For the `sample.customers` table: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +- For the `sample.items` table: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Step 6. Run the sample application + +Let's start with getting information about the customer whose ID is `1`: + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":0} +... +``` + +Then, place an order for three apples and two oranges by using customer ID `1`. Note that the order format is `:,:,...`: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +... +{"order_id":"2358ab35-5819-4f8f-acb1-12e73d97d34e","customer_id":1,"timestamp":1677478005400} +... +``` + +You can see that running this command shows the order ID. + +Let's check the details of the order by using the order ID: + +```console +./gradlew run --args="GetOrder 2358ab35-5819-4f8f-acb1-12e73d97d34e" +... +{"order_id":"2358ab35-5819-4f8f-acb1-12e73d97d34e","timestamp":1677478005400,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":1,"item_name":"Apple","price":1000,"count":3,"total":3000},{"item_id":2,"item_name":"Orange","price":2000,"count":2,"total":4000}],"total":7000} +... +``` + +Then, let's place another order and get the order history of customer ID `1`: + +```console +./gradlew run --args="PlaceOrder 1 5:1" +... +{"order_id":"46062b16-b71b-46f9-a9ff-dc6b0991259b","customer_id":1,"timestamp":1677478201428} +... +./gradlew run --args="GetOrders 1" +... +[{"order_id":"46062b16-b71b-46f9-a9ff-dc6b0991259b","timestamp":1677478201428,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":5,"item_name":"Melon","price":3000,"count":1,"total":3000}],"total":3000},{"order_id":"2358ab35-5819-4f8f-acb1-12e73d97d34e","timestamp":1677478005400,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":1,"item_name":"Apple","price":1000,"count":3,"total":3000},{"item_id":2,"item_name":"Orange","price":2000,"count":2,"total":4000}],"total":7000}] +... +``` + +This order history is shown in descending order by timestamp. + +The customer's current `credit_total` is `10000`. Since the customer has now reached their `credit_limit`, which was shown when retrieving their information, they cannot place anymore orders. + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +java.lang.RuntimeException: Credit limit exceeded. limit:10000, total:17500 + at sample.SampleService.placeOrder(SampleService.java:102) + at sample.SampleService$$FastClassBySpringCGLIB$$1123c447.invoke() + at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793) + at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) + at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) + at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) + at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) + at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) + at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708) + at sample.SampleService$$EnhancerBySpringCGLIB$$a94e1d9.placeOrder() + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:37) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:13) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.SampleApp.run(SampleApp.java:26) + at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:768) + at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:752) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) + at sample.SampleApp.main(SampleApp.java:35) +... +``` + +After making a payment, the customer will be able to place orders again. + +```console +./gradlew run --args="Repayment 1 8000" +... +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":2000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +{"order_id":"0350947a-9003-46f2-870e-6aa4b2df0f1f","customer_id":1,"timestamp":1677478728134} +... +``` + +## Source code of the sample application + +To learn more about Spring Data JDBC for ScalarDB, you can check the [source code of the sample application](https://github.com/scalar-labs/scalardb-samples/tree/main/spring-data-sample/src/main). + +## See also + +For other ScalarDB Cluster tutorials, see the following: + +- [Getting Started with ScalarDB Cluster](getting-started-with-scalardb-cluster.mdx) +- [Getting Started with ScalarDB Cluster GraphQL](getting-started-with-scalardb-cluster-graphql.mdx) +- [Getting Started with ScalarDB Cluster SQL via JDBC](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Getting Started with Using Go for ScalarDB Cluster](getting-started-with-using-go-for-scalardb-cluster.mdx) +- [Getting Started with Using Python for ScalarDB Cluster](getting-started-with-using-python-for-scalardb-cluster.mdx) + +For details about developing applications that use ScalarDB Cluster with the Java API, refer to the following: + +- [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster.mdx new file mode 100644 index 00000000..140afe2b --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-scalardb-cluster.mdx @@ -0,0 +1,405 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Cluster + +This tutorial describes how to create a sample application that uses [ScalarDB Cluster](./index.mdx) through the Java API. + +## Overview + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit by using ScalarDB. + +:::note + +Since the focus of the sample application is to demonstrate using ScalarDB, application-specific error handling, authentication processing, and similar functions are not included in the sample application. For details about exception handling in ScalarDB, see [Handle exceptions](../api-guide.mdx#how-to-handle-exceptions). + +::: + +The following diagram shows the system architecture of the sample application: + +```mermaid +stateDiagram-v2 + state "Schema Loader
(indirect client mode)" as SL + state "Sample application using the Java API
(indirect client mode)" as SA + state "Kubernetes Cluster" as KC + state "Service (Envoy)" as SE + state "Pod" as P1 + state "Pod" as P2 + state "Pod" as P3 + state "Envoy" as E1 + state "Envoy" as E2 + state "Envoy" as E3 + state "Service (ScalarDB Cluster)" as SSC + state "ScalarDB Cluster" as SC1 + state "ScalarDB Cluster" as SC2 + state "ScalarDB Cluster" as SC3 + state "PostgreSQL" as PSQL + SL --> SE + SA --> SE + state KC { + SE --> E1 + SE --> E2 + SE --> E3 + state P1 { + E1 --> SSC + E2 --> SSC + E3 --> SSC + } + SSC --> SC1 + SSC --> SC2 + SSC --> SC3 + state P2 { + SC1 --> PSQL + SC1 --> SC2 + SC1 --> SC3 + SC2 --> PSQL + SC2 --> SC1 + SC2 --> SC3 + SC3 --> PSQL + SC3 --> SC1 + SC3 --> SC2 + } + state P3 { + PSQL + } + } +``` + +### What you can do in this sample application + +The sample application supports the following types of transactions: + +- Get customer information. +- Place an order by using a line of credit. + - Checks if the cost of the order is below the customer's credit limit. + - If the check passes, records the order history and updates the amount the customer has spent. +- Get order information by order ID. +- Get order information by customer ID. +- Make a payment. + - Reduces the amount the customer has spent. + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [Set Up ScalarDB Cluster on Kubernetes by Using a Helm Chart](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../requirements.mdx). + +::: + +## Set up ScalarDB Cluster + +The following sections describe how to set up the sample e-commerce application. + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/scalardb-sample +``` + +### Modify `build.gradle` + +To use ScalarDB Cluster, open `build.gradle` in your preferred text editor. Then, delete the existing dependency for `com.scalar-labs:scalardb` from the `dependencies` section, and add the following dependency to the `dependencies` section: + +```gradle +dependencies { + ... + + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' +} +``` + +### Modify `database.properties` + +You need to modify `database.properties` to connect to ScalarDB Cluster as well. But before doing so, you need to get the `EXTERNAL-IP` address of the Envoy service resource (`scalardb-cluster-envoy`). To get the service resource, run the following command: + +```console +kubectl get svc scalardb-cluster-envoy +``` + +You should see a similar output as below, with different values for `CLUSTER-IP`, `PORT(S)`, and `AGE`: + +```console +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +In `database.properties`, you need to specify `cluster` for the `scalar.db.transaction_manager` property and use `indirect` as the client mode for `scalar.db.contact_points` to connect to the Envoy service resource. + +Open `database.properties` by running the following command: + +```console +vim database.properties +``` + +Then, modify `database.properties` as follows: + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:localhost +``` + +:::note + +For details about the client modes, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +::: + +### Load the schema + +The database schema (the method in which the data will be organized) for the sample application has already been defined in [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sample/schema.json). + +To apply the schema, go to [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4) and download the ScalarDB Cluster Schema Loader to the `scalardb-samples/scalardb-sample` folder. + +Then, run the following command: + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +``` + +#### Schema details + +As shown in [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-sample/schema.json) for the sample application, all the tables are created in the `sample` namespace. + +- `sample.customers`: a table that manages customer information + - `credit_limit`: the maximum amount of money that the lender will allow the customer to spend from their line of credit + - `credit_total`: the amount of money that the customer has spent from their line of credit +- `sample.orders`: a table that manages order information +- `sample.statements`: a table that manages order statement information +- `sample.items`: a table that manages information for items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/getting-started-ERD.png) + +### Load the initial data + +Before running the sample application, you need to load the initial data by running the following command: + +```console +./gradlew run --args="LoadInitialData" +``` + +After the initial data has loaded, the following records should be stored in the tables. + +**`sample.customers` table** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`sample.items` table** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Execute transactions and retrieve data in the sample application + +The following sections describe how to execute transactions and retrieve data in the sample e-commerce application. + +### Get customer information + +Start with getting information about the customer whose ID is `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 0} +... +``` + +### Place an order + +Then, have customer ID `1` place an order for three apples and two oranges by running the following command: + +:::note + +The order format in this command is `./gradlew run --args="PlaceOrder :,:,..."`. + +::: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e"} +... +``` + +### Check order details + +Check details about the order by running the following command, replacing `` with the UUID for the `order_id` that was shown after running the previous command: + +```console +./gradlew run --args="GetOrder " +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`: + +```console +... +{"order": {"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +### Place another order + +Place an order for one melon that uses the remaining amount in `credit_total` for customer ID `1` by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 5:1" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d"} +... +``` + +### Check order history + +Get the history of all orders for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetOrders 1" +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`, which shows the history of all orders for customer ID `1` in descending order by timestamp: + +```console +... +{"order": [{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000},{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d","timestamp": 1650948412766,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000}]} +... +``` + +### Check credit total + +Get the credit total for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output, which shows that customer ID `1` has reached their `credit_limit` in `credit_total` and cannot place anymore orders: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +``` + +Try to place an order for one grape and one mango by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +You should see the following output, which shows that the order failed because the `credit_total` amount would exceed the `credit_limit` amount. + +```console +... +java.lang.RuntimeException: Credit limit exceeded + at sample.Sample.placeOrder(Sample.java:205) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:33) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:8) + at picocli.CommandLine.executeUserObject(CommandLine.java:1783) + at picocli.CommandLine.access$900(CommandLine.java:145) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2141) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2108) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:1975) + at picocli.CommandLine.execute(CommandLine.java:1904) + at sample.command.SampleCommand.main(SampleCommand.java:35) +... +``` + +### Make a payment + +To continue making orders, customer ID `1` must make a payment to reduce the `credit_total` amount. + +Make a payment by running the following command: + +```console +./gradlew run --args="Repayment 1 8000" +``` + +Then, check the `credit_total` amount for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output, which shows that a payment was applied to customer ID `1`, reducing the `credit_total` amount: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 2000} +... +``` + +Now that customer ID `1` has made a payment, place an order for one grape and one melon by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "8911cab3-1c2b-4322-9386-adb1c024e078"} +... +``` + +## See also + +For other ScalarDB Cluster tutorials, see the following: + +- [Getting Started with ScalarDB Cluster GraphQL](getting-started-with-scalardb-cluster-graphql.mdx) +- [Getting Started with ScalarDB Cluster SQL via JDBC](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [Getting Started with Using Go for ScalarDB Cluster](getting-started-with-using-go-for-scalardb-cluster.mdx) +- [Getting Started with Using Python for ScalarDB Cluster](getting-started-with-using-python-for-scalardb-cluster.mdx) + +For details about developing applications that use ScalarDB Cluster with the Java API, refer to the following: + +- [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx new file mode 100644 index 00000000..718b951e --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster.mdx @@ -0,0 +1,444 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Using Go for ScalarDB Cluster + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This document explains how to write gRPC client code for ScalarDB Cluster by using Go. + +## Prerequisites + +- [Go](https://go.dev/dl/) (any one of the three latest major releases) +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [Set Up ScalarDB Cluster on Kubernetes by Using a Helm Chart](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + + + +## Sample application + +This tutorial illustrates the process of creating an electronic money application, where money can be transferred between accounts. + +## Step 1. Create `schema.json` + +The following is a simple example schema. + +Create `schema.json`, and add the following to the file: + +```json +{ + "emoney.account": { + "transaction": true, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } +} +``` + +## Step 2. Create `database.properties` + +You need to create `database.properties` for the Schema Loader for ScalarDB Cluster. +But first, you need to get the `EXTERNAL-IP` address of the service resource of the `LoadBalancer` service (`scalardb-cluster-envoy`). + +To see the `EXTERNAL-IP` address, run the following command: + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +Then, create `database.properties`, and add the following to the file: + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:localhost +``` + +To connect to ScalarDB Cluster, you need to specify `cluster` for the `scalar.db.transaction_manager` property. +In addition, you will use the `indirect` client mode and connect to the service resource of Envoy in this tutorial. +For details about the client modes, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +## Step 3. Load a schema + +To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). Using the Schema Loader for Cluster is basically the same as using the [Schema Loader for ScalarDB](../schema-loader.mdx) except the name of the JAR file is different. You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can run the Schema Loader for Cluster with the following command: + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +``` + +## Step 4. Set up a Go environment + +Follow the [Prerequisites](https://grpc.io/docs/languages/go/quickstart/#prerequisites) section in the gRPC quick-start document to install the following components: + +- Go +- Protocol buffer compiler, `protoc`, version 3.15 or later +- Go plugins for the protocol compiler + +## Step 5. Generate the stub code for ScalarDB Cluster gRPC + +To communicate with the gRPC server for ScalarDB Cluster, you will need to generate the stub code from the proto file. + +First, in a new working directory, create a directory named `scalardb-cluster`, which you will use to generate the gRPC code from, by running the following command: + +```console +mkdir scalardb-cluster +``` + +Then, download the `scalardb-cluster.proto` file and save it in the directory that you created. For ScalarDB Cluster users who have a commercial license, please [contact support](https://www.scalar-labs.com/support) if you need the `scalardb-cluster.proto` file. + +Generate the gRPC code by running the following command: + +```console +protoc --go_out=. --go_opt=paths=source_relative \ + --go_opt=Mscalardb-cluster/scalardb-cluster.proto=example.com/scalardb-cluster \ + --go-grpc_out=. --go-grpc_opt=paths=source_relative \ + --go-grpc_opt=Mscalardb-cluster/scalardb-cluster.proto=example.com/scalardb-cluster \ + scalardb-cluster/scalardb-cluster.proto +``` + +After running the command, you should see two files in the `scalardb-cluster` subdirectory: `scalardb-cluster.pb.go` and `scalardb-cluster_grpc.pb.go`. + +## Step 6. Write a sample application + +The following is the program that uses the gRPC code. Save it as `main.go` in the working directory. This program does the same thing as the `ElectronicMoney.java` program in [Getting Started with ScalarDB](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb/). Note that you have to update the value of `SERVER_ADDRESS` based on the `EXTERNAL-IP` value of the ScalarDB Cluster `LoadBalancer` service in your environment. + +```go +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log" + "os" + "time" + + pb "emoney/scalardb-cluster" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +const ( + SERVER_ADDRESS = "localhost:60053" + NAMESPACE = "emoney" + TABLENAME = "account" + ID = "id" + BALANCE = "balance" +) + +var requestHeader = pb.RequestHeader{HopLimit: 10} + +type TxFn func(ctx context.Context, client pb.DistributedTransactionClient, transactionId string) error + +func withTransaction(fn TxFn) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + // Set up a connection to the server. + conn, err := grpc.Dial(SERVER_ADDRESS, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return err + } + defer conn.Close() + + client := pb.NewDistributedTransactionClient(conn) + + // Begin a transaction + beginResponse, err := client.Begin(ctx, &pb.BeginRequest{RequestHeader: &requestHeader}) + if err != nil { + return err + } + transactionId := beginResponse.TransactionId + + // Execute the function + err = fn(ctx, client, transactionId) + if err != nil { + // Rollback the transaction if there is an error + client.Rollback(ctx, &pb.RollbackRequest{TransactionId: transactionId}) + return err + } + + // Commit the transaction + _, err = client.Commit(ctx, &pb.CommitRequest{RequestHeader: &requestHeader, TransactionId: transactionId}) + return err +} + +func charge(ctx context.Context, client pb.DistributedTransactionClient, transactionId string, id string, amount int) error { + partitionKey := pb.Key{Columns: []*pb.Column{{Name: ID, Value: &pb.Column_TextValue_{TextValue: &pb.Column_TextValue{Value: &id}}}}} + + // Retrieve the current balance for id + get := pb.Get{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &partitionKey, ClusteringKey: nil, + GetType: pb.Get_GET_TYPE_GET, + } + getResponse, err := client.Get(ctx, &pb.GetRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Get: &get}) + if err != nil { + return err + } + + // Calculate the balance + balance := int32(amount) + if result := getResponse.GetResult(); result != nil { + for _, column := range result.GetColumns() { + if column.Name == BALANCE { + balance += column.GetIntValue().GetValue() + break + } + } + } + + // Update the balance + put := pb.Put{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &partitionKey, ClusteringKey: nil, + Columns: []*pb.Column{ + {Name: BALANCE, Value: &pb.Column_IntValue_{IntValue: &pb.Column_IntValue{Value: &balance}}}, + }, + } + _, err = client.Put(ctx, &pb.PutRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Puts: []*pb.Put{&put}}) + return err +} + +func pay(ctx context.Context, client pb.DistributedTransactionClient, transactionId string, fromId string, toId string, amount int) error { + fromPartitionKey := pb.Key{Columns: []*pb.Column{{Name: ID, Value: &pb.Column_TextValue_{TextValue: &pb.Column_TextValue{Value: &fromId}}}}} + toPartitionKey := pb.Key{Columns: []*pb.Column{{Name: ID, Value: &pb.Column_TextValue_{TextValue: &pb.Column_TextValue{Value: &toId}}}}} + + // Retrieve the current balances for ids + fromGet := pb.Get{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &fromPartitionKey, ClusteringKey: nil, + GetType: pb.Get_GET_TYPE_GET, + } + fromGetResponse, err := client.Get(ctx, &pb.GetRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Get: &fromGet}) + if err != nil { + return err + } + toGet := pb.Get{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &toPartitionKey, ClusteringKey: nil, + GetType: pb.Get_GET_TYPE_GET, + } + toGetResponse, err := client.Get(ctx, &pb.GetRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Get: &toGet}) + if err != nil { + return err + } + + // Calculate the balances (it assumes that both accounts exist) + var ( + fromBalance int32 + toBalance int32 + ) + for _, column := range fromGetResponse.GetResult().GetColumns() { + if column.Name == BALANCE { + fromBalance = column.GetIntValue().GetValue() + break + } + } + for _, column := range toGetResponse.GetResult().GetColumns() { + if column.Name == BALANCE { + toBalance = column.GetIntValue().GetValue() + break + } + } + newFromBalance := fromBalance - int32(amount) + newToBalance := toBalance + int32(amount) + + if newFromBalance < 0 { + return errors.New(fromId + " doesn't have enough balance.") + } + + // Update the balances + fromPut := pb.Put{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &fromPartitionKey, ClusteringKey: nil, + Columns: []*pb.Column{ + {Name: BALANCE, Value: &pb.Column_IntValue_{IntValue: &pb.Column_IntValue{Value: &newFromBalance}}}, + }, + } + toPut := pb.Put{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &toPartitionKey, ClusteringKey: nil, + Columns: []*pb.Column{ + {Name: BALANCE, Value: &pb.Column_IntValue_{IntValue: &pb.Column_IntValue{Value: &newToBalance}}}, + }, + } + _, err = client.Put(ctx, &pb.PutRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Puts: []*pb.Put{&fromPut, &toPut}}) + return err +} + +func getBalance(ctx context.Context, client pb.DistributedTransactionClient, transactionId string, id string) (int, error) { + // Retrieve the current balance for id + get := pb.Get{ + NamespaceName: NAMESPACE, TableName: TABLENAME, + PartitionKey: &pb.Key{Columns: []*pb.Column{{Name: ID, Value: &pb.Column_TextValue_{TextValue: &pb.Column_TextValue{Value: &id}}}}}, + ClusteringKey: nil, + GetType: pb.Get_GET_TYPE_GET, + } + getResponse, err := client.Get(ctx, &pb.GetRequest{RequestHeader: &requestHeader, TransactionId: transactionId, Get: &get}) + if err != nil { + return 0, err + } + if getResponse.GetResult() == nil || len(getResponse.GetResult().GetColumns()) == 0 { + return 0, errors.New("Account " + id + " doesn't exist.") + } + + var balance int + for _, column := range getResponse.GetResult().GetColumns() { + if column.Name == BALANCE { + balance = int(column.GetIntValue().GetValue()) + break + } + } + return balance, nil +} + +func main() { + var ( + action = flag.String("action", "", "Action to perform: charge / pay / getBalance") + fromId = flag.String("from", "", "From account (needed for pay)") + toId = flag.String("to", "", "To account (needed for charge and pay)") + id = flag.String("id", "", "Account id (needed for getBalance)") + ) + var amount int + flag.IntVar(&amount, "amount", 0, "Amount to transfer (needed for charge and pay)") + flag.Parse() + + if *action == "charge" { + if *toId == "" || amount < 0 { + printUsageAndExit() + } + err := withTransaction(func(ctx context.Context, client pb.DistributedTransactionClient, txId string) error { + return charge(ctx, client, txId, *toId, amount) + }) + if err != nil { + log.Fatalf("error: %v", err) + } + } else if *action == "pay" { + if *toId == "" || *fromId == "" || amount < 0 { + printUsageAndExit() + } + err := withTransaction(func(ctx context.Context, client pb.DistributedTransactionClient, txId string) error { + return pay(ctx, client, txId, *fromId, *toId, amount) + }) + if err != nil { + log.Fatalf("error: %v", err) + } + } else if *action == "getBalance" { + if *id == "" { + printUsageAndExit() + } + var balance int + err := withTransaction(func(ctx context.Context, client pb.DistributedTransactionClient, txId string) error { + var err error + balance, err = getBalance(ctx, client, txId, *id) + return err + }) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Println(balance) + } else { + fmt.Fprintln(os.Stderr, "Unknown action "+*action) + printUsageAndExit() + } +} + +func printUsageAndExit() { + flag.Usage() + os.Exit(1) +} +``` + +After creating the `main.go` file, you need to create the `go.mod` file by running the following commands: + +```console +go mod init emoney +go mod tidy +``` + +Now, the directory structure should be as follows: + +```text +. +├── go.mod +├── go.sum +├── main.go +└── scalardb-cluster + ├── scalardb-cluster.pb.go + ├── scalardb-cluster.proto + └── scalardb-cluster_grpc.pb.go +``` + +You can then run the program as follows: + +- Charge `1000` to `user1`: + + ```console + go run main.go -action charge -amount 1000 -to user1 + ``` + +- Charge `0` to `merchant1` (Just create an account for `merchant1`): + + ```console + go run main.go -action charge -amount 0 -to merchant1 + ``` + +- Pay `100` from `user1` to `merchant1`: + + ```console + go run main.go -action pay -amount 100 -from user1 -to merchant1 + ``` + +- Get the balance of `user1`: + + ```console + go run main.go -action getBalance -id user1 + ``` + +- Get the balance of `merchant1`: + + ```console + go run main.go -action getBalance -id merchant1 + ``` + +Note that you can also use `go build` to get the binary and then run it: + +```console +go build +./emoney -action getBalance -id user1 +``` + +## See also + +For other ScalarDB Cluster tutorials, see the following: + +- [Getting Started with ScalarDB Cluster](getting-started-with-scalardb-cluster.mdx) +- [Getting Started with ScalarDB Cluster GraphQL](getting-started-with-scalardb-cluster-graphql.mdx) +- [Getting Started with ScalarDB Cluster SQL via JDBC](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [Getting Started with Using Python for ScalarDB Cluster](getting-started-with-using-python-for-scalardb-cluster.mdx) + +For details about developing applications that use ScalarDB Cluster with the Java API, refer to the following: + +- [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx new file mode 100644 index 00000000..f51d3ba0 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster.mdx @@ -0,0 +1,487 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting Started with Using Python for ScalarDB Cluster + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This document explains how to write gRPC client code for ScalarDB Cluster by using Python. + +## Prerequisites + +- [Python](https://www.python.org/downloads) 3.7 or later +- ScalarDB Cluster running on a Kubernetes cluster + - We assume that you have a ScalarDB Cluster running on a Kubernetes cluster that you deployed by following the instructions in [Set Up ScalarDB Cluster on Kubernetes by Using a Helm Chart](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + + + +## Sample application + +This tutorial illustrates the process of creating an electronic money application, where money can be transferred between accounts. + +## Step 1. Create `schema.json` + +The following is a simple example schema. + +Create `schema.json`, and add the following to the file: + +```json +{ + "emoney.account": { + "transaction": true, + "partition-key": [ + "id" + ], + "clustering-key": [], + "columns": { + "id": "TEXT", + "balance": "INT" + } + } +} +``` + +## Step 2. Create `database.properties` + +You need to create `database.properties` for the Schema Loader for ScalarDB Cluster. +But first, you need to get the `EXTERNAL-IP` address of the service resource of the `LoadBalancer` service (`scalardb-cluster-envoy`). + +To see the `EXTERNAL-IP` address, run the following command: + +```console +kubectl get svc scalardb-cluster-envoy +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 16h +``` + +In this case, the `EXTERNAL-IP` address is `localhost`. + +Then, create `database.properties`, and add the following to the file: + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:localhost +``` + +To connect to ScalarDB Cluster, you need to specify `cluster` for the `scalar.db.transaction_manager` property. +In addition, you will use the `indirect` client mode and connect to the service resource of Envoy in this tutorial. +For details about the client modes, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +## Step 3. Load a schema + +To load a schema via ScalarDB Cluster, you need to use the dedicated Schema Loader for ScalarDB Cluster (Schema Loader for Cluster). Using the Schema Loader for Cluster is basically the same as using the [Schema Loader for ScalarDB](../schema-loader.mdx) except the name of the JAR file is different. You can download the Schema Loader for Cluster from [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases/tag/v3.15.4). After downloading the JAR file, you can run the Schema Loader for Cluster with the following command: + +```console +java -jar scalardb-cluster-schema-loader-3.15.4-all.jar --config database.properties -f schema.json --coordinator +``` + +## Step 4. Set up a Python environment + +You can choose any way you like to manage your Python environment. For the purpose of this guide, we assume that your Python application is running in an environment by using `venv`. + +Create a working directory anywhere, and go there. Then, run the following command to activate `venv` by running the following command: + +```console +python3 -m venv venv +source venv/bin/activate +``` + +Let's install the gRPC packages with the `pip` command: + +```console +pip install grpcio grpcio-tools +``` + +## Step 5. Generate the stub code for ScalarDB Cluster gRPC + +To communicate with the gRPC server for ScalarDB Cluster, you will need to generate the stub code from the proto file. + +First, download the `scalardb-cluster.proto` file, then save it in the working directory. For ScalarDB Cluster users who have a commercial license, please [contact support](https://www.scalar-labs.com/support) if you need the `scalardb-cluster.proto` file. + +You can generate the stub code by running the following command: + +```console +python -m grpc_tools.protoc -I . --python_out=. --pyi_out=. --grpc_python_out=. scalardb-cluster.proto +``` + +The following files will be generated: + +- `scalardb_cluster_pb2.py` +- `scalardb_cluster_pb2.pyi` +- `scalardb_cluster_pb2_grpc.py` + +## Step 6. Write a sample application + +The following is the sample Python application (`electronic_money.py`) that uses the stub code. This program does the same thing as the `ElectronicMoney.java` program in [Getting Started with ScalarDB](https://scalardb.scalar-labs.com/docs/latest/getting-started-with-scalardb/). Note that you have to update the value of `SERVER_ADDRESS` based on the `EXTERNAL-IP` value of the ScalarDB Cluster `LoadBalancer` service in your environment. + +```python +import argparse +from typing import Optional + +import grpc + +import scalardb_cluster_pb2_grpc +from scalardb_cluster_pb2 import ( + BeginRequest, + BeginResponse, + Column, + CommitRequest, + Get, + GetRequest, + GetResponse, + Key, + Put, + PutRequest, + RequestHeader, + RollbackRequest, +) + +SERVER_ADDRESS = "localhost:60053" +NAMESPACE = "emoney" +TABLENAME = "account" +ID = "id" +BALANCE = "balance" + +request_header = RequestHeader(hop_limit=10) + + +def charge(id: str, amount: int) -> None: + with grpc.insecure_channel(SERVER_ADDRESS) as channel: + stub = scalardb_cluster_pb2_grpc.DistributedTransactionStub(channel) + + begin_response: BeginResponse = stub.Begin( + BeginRequest(request_header=request_header) + ) + + transaction_id = begin_response.transaction_id + + try: + pkey = Key( + columns=[ + Column( + name=ID, + text_value=Column.TextValue(value=id), + ) + ] + ) + + # Retrieve the current balance for id + get = Get( + namespace_name=NAMESPACE, + table_name=TABLENAME, + get_type=Get.GetType.GET_TYPE_GET, + partition_key=pkey, + ) + get_response: GetResponse = stub.Get( + GetRequest( + request_header=request_header, + transaction_id=transaction_id, + get=get, + ) + ) + + # Calculate the balance + balance = amount + if get_response.result.columns: + balance_column = next( + c for c in get_response.result.columns if c.name == BALANCE + ) + current = balance_column.int_value.value + balance += current + + # Update the balance + put = Put( + namespace_name=NAMESPACE, + table_name=TABLENAME, + partition_key=pkey, + columns=[ + Column(name=BALANCE, int_value=Column.IntValue(value=balance)) + ], + ) + stub.Put( + PutRequest( + request_header=request_header, + transaction_id=transaction_id, + puts=[put], + ) + ) + + # Commit the transaction + stub.Commit( + CommitRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + except Exception as e: + # Rollback the transaction + stub.Rollback( + RollbackRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + raise e + + +def pay(from_id: str, to_id: str, amount: int) -> None: + with grpc.insecure_channel(SERVER_ADDRESS) as channel: + stub = scalardb_cluster_pb2_grpc.DistributedTransactionStub(channel) + + begin_response: BeginResponse = stub.Begin( + BeginRequest(request_header=request_header) + ) + + transaction_id = begin_response.transaction_id + + try: + from_pkey = Key( + columns=[ + Column( + name=ID, + text_value=Column.TextValue(value=from_id), + ) + ] + ) + to_pkey = Key( + columns=[ + Column( + name=ID, + text_value=Column.TextValue(value=to_id), + ) + ] + ) + + # Retrieve the current balances for ids + from_get = Get( + namespace_name=NAMESPACE, + table_name=TABLENAME, + get_type=Get.GetType.GET_TYPE_GET, + partition_key=from_pkey, + ) + from_get_response: GetResponse = stub.Get( + GetRequest( + request_header=request_header, + transaction_id=transaction_id, + get=from_get, + ) + ) + to_get = Get( + namespace_name=NAMESPACE, + table_name=TABLENAME, + get_type=Get.GetType.GET_TYPE_GET, + partition_key=to_pkey, + ) + to_get_response: GetResponse = stub.Get( + GetRequest( + request_header=request_header, + transaction_id=transaction_id, + get=to_get, + ) + ) + + # Calculate the balances (it assumes that both accounts exist) + new_from_balance = ( + next( + c for c in from_get_response.result.columns if c.name == BALANCE + ).int_value.value + - amount + ) + new_to_balance = ( + next( + c for c in to_get_response.result.columns if c.name == BALANCE + ).int_value.value + + amount + ) + + if new_from_balance < 0: + raise RuntimeError(from_id + " doesn't have enough balance.") + + # Update the balances + from_put = Put( + namespace_name=NAMESPACE, + table_name=TABLENAME, + partition_key=from_pkey, + columns=[ + Column( + name=BALANCE, int_value=Column.IntValue(value=new_from_balance) + ) + ], + ) + to_put = Put( + namespace_name=NAMESPACE, + table_name=TABLENAME, + partition_key=to_pkey, + columns=[ + Column( + name=BALANCE, int_value=Column.IntValue(value=new_to_balance) + ) + ], + ) + stub.Put( + PutRequest( + request_header=request_header, + transaction_id=transaction_id, + puts=[from_put, to_put], + ) + ) + + # Commit the transaction (records are automatically recovered in case of failure) + stub.Commit( + CommitRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + except Exception as e: + # Rollback the transaction + stub.Rollback( + RollbackRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + raise e + + +def get_balance(id: str) -> Optional[int]: + with grpc.insecure_channel(SERVER_ADDRESS) as channel: + stub = scalardb_cluster_pb2_grpc.DistributedTransactionStub(channel) + + begin_response: BeginResponse = stub.Begin( + BeginRequest(request_header=request_header) + ) + + transaction_id = begin_response.transaction_id + + try: + # Retrieve the current balance for id + get = Get( + namespace_name=NAMESPACE, + table_name=TABLENAME, + get_type=Get.GetType.GET_TYPE_GET, + partition_key=Key( + columns=[ + Column( + name=ID, + text_value=Column.TextValue(value=id), + ) + ] + ), + ) + get_response: GetResponse = stub.Get( + GetRequest( + request_header=request_header, + transaction_id=transaction_id, + get=get, + ) + ) + + balance = None + if get_response.result.columns: + balance_column = next( + c for c in get_response.result.columns if c.name == BALANCE + ) + balance = balance_column.int_value.value + + # Commit the transaction + stub.Commit( + CommitRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + + return balance + + except Exception as e: + # Rollback the transaction + stub.Rollback( + RollbackRequest( + request_header=request_header, + transaction_id=transaction_id, + ) + ) + raise e + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(required=True) + + parser_charge = subparsers.add_parser("charge") + parser_charge.add_argument("-amount", type=int, required=True) + parser_charge.add_argument("-to", type=str, required=True, dest="to_id") + parser_charge.set_defaults(func=lambda args: charge(args.to_id, args.amount)) + + parser_pay = subparsers.add_parser("pay") + parser_pay.add_argument("-amount", type=int, required=True) + parser_pay.add_argument("-from", type=str, required=True, dest="from_id") + parser_pay.add_argument("-to", type=str, required=True, dest="to_id") + parser_pay.set_defaults( + func=lambda args: pay(args.from_id, args.to_id, args.amount) + ) + + parser_get_balance = subparsers.add_parser("get-balance") + parser_get_balance.add_argument("-id", type=str, required=True) + parser_get_balance.set_defaults(func=lambda args: print(get_balance(args.id))) + + args = parser.parse_args() + args.func(args) + +``` + +You can then run the program as follows: + +- Charge `1000` to `user1`: + + ```console + python electronic_money.py charge -amount 1000 -to user1 + ``` + +- Charge `0` to `merchant1` (Just create an account for `merchant1`): + + ```console + python electronic_money.py charge -amount 0 -to merchant1 + ``` + +- Pay `100` from `user1` to `merchant1`: + + ```console + python electronic_money.py pay -amount 100 -from user1 -to merchant1 + ``` + +- Get the balance of `user1`: + + ```console + python electronic_money.py get-balance -id user1 + ``` + +- Get the balance of `merchant1`: + + ```console + python electronic_money.py get-balance -id merchant1 + ``` + +## See also + +For other ScalarDB Cluster tutorials, see the following: + +- [Getting Started with ScalarDB Cluster](getting-started-with-scalardb-cluster.mdx) +- [Getting Started with ScalarDB Cluster GraphQL](getting-started-with-scalardb-cluster-graphql.mdx) +- [Getting Started with ScalarDB Cluster SQL via JDBC](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [Getting Started with Using Go for ScalarDB Cluster](getting-started-with-using-go-for-scalardb-cluster.mdx) + +For details about developing applications that use ScalarDB Cluster with the Java API, refer to the following: + +- [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +- [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +- [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-vector-search.mdx b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-vector-search.mdx new file mode 100644 index 00000000..3432ceb2 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/getting-started-with-vector-search.mdx @@ -0,0 +1,463 @@ +--- +tags: + - Enterprise Premium + - Private Preview +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Cluster for Vector Search + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +ScalarDB Cluster provides a vector store abstraction to help applications interact with vector stores (embedding stores) in a unified way. This getting-started tutorial explains how to run vector search in ScalarDB Cluster. + +## What is the vector store abstraction? + +ScalarDB Cluster provides an abstraction for various vector stores, similar to how it abstracts different types of databases, including relational databases, NoSQL databases, and NewSQL databases. With this vector store abstraction, you can develop applications that interact with vector stores in a unified manner, making your applications independent of specific vector store implementations and ensuring their portability. Additionally, since the integration of vector stores is built into ScalarDB Cluster, your applications can take advantage of its scalability. + +The current implementation of the vector store abstraction leverages [LangChain4j](https://docs.langchain4j.dev/) and supports the following vector stores and embedding models. + +Vector stores: +- In-memory +- OpenSearch +- Azure Cosmos DB NoSQL +- Azure AI Search +- pgvector + +Embedding models: +- In-process +- Amazon Bedrock +- Azure OpenAI +- Google Vertex AI +- OpenAI + +## Why use the vector store abstraction? + +In the era of generative AI, one of the challenges organizations face when deploying large language models (LLMs) is enabling these models to understand their enterprise data. Retrieval-augmented generation (RAG) is a key technique used to enhance LLMs with specific enterprise knowledge. For example, to ensure that chatbots powered by LLMs provide accurate and relevant responses, companies use RAG to integrate domain-specific information from user manuals and support documents. + +RAG relies on vector stores, which are typically created by extracting data from databases, converting that data into vectors, and then loading those vectors. By using vector store and database abstraction in ScalarDB Cluster, you can implement the entire process seamlessly. This approach significantly simplifies the workflow and code, eliminating the need to write complex applications that depend on specific vector stores and databases. + +## Tutorial + +This tutorial explains how to run vector search in ScalarDB Cluster. + +### Prerequisites + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This tutorial has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../requirements.mdx). + +::: + + + +### 1. Create the ScalarDB Cluster configuration file + +Create the following configuration file as `scalardb-cluster-node.properties`, replacing `` and `` with your ScalarDB license key and license check certificate values. For more information about the license key and certificate, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + +```yaml +scalar.db.transaction.enabled=false + +# Enable the standalone mode +scalar.db.cluster.node.standalone_mode.enabled=true + +# Enable the embedding feature +scalar.db.embedding.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +Additionally, you need to add the properties for the embedding store and the embedding model to the configuration file, depending on the embedding store and the embedding model you want to use. + +Select the embedding store that you want to use, and follow the instructions to configure it. + + + + The in-memory embedding store is a basic in-memory implementation. This embedding store is useful for fast prototyping and simple use cases. + + To use the in-memory embedding store, add the following property to the configuration file: + + ```properties + scalar.db.embedding.store.type=in-memory + ``` + + + The OpenSearch embedding store is an embedding store that uses OpenSearch as the backend. + + Select whether your OpenSearch implementation is running locally or running on AWS, and follow the instructions to configure it. + + + + For OpenSearch clusters that are running locally and are reachable on the network, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.store.type=opensearch + + # OpenSearch Server URL. + scalar.db.embedding.store.opensearch.server_url= + + # OpenSearch API key (optional). + scalar.db.embedding.store.opensearch.api_key= + + # OpenSearch username (optional). + scalar.db.embedding.store.opensearch.user_name= + + # OpenSearch password (optional). + scalar.db.embedding.store.opensearch.password= + + # OpenSearch index name. + scalar.db.embedding.store.opensearch.index_name= + ``` + + + For OpenSearch clusters that are running as a fully managed service on AWS, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.store.type=opensearch + + # OpenSearch Server URL. + scalar.db.embedding.store.opensearch.server_url= + + # The AWS signing service name, one of `es` (Amazon OpenSearch) or `aoss` (Amazon OpenSearch Serverless). + scalar.db.embedding.store.opensearch.service_name= + + # The AWS region for which requests will be signed. This should typically match the region in `server_url`. + scalar.db.embedding.store.opensearch.region= + + # The AWS access key ID. + scalar.db.embedding.store.opensearch.access_key_id= + + # The AWS secret access key. + scalar.db.embedding.store.opensearch.secret_access_key= + + # OpenSearch index name. + scalar.db.embedding.store.opensearch.index_name= + ``` + + + + + The Azure Cosmos DB for NoSQL embedding store is an embedding store that uses Azure Cosmos DB as the backend. + + To use the Azure Cosmos DB for NoSQL embedding store, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.store.type=azure-cosmos-nosql + + # The Azure Cosmos DB endpoint that the SDK will connect to. + scalar.db.embedding.store.azure-cosmos-nosql.endpoint= + + # A master key used to perform authentication for accessing resources. A read-only key can also be used only for read-only operations. + scalar.db.embedding.store.azure-cosmos-nosql.key= + + # The database name to be used. + scalar.db.embedding.store.azure-cosmos-nosql.database_name= + + # The container name to be used. + scalar.db.embedding.store.azure-cosmos-nosql.container_name= + ``` + + + The Azure AI Search embedding store is an embedding store that uses Azure AI Search as the backend. + + To use the Azure AI Search embedding store, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.store.type=azure-ai-search + # The Azure AI Search endpoint. + scalar.db.embedding.store.azure-ai-search.endpoint= + + # The Azure AI Search API key. + scalar.db.embedding.store.azure-ai-search.api_key= + + # The name of the index to be used. If no index is provided, the name of the default index to be used. + scalar.db.embedding.store.azure-ai-search.index_name= + ``` + + + The pgvector embedding store is an embedding store that uses pgvector, which is a Postgres extension for vector similarity search, as the backend. + + To use the pgvector embedding store, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.store.type=pgvector + + # The database host. + scalar.db.embedding.store.pgvector.host= + + # The database port. + scalar.db.embedding.store.pgvector.port= + + # The database user. + scalar.db.embedding.store.pgvector.user= + + # The database password. + scalar.db.embedding.store.pgvector.password= + + # The database name. + scalar.db.embedding.store.pgvector.database= + + # The table name. + scalar.db.embedding.store.pgvector.table= + ``` + + + +Select the embedding model that you want to use, and follow the instructions to configure it. + + + + The in-process embedding model is a local embedding model powered by [ONNX runtime](https://onnxruntime.ai/docs/get-started/with-java.html) and is running in the ScalarDB Cluster process. This embedding model is useful for fast prototyping and simple use cases. + + To use the in-process embedding model, add the following property to the configuration file: + + ```properties + scalar.db.embedding.model.type=in-process + ``` + + + The Amazon Bedrock embedding model is an embedding model that uses Amazon Bedrock as the backend. + + To use the Amazon Bedrock embedding model, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.model.type=bedrock-titan + + # The AWS region for which requests will be signed. + scalar.db.embedding.model.bedrock-titan.region= + + # The AWS access key ID. + scalar.db.embedding.model.bedrock-titan.access_key_id= + + # The AWS secret access key. + scalar.db.embedding.model.bedrock-titan.secret_access_key= + + # The model. Either `amazon.titan-embed-text-v1` or `amazon.titan-embed-text-v2:0`. + scalar.db.embedding.model.bedrock-titan.model= + + # The dimensions. + scalar.db.embedding.model.bedrock-titan.dimensions= + ``` + + + The Azure OpenAI embedding model is an embedding model that uses Azure OpenAI as the backend. + + To use the Azure OpenAI embedding model, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.model.type=azure-open-ai + + # The Azure OpenAI endpoint. + scalar.db.embedding.model.azure-open-ai.endpoint= + + # The Azure OpenAI API key. + scalar.db.embedding.model.azure-open-ai.api_key= + + # The deployment name in Azure OpenAI. + scalar.db.embedding.model.azure-open-ai.deployment_name= + + # The dimensions. + scalar.db.embedding.model.azure-open-ai.dimensions= + ``` + + + The Google Vertex AI embedding model is an embedding model that uses Google Vertex AI as the backend. + + To use the Google Vertex AI embedding model, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.model.type=vertex-ai + + # The Google Cloud project. + scalar.db.embedding.model.vertex-ai.project= + + # The Google Cloud location. + scalar.db.embedding.model.vertex-ai.location= + + # The endpoint. + scalar.db.embedding.model.vertex-ai.endpoint= + + # The publisher. + scalar.db.embedding.model.vertex-ai.publisher= + + # The model name. + scalar.db.embedding.model.vertex-ai.model_name= + + # The output dimensionality. + scalar.db.embedding.model.vertex-ai.output_dimensionality= + ``` + + + The OpenAI embedding model is an embedding model that uses OpenAI as the backend. + + To use the OpenAI embedding model, add the following properties to the configuration file: + + ```properties + scalar.db.embedding.model.type=open-ai + + # The OpenAI API key. + scalar.db.embedding.model.open-ai.api_key= + + # The model name. + scalar.db.embedding.model.open-ai.model_name= + + # The base URL. + scalar.db.embedding.model.open-ai.base_url= + + # The organization ID. + scalar.db.embedding.model.open-ai.organization_id= + + # The dimensions. + scalar.db.embedding.model.open-ai.dimensions= + + # The user. + scalar.db.embedding.model.open-ai.user= + ``` + + + +### 2. Create the Docker Compose file + +Create the following configuration file as `docker-compose.yaml`. + +```yaml +services: + scalardb-cluster-standalone: + container_name: "scalardb-cluster-node" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + ports: + - 60053:60053 + - 9080:9080 + volumes: + - ./scalardb-cluster-node.properties:/scalardb-cluster/node/scalardb-cluster-node.properties +``` + +### 3. Start ScalarDB Cluster + +Run the following command to start ScalarDB Cluster in standalone mode. + +```console +docker compose up -d +``` + +It may take a few minutes for ScalarDB Cluster to fully start. + +### 4. Add the Java Client SDK for the embedding store abstraction to your project + +The ScalarDB Cluster Embedding Java Client SDK library is available on the [Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-cluster-embedding-java-client-sdk). You can add the library as a build dependency to your application by using Gradle or Maven. + +Select your build tool, and follow the instructions to add the build dependency for the ScalarDB Cluster Embedding Java Client SDK to your application. + + + + To add the build dependency for the ScalarDB Cluster Embedding Java Client SDK by using Gradle, add the following to `build.gradle` in your application: + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb-cluster-embedding-java-client-sdk:3.15.4' + } + ``` + + + To add the build dependency for the ScalarDB Cluster Embedding Java Client SDK by using Maven, add the following to `pom.xml` in your application: + + ```xml + + com.scalar-labs + scalardb-cluster-embedding-java-client-sdk + 3.15.4 + + ``` + + + +### 5. Run the sample code + +Create a new Java class and add the following code to run the sample code. + +```java +try (ScalarDbEmbeddingClientFactory scalarDbEmbeddingClientFactory = + ScalarDbEmbeddingClientFactory.builder() + .withProperty("scalar.db.embedding.client.contact_points", "indirect:localhost") + .build()) { + // Create an embedding store and an embedding model. + EmbeddingStore scalarDbEmbeddingStore = + scalarDbEmbeddingClientFactory.createEmbeddingStore(); + EmbeddingModel scalarDbEmbeddingModel = scalarDbEmbeddingClientFactory.createEmbeddingModel(); + + // Add embeddings to the embedding store. + TextSegment segment1 = TextSegment.from("I like football."); + Embedding embedding1 = scalarDbEmbeddingModel.embed(segment1).content(); + scalarDbEmbeddingStore.add(embedding1, segment1); + + TextSegment segment2 = TextSegment.from("The weather is good today."); + Embedding embedding2 = scalarDbEmbeddingModel.embed(segment2).content(); + scalarDbEmbeddingStore.add(embedding2, segment2); + + // Search for embeddings. + Embedding queryEmbedding = + scalarDbEmbeddingModel.embed("What is your favourite sport?").content(); + EmbeddingSearchResult result = + scalarDbEmbeddingStore.search( + EmbeddingSearchRequest.builder() + .queryEmbedding(queryEmbedding) + .maxResults(1) + .build()); + + // Print the search result. + List> matches = result.matches(); + EmbeddingMatch embeddingMatch = matches.get(0); + System.out.println(embeddingMatch.embedded().text()); + System.out.println(embeddingMatch.score()); +} +``` + +This sample code demonstrates how to create an embedding store and an embedding model, add embeddings to the embedding store, and search for embeddings. + +Except for the part of the code that creates an embedding store and an embedding model, the usage is the same as LangChain4j. For more information about LangChain4j, see the following: +- [LangChain4j](https://docs.langchain4j.dev/) +- [Embedding Model](https://docs.langchain4j.dev/tutorials/rag#embedding-model) +- [Embedding Store](https://docs.langchain4j.dev/tutorials/rag#embedding-store) + +#### About `ScalarDbEmbeddingClientFactory` + +As shown in the code snippet, the `ScalarDbEmbeddingClientFactory` class provides a builder to create an instance of the factory. The builder allows you to set properties for the factory. In this example, the `withProperty()` method is used to set the contact points for the factory as follows: + +```java +ScalarDbEmbeddingClientFactory scalarDbEmbeddingClientFactory = ScalarDbEmbeddingClientFactory.builder() + .withProperty("scalar.db.embedding.client.contact_points", "indirect:localhost") + .build(); +``` + +You can also set a properties file by using the `withPropertiesFile()` method. + +Then, you can create an embedding store and an embedding model by using the factory as follows: + +```java +EmbeddingStore scalarDbEmbeddingStore = + scalarDbEmbeddingClientFactory.createEmbeddingStore(); +EmbeddingModel scalarDbEmbeddingModel = scalarDbEmbeddingClientFactory.createEmbeddingModel(); +``` + +Their methods internally connect to ScalarDB Cluster, which interacts with the embedding store by using the embedding model, both of which are specified in the configuration. + +You should reuse the `scalarDbEmbeddingStore` and `scalarDbEmbeddingModel` instances to interact with vector stores in an application. + +:::note + +The `ScalarDbEmbeddingClientFactory` instance should be closed after use to release the connection to ScalarDB Cluster. + +::: + +## Additional details + +The vector search feature is currently in Private Preview. For more details, please [contact us](https://www.scalar-labs.com/contact) or wait for this feature to become publicly available in a future version. + +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-cluster-embedding-java-client-sdk/3.15.4/index.html) diff --git a/versioned_docs/version-3.15/scalardb-cluster/images/direct-kubernetes-client-mode.png b/versioned_docs/version-3.15/scalardb-cluster/images/direct-kubernetes-client-mode.png new file mode 100644 index 00000000..13df52e6 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-cluster/images/direct-kubernetes-client-mode.png differ diff --git a/versioned_docs/version-3.15/scalardb-cluster/images/getting-started-ERD.png b/versioned_docs/version-3.15/scalardb-cluster/images/getting-started-ERD.png new file mode 100644 index 00000000..1a6d13c5 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-cluster/images/getting-started-ERD.png differ diff --git a/versioned_docs/version-3.15/scalardb-cluster/images/indirect-client-mode.png b/versioned_docs/version-3.15/scalardb-cluster/images/indirect-client-mode.png new file mode 100644 index 00000000..4e96108f Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-cluster/images/indirect-client-mode.png differ diff --git a/versioned_docs/version-3.15/scalardb-cluster/images/scalardb-cluster-architecture.png b/versioned_docs/version-3.15/scalardb-cluster/images/scalardb-cluster-architecture.png new file mode 100644 index 00000000..24a0a50d Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-cluster/images/scalardb-cluster-architecture.png differ diff --git a/versioned_docs/version-3.15/scalardb-cluster/images/scalardb-deployment-patterns.png b/versioned_docs/version-3.15/scalardb-cluster/images/scalardb-deployment-patterns.png new file mode 100644 index 00000000..6098c910 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-cluster/images/scalardb-deployment-patterns.png differ diff --git a/versioned_docs/version-3.15/scalardb-cluster/index.mdx b/versioned_docs/version-3.15/scalardb-cluster/index.mdx new file mode 100644 index 00000000..31f56f19 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/index.mdx @@ -0,0 +1,71 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster + +ScalarDB Cluster is a clustering solution for [ScalarDB](../overview.mdx) that consists of a set of cluster nodes, each of which provides ScalarDB functionality. Each cluster node has a routing mechanism that directs transaction requests to the appropriate cluster node within the cluster. + +## Why ScalarDB Cluster? + +When executing a transaction that spans multiple client requests, such as in microservice transactions, all requests for the transaction must be processed on the same server due to the stateful nature of transaction processing. However, in a distributed environment, routing requests to the same server isn't straightforward because a service typically runs on multiple servers (or hosts) for scalability and availability. In this scenario, all requests within a transaction must be routed to the same server, while different transactions should be distributed to ensure load balancing. + +To address this challenge, a routing mechanism such as session affinity (also known as sticky sessions) needs to be configured. This strategy ensures that requests within a transaction are consistently routed to the same server. Alternatively, you can leverage a bidirectional-streaming RPC by using gRPC. However, it's important to note that implementing these configurations typically requires significant time and effort. In addition, specific configuration adjustments may be required depending on the load balancer product you are using. + +For more details on this topic, see [Request routing in transactions with a two-phase commit interface](../two-phase-commit-transactions.mdx#request-routing-in-transactions-with-a-two-phase-commit-interface). + +ScalarDB Cluster addresses this issue by providing a routing mechanism capable of directing requests to the appropriate cluster node within the cluster. Thus, when a cluster node receives a request, the node can route that request to the correct cluster node in the cluster. + +## Architecture + +ScalarDB Cluster consists of a set of cluster nodes, each equipped with ScalarDB functionality. By using this solution, each cluster node can execute transactions independently. + +A notable feature of ScalarDB Cluster is the distribution of transaction requests by using a routing mechanism. When a cluster node receives a request, the node determines whether it's the appropriate cluster node to process the request. If it's not the appropriate node, the node routes the request to the appropriate cluster node within the cluster. To determine the appropriate cluster node, ScalarDB Cluster uses a consistent hashing algorithm. + +Membership management plays a critical role in ScalarDB Cluster. When a cluster node either joins or leaves the cluster, the configuration of the cluster is automatically adjusted to reflect this change. ScalarDB Cluster currently retrieves membership information by using the Kubernetes API. + +:::note + +Currently, ScalarDB Cluster supports running on Kubernetes only. + +::: + +![ScalarDB Cluster architecture](images/scalardb-cluster-architecture.png) + +## Getting started + +Before you start the tutorials, you need to set up ScalarDB Cluster. To set up ScalarDB Cluster, see [Set Up ScalarDB Cluster on Kubernetes by Using a Helm Chart](setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx). + +For tutorials on getting started with ScalarDB Cluster, see the following: + +* [Getting Started with ScalarDB Cluster](getting-started-with-scalardb-cluster.mdx) +* [Getting Started with ScalarDB Cluster GraphQL](getting-started-with-scalardb-cluster-graphql.mdx) +* [Getting Started with ScalarDB Cluster SQL via JDBC](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +* [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +* [Getting Started with ScalarDB Cluster via .NET](getting-started-with-scalardb-cluster-dotnet.mdx) +* [Getting Started with ScalarDB Cluster SQL via .NET](getting-started-with-scalardb-cluster-sql-dotnet.mdx) +* [Getting Started with ScalarDB Cluster SQL via .NET and LINQ](getting-started-with-scalardb-cluster-sql-linq.mdx) + +## References + +For details about the ScalarDB Cluster Helm Chart, refer to the following: + +* [ScalarDB Cluster Helm Chart](https://github.com/scalar-labs/helm-charts/tree/main/charts/scalardb-cluster) +* [Deploy Scalar products using Scalar Helm Charts](../helm-charts/how-to-deploy-scalar-products.mdx) +* [How to deploy ScalarDB Cluster](../helm-charts/how-to-deploy-scalardb-cluster.mdx) + +For details about the configurations for ScalarDB Cluster, refer to the following: + +* [ScalarDB Cluster Configurations](scalardb-cluster-configurations.mdx) + +For details about developing applications that use ScalarDB Cluster with the Java API, refer to the following: + +* [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) + +For details about the ScalarDB Cluster gRPC API, refer to the following: + +* [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +* [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx b/versioned_docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx new file mode 100644 index 00000000..9261de2a --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster.mdx @@ -0,0 +1,311 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Non-Transactional Storage Operations Through ScalarDB Cluster + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to run non-transactional storage operations through ScalarDB Cluster. + +:::warning + +You need to have a license key (trial license or commercial license) for ScalarDB Cluster. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). + +::: + +## Preparation + +For the purpose of this guide, you will set up a database and ScalarDB Cluster in standalone mode by using a sample in the ScalarDB samples repository. + +:::note + +ScalarDB Cluster in standalone mode is primarily for development and testing purposes. + +::: + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the necessary files by running the following command: + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode +``` + +## Set up a database + +Select your database, and follow the instructions to configure it for ScalarDB Cluster. + +For a list of databases that ScalarDB supports, see [Databases](../requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for MySQL in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for PostgreSQL in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Oracle Database in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for SQL Server in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Amazon DynamoDB Local in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB Cluster

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Apache Cassandra, run the following command: + + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Cassandra in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +For a comprehensive list of configurations for ScalarDB, see [ScalarDB Configurations](../configurations.mdx). + +## Set up ScalarDB Cluster in standalone mode + +To set up ScalarDB Cluster in standalone mode, you'll need to configure ScalarDB Cluster to run non-transactional storage operations, set a license key, and then start ScalarDB Cluster. + +### Configure ScalarDB Cluster to run non-transactional storage operations + +To run non-transactional storage operations, you need to configure the `scalar.db.transaction_manager` property to `single-crud-operation` in the configuration file `scalardb-cluster-node.properties`: + +```properties +scalar.db.transaction_manager=single-crud-operation +``` + +### Set the license key + +Set the license key (trial license or commercial license) for the ScalarDB Clusters in the properties file. For details, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + +### Start ScalarDB Cluster in standalone mode + +To start ScalarDB Cluster in standalone mode, run the following command: + +:::note + +If you want to change other configurations for ScalarDB Cluster, update the `scalardb-cluster-node.properties` file before running the command below. + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## Create or import a schema + +ScalarDB has its own data model and schema that maps to the implementation-specific data model and schema. + +- **Need to create a database schema?** See [Schema Loader for Cluster](developer-guide-for-scalardb-cluster-with-java-api.mdx#schema-loader-for-cluster). +- **Need to import an existing database?** See [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](../schema-loader-import.mdx). + +## Create your Java application + +This section describes how to add the ScalarDB Cluster Java Client SDK to your project and how to configure it to run non-transactional storage operations by using Java. + +### Add the ScalarDB Cluster Java Client SDK to your build + +The ScalarDB Cluster Java Client SDK is available in the [Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-cluster-java-client-sdk). You can add the SDK as a build dependency to your application by using Gradle or Maven. + +Select your build tool, and follow the instructions to add the build dependency for the ScalarDB Cluster Java Client SDK to your application. + + + + To add the build dependency for the ScalarDB Cluster Java Client SDK by using Gradle, add the following to `build.gradle` in your application: + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + } + ``` + + + To add the build dependency for the ScalarDB Cluster Java Client SDK by using Maven, add the following to `pom.xml` in your application: + + ```xml + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + ``` + + + +### Configure the ScalarDB Cluster Java SDK + +For details about configuring the ScalarDB Cluster Java SDK, see [Client configurations](developer-guide-for-scalardb-cluster-with-java-api.mdx#client-configurations) + +### Use the Java API + +For details about the Java API, see [ScalarDB Java API Guide](../api-guide.mdx). + +:::note + +The following limitations apply to non-transactional storage operations: + +- Beginning a transaction is not supported. For more details, see [Execute transactions without beginning or starting a transaction](../api-guide.mdx#execute-transactions-without-beginning-or-starting-a-transaction). +- Executing multiple mutations in a single transaction is not supported. + +::: + +### Learn more + +- [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb/3.15.4/index.html) +- [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx b/versioned_docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx new file mode 100644 index 00000000..9479c41f --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface.mdx @@ -0,0 +1,393 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Non-Transactional Storage Operations Through the SQL Interface + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to run non-transactional storage operations through the SQL interface for ScalarDB Cluster. + +:::warning + +You need to have a license key (trial license or commercial license) for ScalarDB Cluster. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). + +::: + +## Preparation + +For the purpose of this guide, you will set up a database and ScalarDB Cluster in standalone mode by using a sample in the ScalarDB samples repository. + +:::note + +ScalarDB Cluster in standalone mode is primarily for development and testing purposes. + +::: + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the necessary files by running the following command: + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode +``` + +## Set up a database + +Select your database, and follow the instructions to configure it for ScalarDB Cluster. + +For a list of databases that ScalarDB supports, see [Databases](../requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for MySQL in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for PostgreSQL in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Oracle Database in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for SQL Server in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Amazon DynamoDB Local in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB Cluster

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Apache Cassandra, run the following command: + + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Cassandra in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +For a comprehensive list of configurations for ScalarDB, see [ScalarDB Configurations](../configurations.mdx). + +## Set up ScalarDB Cluster in standalone mode + +To set up ScalarDB Cluster in standalone mode, you'll need to configure ScalarDB Cluster to run non-transactional storage operations, set a license key, and then start ScalarDB Cluster. + +### Configure ScalarDB Cluster to run non-transactional storage operations + +To run non-transactional storage operations, you need to configure the `scalar.db.transaction_manager` property to `single-crud-operation` in the configuration file `scalardb-cluster-node.properties`: + +```properties +scalar.db.transaction_manager=single-crud-operation +``` + +### Set the license key + +Set the license key (trial license or commercial license) for the ScalarDB Clusters in the properties file. For details, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + +### Start ScalarDB Cluster in standalone mode + +To start ScalarDB Cluster in standalone mode, run the following command: + +:::note + +If you want to change other configurations for ScalarDB Cluster, update the `scalardb-cluster-node.properties` file before running the command below. + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## Create or import a schema + +ScalarDB has its own data model and schema that maps to the implementation-specific data model and schema. + +- **Need to create a database schema?** See [SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli). +- **Need to import an existing database?** See [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](../schema-loader-import.mdx). + +Also, for a list of supported DDLs, see [ScalarDB SQL Grammar](../scalardb-sql/grammar.mdx). + +## Create your application + + + +

Configure your JDBC application

+ + This section describes how to add the ScalarDB JDBC driver to your project and how to configure it to run non-transactional storage operations by using Java. + +

Add the ScalarDB JDBC driver to your project

+ + You can add the ScalarDB JDBC driver as a build dependency to your application by using Gradle or Maven. + + Select your build tool, and follow the instructions to add the build dependency for the ScalarDB JDBC driver to your application. + + + + To add the build dependency for the ScalarDB JDBC driver by using Gradle, add the following to `build.gradle` in your application: + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb-sql-jdbc:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + } + ``` + + + To add the build dependency for the ScalarDB SQL API by using Maven, add the following to `pom.xml` in your application: + + ```xml + + + com.scalar-labs + scalardb-sql-jdbc + 3.15.4 + + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + + ``` + + + +

Configure the ScalarDB Cluster Java SDK for the SQL interface

+ + For details about configuring the ScalarDB Cluster Java SDK for the SQL interface, see [ScalarDB Cluster SQL client configurations](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations). + +

Use the JDBC API

+ + For details about the JDBC API, see [ScalarDB JDBC Guide](../scalardb-sql/jdbc-guide.mdx). + +:::note + +The following limitations apply to non-transactional storage operations: + +- Beginning a transaction is not supported. +- Executing multiple mutations in a single SQL statement is not supported. +- The isolation level is always `READ_COMMITTED`. + +::: + +

Learn more

+ + - [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx) + - [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) +
+ +

Configure your Java application

+ + This section describes how to add the ScalarDB SQL API to your project and how to configure it to run non-transactional storage operations by using Java. + +

Add ScalarDB SQL API to your project

+ + You can add the ScalarDB SQL API as a build dependency to your application by using Gradle or Maven. + + Select your build tool, and follow the instructions to add the build dependency for the ScalarDB SQL API to your application. + + + + To add the build dependency for the ScalarDB SQL API by using Gradle, add the following to `build.gradle` in your application: + + ```gradle + dependencies { + implementation 'com.scalar-labs:scalardb-sql:3.15.4' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:3.15.4' + } + ``` + + + To add the build dependency for the ScalarDB SQL API by using Maven, add the following to `pom.xml` in your application: + + ```xml + + + com.scalar-labs + scalardb-sql + 3.15.4 + + + com.scalar-labs + scalardb-cluster-java-client-sdk + 3.15.4 + + + ``` + + + +

Configure the ScalarDB Cluster Java SDK for the SQL interface

+ + For details about configuring the ScalarDB Cluster Java SDK for the SQL interface, see [ScalarDB Cluster SQL client configurations](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations). + +

Use the Java API

+ + For details about the SQL API, see [ScalarDB SQL API Guide](../scalardb-sql/sql-api-guide.mdx). + +:::note + +The following limitations apply to non-transactional storage operations: + +- Beginning a transaction is not supported. +- Executing multiple mutations in a single SQL statement is not supported. +- The isolation level is always `READ_COMMITTED`. + +::: + + +

Learn more

+ + - [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.15.4/index.html) + +
+
diff --git a/versioned_docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx b/versioned_docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx new file mode 100644 index 00000000..f3677a25 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster-sql.mdx @@ -0,0 +1,298 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Transactions Through ScalarDB Cluster SQL + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to configure your ScalarDB properties file and creating schemas to run transactions through a one-phase or a two-phase commit interface by using ScalarDB Cluster SQL. + +:::warning + +You need to have a license key (trial license or commercial license) for ScalarDB Cluster. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). + +::: + +## Preparation + +For the purpose of this guide, you will set up a database and ScalarDB Cluster in standalone mode by using a sample in the ScalarDB samples repository. + +:::note + +ScalarDB Cluster in standalone mode is primarily for development and testing purposes. + +::: + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the necessary files by running the following command: + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode +``` + +## Set up a database + +Select your database, and follow the instructions to configure it for ScalarDB Cluster. + +For a list of databases that ScalarDB supports, see [Databases](../requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for MySQL in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for PostgreSQL in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Oracle Database in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for SQL Server in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Amazon DynamoDB Local in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB Cluster

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Apache Cassandra, run the following command: + + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Cassandra in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +For a comprehensive list of configurations for ScalarDB Cluster SQL, see [ScalarDB Cluster SQL client configurations](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations). + +## Set up ScalarDB Cluster in standalone mode + +To set up ScalarDB Cluster in standalone mode, you'll need to set a license key and then start ScalarDB Cluster. + +### Set the license key + +Set the license key (trial license or commercial license) for the ScalarDB Clusters in the properties file. For details, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + +### Start ScalarDB Cluster in standalone mode + +To start ScalarDB Cluster in standalone mode, run the following command: + +:::note + +If you want to change other configurations for ScalarDB Cluster, update the `scalardb-cluster-node.properties` file before running the command below. + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## Create or import a schema + +ScalarDB has its own data model and schema that maps to the implementation-specific data model and schema. + +- **Need to create a database schema?** See [SQL CLI](developer-guide-for-scalardb-cluster-with-java-api.mdx#sql-cli). +- **Need to import an existing database?** See [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](../schema-loader-import.mdx). + +## Run transactions + +You can run transactions by using a one-phase or a two-phase commit interface. Select your method for running transactions. + + + +

One-phase commit interface

+ + For details about how to run transactions by using a one-phase commit interface, see the [ScalarDB SQL JDBC Guide](../scalardb-sql/jdbc-guide.mdx). + +:::note + +Documentation for how to run transactions in a two-phase commit interface is coming soon. + +::: +
+ +

One-phase commit interface

+ + For details about how to run transactions by using a one-phase commit interface, see the [ScalarDB SQL API Guide](../scalardb-sql/sql-api-guide.mdx). + +:::note + +Documentation for how to run transactions in a two-phase commit interface is coming soon. + +::: + +

Learn more

+ + To learn more about running transactions by using ScalarDB Cluster SQL, see the following: + + - [ScalarDB Cluster SQL gRPC API Guide](scalardb-cluster-sql-grpc-api-guide.mdx) +
+ +

One-phase or two-phase commit interface

+ + For details about how to run transactions by using a one-phase or a two-phase commit interface, see the [Getting Started with LINQ in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/getting-started-with-linq.mdx#manage-transactions). +
+ +

One-phase commit interface

+ + For details about how to run transactions by using a one-phase commit interface, see the [Getting Started with Distributed SQL Transactions in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions.mdx). + +:::note + +Documentation for how to run transactions in a two-phase commit interface is coming soon. For now, please refer to [Getting Started with Distributed Transactions with a Two-Phase Commit Interface in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx). + +::: +
+
diff --git a/versioned_docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx b/versioned_docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx new file mode 100644 index 00000000..1d9ed0c1 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/run-transactions-through-scalardb-cluster.mdx @@ -0,0 +1,303 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Transactions Through ScalarDB Cluster + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This guide explains how to configure your ScalarDB properties file and create schemas to run transactions through a one-phase or a two-phase commit interface by using ScalarDB Cluster. + +:::warning + +You need to have a license key (trial license or commercial license) for ScalarDB Cluster. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). + +::: + +## Preparation + +For the purpose of this guide, you will set up a database and ScalarDB Cluster in standalone mode by using a sample in the ScalarDB samples repository. + +:::note + +ScalarDB Cluster in standalone mode is primarily for development and testing purposes. + +::: + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the necessary files by running the following command: + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode +``` + +## Set up a database + +Select your database, and follow the instructions to configure it for ScalarDB Cluster. + +For a list of databases that ScalarDB supports, see [Databases](../requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB Cluster

+ + The `scalardb-cluster-node.properties` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for MySQL in the `scalardb-cluster-node.properties` file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB Cluster

+ + The `scalardb-cluster-node.properties` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for PostgreSQL in the `scalardb-cluster-node.properties` file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB Cluster

+ + The `scalardb-cluster-node.properties` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Oracle Database in the `scalardb-cluster-node.properties` file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for SQL Server in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Amazon DynamoDB Local in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB Cluster

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Apache Cassandra, run the following command: + + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Cassandra in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +For a comprehensive list of configurations for ScalarDB Cluster, see [ScalarDB Cluster Configurations](developer-guide-for-scalardb-cluster-with-java-api.mdx#client-configurations). + +## Set up ScalarDB Cluster in standalone mode + +To set up ScalarDB Cluster in standalone mode, you'll need to set a license key and then start ScalarDB Cluster. + +### Set the license key + +Set the license key (trial license or commercial license) for the ScalarDB Clusters in the properties file. For details, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + +### Start ScalarDB Cluster in standalone mode + +To start ScalarDB Cluster in standalone mode, run the following command: + +:::note + +If you want to change other configurations for ScalarDB Cluster, update the `scalardb-cluster-node.properties` file before running the command below. + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## Create or import a schema + +ScalarDB has its own data model and schema that maps to the implementation-specific data model and schema. + +- **Need to create a database schema?** See [ScalarDB Schema Loader](../schema-loader.mdx). +- **Need to import an existing database?** See [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](../schema-loader-import.mdx). + +## Run transactions + +You can run transactions by using a one-phase or a two-phase commit interface. Select your method for running transactions. + +:::note + +If you are building a monolithic application, you should use the one-phase commit interface. However, if you are building a microservice application, see [ScalarDB Cluster Deployment Patterns for Microservices](./deployment-patterns-for-microservices.mdx) to decide which interface to use. + +::: + + + +

One-phase commit interface

+ + For details about how to run transactions by using a one-phase commit interface, see the [ScalarDB Java API Guide](../api-guide.mdx#transactional-api). + +:::note + +To try running transactions by using a one-phase commit interface, see the following sample tutorials: + +- [Create a Sample Application That Supports Multi-Storage Transactions](../scalardb-samples/multi-storage-transaction-sample/README.mdx) +- [Sample application of Spring Data JDBC for ScalarDB with Multi-storage Transactions](../scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx) + +::: + +

Two-phase commit interface

+ + For details about how to run transactions by using a two-phase commit interface, see [Transactions with a Two-Phase Commit Interface](../two-phase-commit-transactions.mdx). + +:::note + +To try running transactions by using a two-phase commit interface, see the following sample tutorials: + +- [Create a Sample Application That Supports Microservice Transactions](../scalardb-samples/microservice-transaction-sample/README.mdx) +- [Sample application of Spring Data JDBC for ScalarDB with Microservice Transactions](../scalardb-samples/spring-data-microservice-transaction-sample/README.mdx) + +::: + +

Learn more

+ + To learn more about running transactions by using ScalarDB Cluster, see the following: + + - [ScalarDB Cluster gRPC API Guide](scalardb-cluster-grpc-api-guide.mdx) +
+ +

One-phase commit interface

+ + For details about how to run transactions by using a one-phase commit interface, see the [Getting Started with Distributed Transactions in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions.mdx). + +

Two-phase commit interface

+ + For details about how to run transactions by using a two-phase commit interface, see [Getting Started with Distributed Transactions with a Two-Phase Commit Interface in the ScalarDB Cluster .NET Client SDK](../scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions.mdx). +
+
diff --git a/versioned_docs/version-3.15/scalardb-cluster/scalardb-abac-status-codes.mdx b/versioned_docs/version-3.15/scalardb-cluster/scalardb-abac-status-codes.mdx new file mode 100644 index 00000000..35df2526 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/scalardb-abac-status-codes.mdx @@ -0,0 +1,726 @@ +--- +tags: + - Enterprise Premium Option + - Private Preview +displayed_sidebar: docsEnglish +--- + +# Attribute-Based Access Control Error Codes + +This page provides a list of error codes related to attribute-based access control. + +## Error code classes and descriptions + +| Class | Description | +|:----------------|:----------------------------------------------| +| `DB-ABAC-1xxxx` | Errors for the user error category | +| `DB-ABAC-2xxxx` | Errors for the concurrency error category | +| `DB-ABAC-3xxxx` | Errors for the internal error category | + +## `DB-ABAC-1xxxx` status codes + +The following are status codes and messages for the user error category. + +### `DB-ABAC-10000` + +**Message** + +```markdown +The put operation is not supported. Use insert, upsert, or update instead +``` + +### `DB-ABAC-10001` + +**Message** + +```markdown +The default level must be less than or equal to the level. Default-level short name: %s; Default-level number: %d; Level short name: %s; Level number: %d +``` + +### `DB-ABAC-10002` + +**Message** + +```markdown +The row level must be less than or equal to the level. Row-level short name: %s; Row-level number: %d; Level short name: %s; Level number: %d +``` + +### `DB-ABAC-10003` + +**Message** + +```markdown +The operation does not have the target namespace or table name. Operation: %s +``` + +### `DB-ABAC-10004` + +**Message** + +```markdown +The policy does not exist. Policy: %s +``` + +### `DB-ABAC-10005` + +**Message** + +```markdown +The level does not exist. Policy: %s; Level short name: %s +``` + +### `DB-ABAC-10006` + +**Message** + +```markdown +The compartment does not exist. Policy: %s; Compartment short name: %s +``` + +### `DB-ABAC-10007` + +**Message** + +```markdown +The group does not exist. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-10008` + +**Message** + +```markdown +The policy already exists. Policy: %s +``` + +### `DB-ABAC-10009` + +**Message** + +```markdown +The data tag column name is already in use in the policy %s. Policy: %s; Data tag column name: %s +``` + +### `DB-ABAC-10010` + +**Message** + +```markdown +The level already exists. Policy: %s; Level short name: %s +``` + +### `DB-ABAC-10011` + +**Message** + +```markdown +The compartment already exists. Policy: %s; Compartment short name: %s +``` + +### `DB-ABAC-10012` + +**Message** + +```markdown +The group already exists. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-10013` + +**Message** + +```markdown +The parent group does not exist. Policy: %s; Group short name: %s; Parent-group short name: %s +``` + +### `DB-ABAC-10014` + +**Message** + +```markdown +The parent group is the same as the child group. Policy: %s; Group short name: %s; Parent-group short name: %s +``` + +### `DB-ABAC-10015` + +**Message** + +```markdown +The group has child groups. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-10016` + +**Message** + +```markdown +The compartment cannot be a row compartment for read-only access mode. Policy: %s; User: %s; Compartment short name: %s +``` + +### `DB-ABAC-10017` + +**Message** + +```markdown +The compartment is already assigned to the user. Policy: %s; User: %s; Compartment short name: %s +``` + +### `DB-ABAC-10018` + +**Message** + +```markdown +The group cannot be a row group for read-only access mode. Policy: %s; User: %s; Group short name: %s +``` + +### `DB-ABAC-10019` + +**Message** + +```markdown +The group is already assigned to the user. Policy: %s; User: %s; Group short name: %s +``` + +### `DB-ABAC-10020` + +**Message** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-ABAC-10021` + +**Message** + +```markdown +The namespace policy already exists. NamespacePolicy: %s +``` + +### `DB-ABAC-10022` + +**Message** + +```markdown +The namespace policy does not exist. NamespacePolicy: %s +``` + +### `DB-ABAC-10023` + +**Message** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-ABAC-10024` + +**Message** + +```markdown +The table policy already exists. TablePolicy: %s +``` + +### `DB-ABAC-10025` + +**Message** + +```markdown +The table policy does not exist. TablePolicy: %s +``` + +### `DB-ABAC-10026` + +**Message** + +```markdown +The short name must not be empty. Short name: %s +``` + +### `DB-ABAC-10027` + +**Message** + +```markdown +The short name must be 30 characters or less. Short name: %s +``` + +### `DB-ABAC-10028` + +**Message** + +```markdown +The short name must not contain a colon. Short name: %s +``` + +### `DB-ABAC-10029` + +**Message** + +```markdown +The short name must not contain a comma. Short name: %s +``` + +### `DB-ABAC-10030` + +**Message** + +```markdown +The data tag is invalid. Data tag: %s +``` + +### `DB-ABAC-10031` + +**Message** + +```markdown +The level must be specified in the data tag. Data tag: %s +``` + +### `DB-ABAC-10032` + +**Message** + +```markdown +The user tag is invalid. User tag: %s +``` + +### `DB-ABAC-10033` + +**Message** + +```markdown +The level must be specified in the user tag. User tag: %s +``` + +### `DB-ABAC-10034` + +**Message** + +```markdown +The specified user tag is not allowed. User tag: %s +``` + +### `DB-ABAC-10035` + +**Message** + +```markdown +The data tag column type should be TEXT. Policy: %s; Data tag column: %s +``` + +### `DB-ABAC-10036` + +**Message** + +```markdown +The specified data tag is not allowed. Data tag: %s +``` + +### `DB-ABAC-10037` + +**Message** + +```markdown +The data tag column cannot be used in conditions. Operation: %s; Data tag column: %s +``` + +### `DB-ABAC-10038` + +**Message** + +```markdown +The operation is not allowed for the policy. Policy: %s; Operation: %s +``` + +### `DB-ABAC-10039` + +**Message** + +```markdown +Access denied: Invalid auth token +``` + +### `DB-ABAC-10040` + +**Message** + +```markdown +The authentication and authorization feature must be enabled to use the attribute-based access control feature +``` + +### `DB-ABAC-10041` + +**Message** + +```markdown +The single CRUD operation transaction manager does not support the attribute-based access control feature +``` + +### `DB-ABAC-10042` + +**Message** + +```markdown +The data tag column cannot be used in ordering. Operation: %s; Data tag column: %s +``` + +### `DB-ABAC-10043` + +**Message** + +```markdown +The namespace policy for the policy and namespace already exists. Policy: %s; Namespace: %s +``` + +### `DB-ABAC-10044` + +**Message** + +```markdown +The table policy for the policy and table already exists. Policy: %s; Table: %s +``` + +## `DB-ABAC-2xxxx` status codes + +The following are status codes and messages for the concurrency error category. + +### `DB-ABAC-20000` + +**Message** + +```markdown +The record does not exist, so the %s condition is not satisfied +``` + +## `DB-ABAC-3xxxx` status codes + +The following are status codes and messages for the internal error category. + +### `DB-ABAC-30000` + +**Message** + +```markdown +Creating a policy failed. Policy: %s; Data tag column: %s +``` + +### `DB-ABAC-30001` + +**Message** + +```markdown +Enabling the policy failed. Policy: %s +``` + +### `DB-ABAC-30002` + +**Message** + +```markdown +Disabling the policy failed. Policy: %s +``` + +### `DB-ABAC-30003` + +**Message** + +```markdown +Getting the policy failed. Policy: %s +``` + +### `DB-ABAC-30004` + +**Message** + +```markdown +Getting the policies failed +``` + +### `DB-ABAC-30005` + +**Message** + +```markdown +Creating a level failed. Policy: %s; Level short name: %s; Level long name: %s; Level number: %d +``` + +### `DB-ABAC-30006` + +**Message** + +```markdown +Dropping the level failed. Policy: %s; Level short name: %s +``` + +### `DB-ABAC-30007` + +**Message** + +```markdown +Getting the level failed. Policy: %s; Level short name: %s +``` + +### `DB-ABAC-30008` + +**Message** + +```markdown +Getting the levels failed. Policy: %s +``` + +### `DB-ABAC-30009` + +**Message** + +```markdown +Creating a compartment failed. Policy: %s; Compartment short name: %s; Compartment long name: %s +``` + +### `DB-ABAC-30010` + +**Message** + +```markdown +Dropping the compartment failed. Policy: %s; Compartment short name: %s +``` + +### `DB-ABAC-30011` + +**Message** + +```markdown +Getting the compartment failed. Policy: %s; Compartment short name: %s +``` + +### `DB-ABAC-30012` + +**Message** + +```markdown +Getting the compartments failed. Policy: %s +``` + +### `DB-ABAC-30013` + +**Message** + +```markdown +Creating a group failed. Policy: %s; Group short name: %s; Group long name: %s; Parent-group short name: %s +``` + +### `DB-ABAC-30014` + +**Message** + +```markdown +Dropping the group failed. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-30015` + +**Message** + +```markdown +Getting the group failed. Policy: %s; Group short name: %s +``` + +### `DB-ABAC-30016` + +**Message** + +```markdown +Getting groups failed. Policy: %s +``` + +### `DB-ABAC-30017` + +**Message** + +```markdown +Getting child groups failed. Policy: %s; Parent-group short name: %s +``` + +### `DB-ABAC-30018` + +**Message** + +```markdown +Setting the levels to the user failed. Policy: %s; User: %s; Level short name: %s; Default-level short name: %s; Row-level short name: %s +``` + +### `DB-ABAC-30019` + +**Message** + +```markdown +Adding the compartment to the user failed. Policy: %s; User: %s; Compartment short name: %s +``` + +### `DB-ABAC-30020` + +**Message** + +```markdown +Removing the compartment from the user failed. Policy: %s; User: %s; Compartment short name: %s +``` + +### `DB-ABAC-30021` + +**Message** + +```markdown +Adding the group to the user failed. Policy: %s; User: %s; Group short name: %s +``` + +### `DB-ABAC-30022` + +**Message** + +```markdown +Removing the group from the user failed. Policy: %s; User: %s; Group short name: %s +``` + +### `DB-ABAC-30023` + +**Message** + +```markdown +Dropping the user tag information from the user failed. Policy: %s; User: %s +``` + +### `DB-ABAC-30024` + +**Message** + +```markdown +Getting the user tag information failed. Policy: %s; User: %s +``` + +### `DB-ABAC-30025` + +**Message** + +```markdown +Creating a namespace policy failed. NamespacePolicy: %s; Policy: %s; Namespace: %s +``` + +### `DB-ABAC-30026` + +**Message** + +```markdown +Enabling the namespace policy failed. NamespacePolicy: %s +``` + +### `DB-ABAC-30027` + +**Message** + +```markdown +Disabling the namespace policy failed. NamespacePolicy: %s +``` + +### `DB-ABAC-30028` + +**Message** + +```markdown +Removing the namespace policies assigned to the namespace failed. Namespace: %s +``` + +### `DB-ABAC-30029` + +**Message** + +```markdown +Getting the namespace policies failed +``` + +### `DB-ABAC-30030` + +**Message** + +```markdown +Creating a table policy failed. TablePolicy: %s; Policy: %s; Table: %s +``` + +### `DB-ABAC-30031` + +**Message** + +```markdown +Enabling the table policy failed. TablePolicy: %s +``` + +### `DB-ABAC-30032` + +**Message** + +```markdown +Disabling the table policy failed. TablePolicy: %s +``` + +### `DB-ABAC-30033` + +**Message** + +```markdown +Removing the table policies assigned to the table failed. Table: %s +``` + +### `DB-ABAC-30034` + +**Message** + +```markdown +Getting the table policies failed +``` + +### `DB-ABAC-30035` + +**Message** + +```markdown +Getting the policies assigned to the namespace failed. Namespace: %s +``` + +### `DB-ABAC-30036` + +**Message** + +```markdown +Getting the policies assigned to the table failed. Table: %s +``` + +### `DB-ABAC-30037` + +**Message** + +```markdown +Registering the data tag failed. Policy: %s; Data tag: %s +``` + +### `DB-ABAC-30038` + +**Message** + +```markdown +Getting the data tags failed. Policy: %s +``` + +### `DB-ABAC-30039` + +**Message** + +```markdown +Getting the namespace policy failed. NamespacePolicy: %s +``` + +### `DB-ABAC-30040` + +**Message** + +```markdown +Getting the table policy failed. TablePolicy: %s +``` diff --git a/versioned_docs/version-3.15/scalardb-cluster/scalardb-auth-status-codes.mdx b/versioned_docs/version-3.15/scalardb-cluster/scalardb-auth-status-codes.mdx new file mode 100644 index 00000000..00ef8e73 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/scalardb-auth-status-codes.mdx @@ -0,0 +1,305 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Authentication and Authorization Error Codes + +This page provides a list of error codes related to authentication and authorization. + +## Error code classes and descriptions + +| Class | Description | +|:----------------|:---------------------------------------| +| `DB-AUTH-1xxxx` | Errors for the user error category | +| `DB-AUTH-3xxxx` | Errors for the internal error category | + +## `DB-AUTH-1xxxx` status codes + +The following are status codes and messages for the user error category. + +### `DB-AUTH-10000` + +**Message** + +```markdown +The user already exists. Username: %s +``` + +### `DB-AUTH-10001` + +**Message** + +```markdown +The user does not exist. Username: %s +``` + +### `DB-AUTH-10003` + +**Message** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-AUTH-10004` + +**Message** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-AUTH-10005` + +**Message** + +```markdown +Invalid username or password +``` + +### `DB-AUTH-10006` + +**Message** + +```markdown +Access denied: Invalid auth token +``` + +### `DB-AUTH-10007` + +**Message** + +```markdown +Access denied: You need the %s privilege on the namespace %s to execute this operation +``` + +### `DB-AUTH-10008` + +**Message** + +```markdown +Access denied: You need the %s privilege on the table %s to execute this operation +``` + +### `DB-AUTH-10009` + +**Message** + +```markdown +Access denied: You must be a superuser to execute this operation +``` + +### `DB-AUTH-10010` + +**Message** + +```markdown +Access denied: You can't access information about the user %s +``` + +### `DB-AUTH-10011` + +**Message** + +```markdown +Access denied: You can't alter the user %s +``` + +### `DB-AUTH-10012` + +**Message** + +```markdown +Access denied: You must be a superuser to change the SUPERUSER attribute +``` + +### `DB-AUTH-10013` + +**Message** + +```markdown +You can't change the SUPERUSER attribute for the current user %s +``` + +### `DB-AUTH-10014` + +**Message** + +```markdown +You can't drop the current user %s +``` + +### `DB-AUTH-10015` + +**Message** + +```markdown +Access denied: You can't grant the %s privilege because you don't have the same privilege on the table %s +``` + +### `DB-AUTH-10016` + +**Message** + +```markdown +Access denied: You can't grant the %s privilege because you don't have the same privilege on the namespace %s +``` + +### `DB-AUTH-10017` + +**Message** + +```markdown +Access denied: You can't revoke the %s privilege because you don't have the same privilege on the table %s +``` + +### `DB-AUTH-10018` + +**Message** + +```markdown +Access denied: You can't revoke the %s privilege because you don't have the same privilege on the namespace %s +``` + +### `DB-AUTH-10019` + +**Message** + +```markdown +The operation does not have the target namespace or table name. Operation: %s +``` + +## `DB-AUTH-3xxxx` status codes + +The following are status codes and messages for the internal error category. + +### `DB-AUTH-30000` + +**Message** + +```markdown +Getting auth token information failed +``` + +### `DB-AUTH-30001` + +**Message** + +```markdown +Getting the user failed. Username: %s +``` + +### `DB-AUTH-30002` + +**Message** + +```markdown +Creating a user failed. Username: %s +``` + +### `DB-AUTH-30003` + +**Message** + +```markdown +Altering the user failed. Username: %s +``` + +### `DB-AUTH-30004` + +**Message** + +```markdown +Dropping the user failed. Username: %s +``` + +### `DB-AUTH-30005` + +**Message** + +```markdown +Granting privileges failed. Username: %s; Namespace: %s; Privileges: %s +``` + +### `DB-AUTH-30006` + +**Message** + +```markdown +Granting privileges failed. Username: %s; Table: %s; Privileges: %s +``` + +### `DB-AUTH-30007` + +**Message** + +```markdown +Revoking privileges failed. Username: %s; Namespace: %s; Privileges: %s +``` + +### `DB-AUTH-30008` + +**Message** + +```markdown +Revoking privileges failed. Username: %s; Table: %s; Privileges: %s +``` + +### `DB-AUTH-30009` + +**Message** + +```markdown +Getting users failed +``` + +### `DB-AUTH-30010` + +**Message** + +```markdown +Getting privileges failed. Username: %s; Namespace: %s +``` + +### `DB-AUTH-30011` + +**Message** + +```markdown +Getting privileges failed. Username: %s; Table: %s +``` + +### `DB-AUTH-30012` + +**Message** + +```markdown +Deleting privileges failed. Namespace: %s +``` + +### `DB-AUTH-30013` + +**Message** + +```markdown +Deleting privileges failed. Table: %s +``` + +### `DB-AUTH-30014` + +**Message** + +```markdown +Logging in failed. Username: %s +``` + +### `DB-AUTH-30015` + +**Message** + +```markdown +Logging out failed +``` diff --git a/versioned_docs/version-3.15/scalardb-cluster/scalardb-auth-with-sql.mdx b/versioned_docs/version-3.15/scalardb-cluster/scalardb-auth-with-sql.mdx new file mode 100644 index 00000000..afeb17f5 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/scalardb-auth-with-sql.mdx @@ -0,0 +1,379 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Authenticate and Authorize Users + +import JavadocLink from '/src/theme/JavadocLink.js'; +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +ScalarDB Cluster has a mechanism to authenticate and authorize users. + +This guide describes how to use authentication and authorization in ScalarDB SQL. + +:::tip + +You can also do authentication and authorization by using the primitive interface. For details, see , which implements . + +::: + +## Overview + +By using authentication and authorization, you can create users and grant or revoke their privileges. You can create a user by using the `CREATE USER` command, and you can grant or revoke one's privileges on a table or a namespace by using the `GRANT` or `REVOKE` command, respectively. For details about such data control language (DCL) commands, see [DCL](../scalardb-sql/grammar.mdx#dcl). + +Users can log in to ScalarDB Cluster with a username and a password and execute SQL statements if they have the required privileges. + +Authentication and authorization support two types of users: + +- **Superusers:** This type of user has all privileges. Only superusers can create or drop other users and namespaces. +- **Normal users:** This type of user initially doesn't have any privileges, so they need to be granted privileges by a superuser or another user who has the `GRANT` privilege. + +The following privileges are available when using authentication and authorization: + +- `SELECT` +- `INSERT` +- `UPDATE` +- `DELETE` +- `CREATE` +- `DROP` +- `TRUNCATE` +- `ALTER` +- `GRANT` + +For details about privileges, see [Which privileges are required for each type of operation](#which-privileges-are-required-for-each-type-of-operation). + +## Configurations + +This section describes the available configurations for authentication and authorization. + +### ScalarDB Cluster node configurations + +To enable authentication and authorization, you need to set `scalar.db.cluster.auth.enabled` to `true`. + +| Name | Description | Default | +|----------------------------------|------------------------------------|---------| +| `scalar.db.cluster.auth.enabled` | Whether authentication and authorization are enabled. | `false` | + +You can also set the following configurations: + +| Name | Description | Default | +|----------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|--------------------| +| `scalar.db.cluster.auth.cache_expiration_time_millis` | Cache expiration time for authentication and authorization information in milliseconds. | `60000` (1 minute) | +| `scalar.db.cluster.auth.auth_token_expiration_time_minutes` | Authentication and authorization token expiration time in minutes. | `1440` (1 day) | +| `scalar.db.cluster.auth.auth_token_gc_thread_interval_minutes` | Authentication and authorization token garbage collection (GC) thread interval in minutes. | `360` (6 hours) | +| `scalar.db.cluster.auth.pepper` | A secret value added to a password before hashing. If not specified, the password is hashed without pepper. | | + +:::note + +If you enable authentication and authorization, you will also need to set `scalar.db.cross_partition_scan.enabled` to `true` for the system namespace (`scalardb` by default) because authentication and authorization perform cross-partition scans internally. + +::: + +### ScalarDB Cluster Java client SDK configurations + +To enable authentication and authorization on the client side, you need to set `scalar.db.cluster.auth.enabled` to `true`. + +| Name | Description | Default | +|----------------------------------|-----------------------------------|---------| +| `scalar.db.cluster.auth.enabled` | Whether authentication and authorization are enabled. | `false` | + +In addition to the configuration in the [ScalarDB Cluster SQL client configurations](developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations) section, you also need to set `scalar.db.sql.cluster_mode.username` and `scalar.db.sql.cluster_mode.password` to specify the username and password of the client. + +| Name | Description | Default | +|---------------------------------------|-----------------------------|---------| +| `scalar.db.sql.cluster_mode.username` | The username of the client. | | +| `scalar.db.sql.cluster_mode.password` | The password of the client. | | + +## Initial user + +When you enable authentication and authorization, the initial user `admin` is created and the initial password of that user is `admin`. This user is a superuser and has all privileges. You can log in with this user and create other users if necessary. + +:::warning + +For security purposes, be sure to change the password of the initial user, especially before deploying to a production environment. + +::: + +## Which privileges are required for each type of operation + +The following tables show which privileges are required for each type of operation: + +### DDL + +| Command | Superuser required | Required privileges | +|-------------------------------|--------------------|---------------------| +| `CREATE NAMESPACE` | `true` | | +| `DROP NAMESPACE` | `true` | | +| `CREATE TABLE` | | `CREATE` | +| `DROP TABLE` | | `DROP` | +| `CREATE INDEX` | | `CREATE` | +| `DROP INDEX` | | `DROP` | +| `TRUNCATE TABLE` | | `TRUNCATE` | +| `ALTER TABLE` | | `ALTER` | +| `CREATE COORDINATOR TABLES` | `true` | | +| `DROP COORDINATOR TABLES` | `true` | | +| `TRUNCATE COORDINATOR TABLES` | `true` | | + +### DML + +| Command | Superuser required | Required privileges | +|----------|--------------------|-----------------------| +| `SELECT` | | `SELECT` | +| `INSERT` | | `INSERT` | +| `UPSERT` | | `INSERT` | +| `UPDATE` | | `SELECT` and `UPDATE` | +| `DELETE` | | `SELECT` and `DELETE` | + +### DCL + +| Command | Superuser required | Required privileges | +|---------------|-----------------------------------------------|----------------------------------------------------------------| +| `CREATE USER` | `true` | | +| `ALTER USER` | `true` (Users can change their own password.) | | +| `DROP USER` | `true` | | +| `GRANT` | | `GRANT` (Users can grant only the privileges that they have.) | +| `REVOKE` | | `GRANT` (Users can revoke only the privileges that they have.) | + +## Limitations + +There are some limitations to the privileges granted or revoked in authentication and authorization: + +- You must grant or revoke `INSERT` and `UPDATE` privileges together. +- To grant a user the `UPDATE` or `DELETE` privilege, the target user must have the `SELECT` privilege. +- If the target user has the `INSERT` or `UPDATE` privilege, you cannot revoke the `SELECT` privilege from them. + +## Wire encryption + +If you enable authentication and authorization, enabling wire encryption to protect the user credentials is strongly recommended, especially in production environments. For details about wire encryption, see [Encrypt Wire Communications](encrypt-wire-communications.mdx). + +## Tutorial - Authenticate and authorize users + +This tutorial explains how to use authentication and authorization. + +### Prerequisites + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This tutorial has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../requirements.mdx). + +::: + + + +### 1. Create the ScalarDB Cluster configuration file + +Create the following configuration file as `scalardb-cluster-node.properties`, replacing `` and `` with your ScalarDB license key and license check certificate values. For more information about the license key and certificate, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + +```properties +scalar.db.storage=jdbc +scalar.db.contact_points=jdbc:postgresql://postgresql:5432/postgres +scalar.db.username=postgres +scalar.db.password=postgres +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.cross_partition_scan.enabled=true +scalar.db.sql.enabled=true + +# Enable authentication and authorization +scalar.db.cluster.auth.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +### 2. Create the Docker Compose file + +Create the following configuration file as `docker-compose.yaml`. + +```yaml +services: + postgresql: + container_name: "postgresql" + image: "postgres:15" + ports: + - 5432:5432 + environment: + - POSTGRES_PASSWORD=postgres + healthcheck: + test: ["CMD-SHELL", "pg_isready || exit 1"] + interval: 1s + timeout: 10s + retries: 60 + start_period: 30s + + scalardb-cluster-standalone: + container_name: "scalardb-cluster-node" + image: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium:3.15.4" + ports: + - 60053:60053 + - 9080:9080 + volumes: + - ./scalardb-cluster-node.properties:/scalardb-cluster/node/scalardb-cluster-node.properties + depends_on: + postgresql: + condition: service_healthy +``` + +### 3. Start PostgreSQL and ScalarDB Cluster + +Run the following command to start PostgreSQL and ScalarDB Cluster in standalone mode. + +```console +docker compose up -d +``` + +It may take a few minutes for ScalarDB Cluster to fully start. + +### 4. Connect to ScalarDB Cluster + +To connect to ScalarDB Cluster, this tutorial uses the SQL CLI, a tool for connecting to ScalarDB Cluster and executing SQL queries. You can download the SQL CLI from the [ScalarDB releases page](https://github.com/scalar-labs/scalardb/releases). + +Create a configuration file named `scalardb-cluster-sql-cli.properties`. This file will be used to connect to ScalarDB Cluster by using the SQL CLI. + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost + +# Enable authentication and authorization +scalar.db.cluster.auth.enabled=true +``` + +Then, start the SQL CLI by running the following command. + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +Enter the username and password as `admin` and `admin`, respectively. + +Now you're ready to use the database with authentication and authorization enabled in ScalarDB Cluster. + +### 5. Create namespaces and a table + +Create namespaces. + +```sql +CREATE NAMESPACE ns1; + +CREATE NAMESPACE ns2; +``` + +Next, create a table in the `ns1` namespaces. + +```sql +CREATE TABLE ns1.tbl ( + id INT PRIMARY KEY, + col1 TEXT, + col2 INT); +``` + +### 6. Create a user + +Create a user named `user1`. + +```sql +CREATE USER user1 WITH PASSWORD 'user1'; +``` + +To check the user, run the following command. + +```sql +SHOW USERS; +``` + +```console ++----------+-------------+ +| username | isSuperuser | ++----------+-------------+ +| user1 | false | +| admin | true | ++----------+-------------+ +``` + +You can see that the `user1` user has been created. + +### 7. Grant privileges + +Grant the `SELECT`, `INSERT`, and `UPDATE` privileges to `user1` on the `ns1.tbl` table. + +```sql +GRANT SELECT, INSERT, UPDATE ON ns1.tbl TO user1; +``` + +Then, grant the `SELECT` privilege to `user1` on the `ns2` namespace. + +```sql +GRANT SELECT ON NAMESPACE ns2 TO user1; +``` + +To check the privileges, run the following command. + +```sql +SHOW GRANTS FOR user1; +``` + +```console ++---------+-----------+-----------+ +| name | type | privilege | ++---------+-----------+-----------+ +| ns2 | NAMESPACE | SELECT | +| ns1.tbl | TABLE | SELECT | +| ns1.tbl | TABLE | INSERT | +| ns1.tbl | TABLE | UPDATE | ++---------+-----------+-----------+ +``` + +You can see that `user1` has been granted the `SELECT`, `INSERT`, and `UPDATE` privileges on the `ns.tbl` table, and the `SELECT` privilege on the `ns2` namespace. + +### 8. Log in as `user1` + +Log in as `user1` and execute SQL statements. + +```console +java -jar scalardb-cluster-sql-cli-3.15.4-all.jar --config scalardb-cluster-sql-cli.properties +``` + +Enter the username and password as `user1` and `user1`, respectively. + +Now you can execute SQL statements as `user1`. + +### 9. Execute DML statements + +Execute the following `INSERT` statement as `user1`. + +```sql +INSERT INTO ns1.tbl VALUES (1, 'a', 1); +``` + +Then, execute the following `SELECT` statement as `user1`. + +```sql +SELECT * FROM ns1.tbl; +``` + +```console ++----+------+------+ +| id | col1 | col2 | ++----+------+------+ +| 1 | a | 1 | ++----+------+------+ +``` + +You can see that `user1` can execute `INSERT` and `SELECT` statements. + +Next, try executing the following `DELETE` statement as `user1`. + +```sql +DELETE FROM ns1.tbl WHERE id = 1; +``` + +```console +Error: Authorization error (PERMISSION_DENIED: SQL-10021: Access denied: You need the DELETE privilege on the table ns1.tbl to execute this operation) (state=SDB11,code=9911) +``` + +You will see the above error message because `user1` doesn't have the `DELETE` privilege on the `ns1.tbl` table. diff --git a/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-configurations.mdx b/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-configurations.mdx new file mode 100644 index 00000000..87051421 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-configurations.mdx @@ -0,0 +1,314 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster Configurations + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +This document describes the configurations for ScalarDB Cluster. ScalarDB Cluster consists of multiple cluster nodes, each of which needs to be configured. The configurations need to be specified in the properties file. + +## Cluster configurations + +This section describes the configurations for ScalarDB Cluster. + +### General configurations + +The following general configurations are available for ScalarDB Cluster. + +#### Transaction management configurations + +| Name | Description | Default | +|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------| +| `scalar.db.transaction_manager` | Transaction manager of ScalarDB. Specify `consensus-commit` to use [Consensus Commit](../consensus-commit.mdx) or `single-crud-operation` to [run non-transactional storage operations](./run-non-transactional-storage-operations-through-scalardb-cluster.mdx). Note that the configurations under the `scalar.db.consensus_commit` prefix are ignored if you use `single-crud-operation`. | `consensus-commit` | +| `scalar.db.consensus_commit.isolation_level` | Isolation level used for Consensus Commit. Either `SNAPSHOT` or `SERIALIZABLE` can be specified. | `SNAPSHOT` | +| `scalar.db.consensus_commit.serializable_strategy` | Serializable strategy used for Consensus Commit. Either `EXTRA_READ` or `EXTRA_WRITE` can be specified. If `SNAPSHOT` is specified in the property `scalar.db.consensus_commit.isolation_level`, this configuration will be ignored. | `EXTRA_READ` | +| `scalar.db.consensus_commit.coordinator.namespace` | Namespace name of Coordinator tables. | `coordinator` | +| `scalar.db.consensus_commit.include_metadata.enabled` | If set to `true`, `Get` and `Scan` operations results will contain transaction metadata. To see the transaction metadata columns details for a given table, you can use the `DistributedTransactionAdmin.getTableMetadata()` method, which will return the table metadata augmented with the transaction metadata columns. Using this configuration can be useful to investigate transaction-related issues. | `false` | + +#### Node configurations + +| Name | Description | Default | +|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------| +| `scalar.db.cluster.membership.type` | Membership type. Currently, only `KUBERNETES` can be specified. | `KUBERNETES` | +| `scalar.db.cluster.membership.kubernetes.endpoint.namespace_name` | This configuration is for the `KUBERNETES` membership type. Namespace name for the [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints). | `default` | +| `scalar.db.cluster.membership.kubernetes.endpoint.name` | This configuration is for the `KUBERNETES` membership type. Name of the [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) to get the membership info. | | +| `scalar.db.cluster.node.decommissioning_duration_secs` | Decommissioning duration in seconds. | `30` | +| `scalar.db.cluster.node.grpc.max_inbound_message_size` | Maximum message size allowed to be received. | The gRPC default value | +| `scalar.db.cluster.node.grpc.max_inbound_metadata_size` | Maximum size of metadata allowed to be received. | The gRPC default value | +| `scalar.db.cluster.node.port` | Port number of the ScalarDB Cluster node. | `60053` | +| `scalar.db.cluster.node.prometheus_exporter_port` | Port number of the Prometheus exporter. | `9080` | +| `scalar.db.cluster.grpc.deadline_duration_millis` | Deadline duration for gRPC in milliseconds. | `60000` (60 seconds) | +| `scalar.db.cluster.node.standalone_mode.enabled` | Whether standalone mode is enabled. Note that if standalone mode is enabled, the membership configurations (`scalar.db.cluster.membership.*`) will be ignored. | `false` | +| `scalar.db.metadata.cache_expiration_time_secs` | ScalarDB has a metadata cache to reduce the number of requests to the database. This setting specifies the expiration time of the cache in seconds. If you specify `-1`, the cache will never expire. | `60` | +| `scalar.db.active_transaction_management.expiration_time_millis` | ScalarDB Cluster nodes maintain ongoing transactions, which can be resumed by using a transaction ID. This configuration specifies the expiration time of this transaction management feature in milliseconds. | `60000` (60 seconds) | +| `scalar.db.system_namespace_name` | The given namespace name will be used by ScalarDB internally. | `scalardb` | +| `scalar.db.transaction.enabled` | Whether the transaction feature is enabled. For example, if you use only the embedding feature, you can set this property to `false`. | `true` | + +### Performance-related configurations + +The following performance-related configurations are available for the Consensus Commit transaction manager: + +| Name | Description | Default | +|----------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------| +| `scalar.db.consensus_commit.parallel_executor_count` | Number of executors (threads) for parallel execution. This number refers to the total number of threads across transactions in a ScalarDB Cluster node or a ScalarDB process. | `128` | +| `scalar.db.consensus_commit.parallel_preparation.enabled` | Whether or not the preparation phase is executed in parallel. | `true` | +| `scalar.db.consensus_commit.parallel_validation.enabled` | Whether or not the validation phase (in `EXTRA_READ`) is executed in parallel. | The value of `scalar.db.consensus_commit.parallel_commit.enabled` | +| `scalar.db.consensus_commit.parallel_commit.enabled` | Whether or not the commit phase is executed in parallel. | `true` | +| `scalar.db.consensus_commit.parallel_rollback.enabled` | Whether or not the rollback phase is executed in parallel. | The value of `scalar.db.consensus_commit.parallel_commit.enabled` | +| `scalar.db.consensus_commit.async_commit.enabled` | Whether or not the commit phase is executed asynchronously. | `false` | +| `scalar.db.consensus_commit.async_rollback.enabled` | Whether or not the rollback phase is executed asynchronously. | The value of `scalar.db.consensus_commit.async_commit.enabled` | +| `scalar.db.consensus_commit.parallel_implicit_pre_read.enabled` | Whether or not implicit pre-read is executed in parallel. | `true` | +| `scalar.db.consensus_commit.coordinator.group_commit.enabled` | Whether or not committing the transaction state is executed in batch mode. This feature can't be used with a two-phase commit interface. | `false` | +| `scalar.db.consensus_commit.coordinator.group_commit.slot_capacity` | Maximum number of slots in a group for the group commit feature. A large value improves the efficiency of group commit, but may also increase latency and the likelihood of transaction conflicts.[^1] | `20` | +| `scalar.db.consensus_commit.coordinator.group_commit.group_size_fix_timeout_millis` | Timeout to fix the size of slots in a group. A large value improves the efficiency of group commit, but may also increase latency and the likelihood of transaction conflicts.[^1] | `40` | +| `scalar.db.consensus_commit.coordinator.group_commit.delayed_slot_move_timeout_millis` | Timeout to move delayed slots from a group to another isolated group to prevent the original group from being affected by delayed transactions. A large value improves the efficiency of group commit, but may also increase the latency and the likelihood of transaction conflicts.[^1] | `1200` | +| `scalar.db.consensus_commit.coordinator.group_commit.old_group_abort_timeout_millis` | Timeout to abort an old ongoing group. A small value reduces resource consumption through aggressive aborts, but may also increase the likelihood of unnecessary aborts for long-running transactions. | `60000` | +| `scalar.db.consensus_commit.coordinator.group_commit.timeout_check_interval_millis` | Interval for checking the group commit–related timeouts. | `20` | +| `scalar.db.consensus_commit.coordinator.group_commit.metrics_monitor_log_enabled` | Whether or not the metrics of the group commit are logged periodically. | `false` | + +### Storage-related configurations + +ScalarDB has a storage (database) abstraction layer that supports multiple storage implementations. You can specify the storage implementation by using the `scalar.db.storage` property. + +Select a database to see the configurations available for each storage. + + + + The following configurations are available for JDBC databases: + + | Name | Description | Default | + |-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| + | `scalar.db.storage` | `jdbc` must be specified. | - | + | `scalar.db.contact_points` | JDBC connection URL. | | + | `scalar.db.username` | Username to access the database. | | + | `scalar.db.password` | Password to access the database. | | + | `scalar.db.jdbc.connection_pool.min_idle` | Minimum number of idle connections in the connection pool. | `20` | + | `scalar.db.jdbc.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool. | `50` | + | `scalar.db.jdbc.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool. Use a negative value for no limit. | `100` | + | `scalar.db.jdbc.prepared_statements_pool.enabled` | Setting this property to `true` enables prepared-statement pooling. | `false` | + | `scalar.db.jdbc.prepared_statements_pool.max_open` | Maximum number of open statements that can be allocated from the statement pool at the same time. Use a negative value for no limit. | `-1` | + | `scalar.db.jdbc.isolation_level` | Isolation level for JDBC. `READ_UNCOMMITTED`, `READ_COMMITTED`, `REPEATABLE_READ`, or `SERIALIZABLE` can be specified. | Underlying-database specific | + | `scalar.db.jdbc.table_metadata.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for the table metadata. | `5` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for the table metadata. | `10` | + | `scalar.db.jdbc.table_metadata.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for the table metadata. Use a negative value for no limit. | `25` | + | `scalar.db.jdbc.admin.connection_pool.min_idle` | Minimum number of idle connections in the connection pool for admin. | `5` | + | `scalar.db.jdbc.admin.connection_pool.max_idle` | Maximum number of connections that can remain idle in the connection pool for admin. | `10` | + | `scalar.db.jdbc.admin.connection_pool.max_total` | Maximum total number of idle and borrowed connections that can be active at the same time for the connection pool for admin. Use a negative value for no limit. | `25` | + +:::note + +If you're using SQLite3 as a JDBC database, you must set `scalar.db.contact_points` as follows: + +```properties +scalar.db.contact_points=jdbc:sqlite:?busy_timeout=10000 +``` + +Unlike other JDBC databases, [SQLite3 doesn't fully support concurrent access](https://www.sqlite.org/lang_transaction.html). +To avoid frequent errors caused internally by [`SQLITE_BUSY`](https://www.sqlite.org/rescode.html#busy), we recommend setting a [`busy_timeout`](https://www.sqlite.org/c3ref/busy_timeout.html) parameter. + +::: + + +The following configurations are available for DynamoDB: + + | Name | Description | Default | + |---------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------| + | `scalar.db.storage` | `dynamo` must be specified. | - | + | `scalar.db.contact_points` | AWS region with which ScalarDB should communicate (e.g., `us-east-1`). | | + | `scalar.db.username` | AWS access key used to identify the user interacting with AWS. | | + | `scalar.db.password` | AWS secret access key used to authenticate the user interacting with AWS. | | + | `scalar.db.dynamo.endpoint_override` | Amazon DynamoDB endpoint with which ScalarDB should communicate. This is primarily used for testing with a local instance instead of an AWS service. | | + | `scalar.db.dynamo.namespace.prefix` | Prefix for the user namespaces and metadata namespace names. Since AWS requires having unique tables names in a single AWS region, this is useful if you want to use multiple ScalarDB environments (development, production, etc.) in a single AWS region. | | + + + The following configurations are available for CosmosDB for NoSQL: + + | Name | Description | Default | + |--------------------------------------|----------------------------------------------------------------------------------------------------------|----------| + | `scalar.db.storage` | `cosmos` must be specified. | - | + | `scalar.db.contact_points` | Azure Cosmos DB for NoSQL endpoint with which ScalarDB should communicate. | | + | `scalar.db.password` | Either a master or read-only key used to perform authentication for accessing Azure Cosmos DB for NoSQL. | | + | `scalar.db.cosmos.consistency_level` | Consistency level used for Cosmos DB operations. `STRONG` or `BOUNDED_STALENESS` can be specified. | `STRONG` | + + + The following configurations are available for Cassandra: + + | Name | Description | Default | + |-----------------------------------------|-----------------------------------------------------------------------|------------| + | `scalar.db.storage` | `cassandra` must be specified. | - | + | `scalar.db.contact_points` | Comma-separated contact points. | | + | `scalar.db.contact_port` | Port number for all the contact points. | | + | `scalar.db.username` | Username to access the database. | | + | `scalar.db.password` | Password to access the database. | | + + + +#### Multi-storage support + +ScalarDB supports using multiple storage implementations simultaneously. You can use multiple storages by specifying `multi-storage` as the value for the `scalar.db.storage` property. + +For details about using multiple storages, see [Multi-Storage Transactions](../multi-storage-transactions.mdx). + +#### Cross-partition scan configurations + +By enabling the cross-partition scan option as described below, the `Scan` operation can retrieve all records across partitions. In addition, you can specify arbitrary conditions and orderings in the cross-partition `Scan` operation by enabling `cross_partition_scan.filtering` and `cross_partition_scan.ordering`, respectively. Currently, the cross-partition scan with ordering option is available only for JDBC databases. To enable filtering and ordering, `scalar.db.cross_partition_scan.enabled` must be set to `true`. + +For details on how to use cross-partition scan, see [Scan operation](../api-guide.mdx#scan-operation). + +:::warning + +For non-JDBC databases, we do not recommend enabling cross-partition scan with the `SERIALIAZABLE` isolation level because transactions could be executed at a lower isolation level (that is, `SNAPSHOT`). When using non-JDBC databases, use cross-partition scan at your own risk only if consistency does not matter for your transactions. + +::: + +| Name | Description | Default | +|----------------------------------------------------|-----------------------------------------------|---------| +| `scalar.db.cross_partition_scan.enabled` | Enable cross-partition scan. | `false` | +| `scalar.db.cross_partition_scan.filtering.enabled` | Enable filtering in cross-partition scan. | `false` | +| `scalar.db.cross_partition_scan.ordering.enabled` | Enable ordering in cross-partition scan. | `false` | + +### GraphQL-related configurations + +The configurations for ScalarDB Cluster GraphQL are as follows: + +| Name | Description | Default | +|-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------|----------------------| +| `scalar.db.graphql.enabled` | Whether ScalarDB Cluster GraphQL is enabled. | `false` | +| `scalar.db.graphql.port` | Port number of the GraphQL server. | `8080` | +| `scalar.db.graphql.path` | Path component of the URL of the GraphQL endpoint. | `/graphql` | +| `scalar.db.graphql.namespaces` | Comma-separated list of namespaces of tables for which the GraphQL server generates a schema. Note that at least one namespace is required. | | +| `scalar.db.graphql.graphiql` | Whether the GraphQL server serves [GraphiQL](https://github.com/graphql/graphiql) IDE. | `true` | +| `scalar.db.graphql.schema_checking_interval_millis` | Interval in milliseconds at which GraphQL server will rebuild the GraphQL schema if any change is detected in the ScalarDB schema. | `30000` (30 seconds) | + +#### Creating or modifying the ScalarDB schema when the server is running + +Since the GraphQL schema is statically built at server startup, if the ScalarDB schema is modified (for example, if a table is added, altered, or deleted), then the corresponding GraphQL schema won't reflect the changes unless it is rebuilt. To address this, the GraphQL server provides two mechanisms: a periodic check and an on-demand check. + +##### Run periodic checks + +The server periodically checks if changes in the ScalarDB schema occur and rebuilds the corresponding GraphQL schema if necessary. By default, the check occurs every 30 seconds, but the interval can be configured by using the `scalar.db.graphql.schema_checking_interval_millis` property. + +If you don't need to run periodic checks, you can disable it by setting the property value to `-1`. + +##### Run on-demand checks + +You can also request the server to check changes in the ScalarDB schema and rebuild the corresponding GraphQL schema if necessary by performing a POST request to the `/update-graphql-schema` endpoint of the HTTP API. + +For example, if the HTTP API is running on `localhost:8080` and the `scalar.db.graphql.path` property is set to `/graphql`, this endpoint can be called by running the following command: + +```console +curl -X POST http://localhost:8080/graphql/update-graphql-schema +``` + +### SQL-related configurations + +The configurations for ScalarDB Cluster SQL are as follows: + +| Name | Description | Default | +|------------------------------------------|----------------------------------------------------------------------------------------------------------|---------------| +| `scalar.db.sql.enabled` | Whether ScalarDB Cluster SQL is enabled. | `false` | +| `scalar.db.sql.statement_cache.enabled` | Enable the statement cache. | `false` | +| `scalar.db.sql.statement_cache.size` | Maximum number of cached statements. | `100` | +| `scalar.db.sql.default_transaction_mode` | Default transaction mode. `TRANSACTION` or `TWO_PHASE_COMMIT_TRANSACTION` can be set. | `TRANSACTION` | +| `scalar.db.sql.default_namespace_name` | Default namespace name. If you don't specify a namespace name in your SQL statement, this value is used. | | + +## Client configurations + +This section describes the general configurations for the ScalarDB Cluster client. + +### Configurations for the primitive interface + +The following table shows the general configurations for the ScalarDB Cluster client. + +| Name | Description | Default | +|----------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------| +| `scalar.db.transaction_manager` | `cluster` should be specified. | - | +| `scalar.db.contact_points` | Contact point of the cluster. If you use the `indirect` client mode, specify the IP address of the load balancer in front of your cluster nodes by using the format `indirect:`. If you use the `direct-kubernetes` client mode, specify the namespace name (optional) and the name of the [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) to get the membership information by using the format `direct-kubernetes:/` or just `direct-kubernetes:`. If you don't specify the namespace name, the client will use the `default` namespace. | | +| `scalar.db.contact_port` | Port number for the contact point. | `60053` | +| `scalar.db.cluster.grpc.deadline_duration_millis` | Deadline duration for gRPC in millis. | `60000` (60 seconds) | +| `scalar.db.cluster.grpc.max_inbound_message_size` | Maximum message size allowed for a single gRPC frame. | The gRPC default value | +| `scalar.db.cluster.grpc.max_inbound_metadata_size` | Maximum size of metadata allowed to be received. | The gRPC default value | + +For example, if you use the `indirect` client mode and the load balancer IP address is `192.168.10.1`, you can configure the client as follows: + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=indirect:192.168.10.1 +``` + +Or if you use the `direct-kubernetes` client mode, with the namespace of the endpoint as `ns` and the endpoint name as `scalardb-cluster`, you can configure the client as follows: + +```properties +scalar.db.transaction_manager=cluster +scalar.db.contact_points=direct-kubernetes:ns/scalardb-cluster +``` + +### Configurations for the SQL interface + +The following table shows the configurations for the ScalarDB Cluster SQL client. + +| Name | Description | Default | +|----------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------| +| `scalar.db.sql.connection_mode` | `cluster` should be specified. | - | +| `scalar.db.sql.cluster_mode.contact_points` | Contact point of the cluster. If you use the `indirect` client mode, specify the IP address of the load balancer in front of your cluster nodes by using the format `indirect:`. If you use the `direct-kubernetes` client mode, specify the namespace name (optional) and the name of the [endpoint resource](https://kubernetes.io/docs/concepts/services-networking/service/#endpoints) to get the membership information by using the format `direct-kubernetes:/` or just `direct-kubernetes:`. If you don't specify the namespace name, the client will use the `default` namespace. | | +| `scalar.db.sql.cluster_mode.contact_port` | Port number for the contact point. | `60053` | +| `scalar.db.sql.default_transaction_mode` | Default transaction mode. `TRANSACTION` or `TWO_PHASE_COMMIT_TRANSACTION` can be set. | `TRANSACTION` | +| `scalar.db.sql.default_namespace_name` | Default namespace name. If you don't specify a namespace name in your SQL statement, this value is used. | | +| `scalar.db.cluster.grpc.deadline_duration_millis` | Deadline duration for gRPC in millis. | `60000` (60 seconds) | +| `scalar.db.cluster.grpc.max_inbound_message_size` | Maximum message size allowed for a single gRPC frame. | The gRPC default value | +| `scalar.db.cluster.grpc.max_inbound_metadata_size` | Maximum size of metadata allowed to be received. | The gRPC default value | + +For example, if you use the `indirect` client mode and the load balancer IP address is `192.168.10.1`, you can configure the client as follows: + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:192.168.10.1 +``` + +Or if you use the `direct-kubernetes` client mode, with the namespace of the endpoint as `ns` and the endpoint name as `scalardb-cluster`, you can configure the client as follows: + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=direct-kubernetes:ns/scalardb-cluster +``` + +For details about how to configure ScalarDB JDBC, see [JDBC connection URL](../scalardb-sql/jdbc-guide.mdx#jdbc-connection-url). + +For details about how to configure Spring Data JDBC for ScalarDB, see [Configurations](../scalardb-sql/spring-data-guide.mdx#configurations). + +## Configuration example - App, ScalarDB Cluster, and database + +```mermaid +flowchart LR + app["App -
ScalarDB library with gRPC"] + cluster["ScalarDB Cluster -
(ScalarDB library with
Consensus Commit)"] + db[(Underlying storage or database)] + app --> cluster --> db +``` + +In this example configuration, the app (ScalarDB library with gRPC) connects to an underlying storage or database (in this case, Cassandra) through ScalarDB Cluster, which is a component that is available only in the ScalarDB Enterprise edition. + +:::note + +This configuration is acceptable for production use because ScalarDB Cluster implements the [Scalar Admin](https://github.com/scalar-labs/scalar-admin) interface, which enables you to take transactionally consistent backups for ScalarDB by pausing ScalarDB Cluster. + +::: + +The following is an example of the configuration for connecting the app to the underlying database through ScalarDB Cluster: + +```properties +# Transaction manager implementation. +scalar.db.transaction_manager=cluster + +# Contact point of the cluster. +scalar.db.contact_points=indirect: +``` + +For details about client configurations, see the [ScalarDB Cluster client configurations](#client-configurations). + +[^1]: It's worth benchmarking the performance with a few variations (for example, 75% and 125% of the default value) on the same underlying storage that your application uses, considering your application's access pattern, to determine the optimal configuration as it really depends on those factors. Also, it's important to benchmark combinations of these parameters (for example, first, `slot_capacity:20` and `group_size_fix_timeout_millis:40`; second, `slot_capacity:30` and `group_size_fix_timeout_millis:40`; and third, `slot_capacity:20` and `group_size_fix_timeout_millis:80`) to determine the optimal combination. diff --git a/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-grpc-api-guide.mdx b/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-grpc-api-guide.mdx new file mode 100644 index 00000000..ac860cd3 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-grpc-api-guide.mdx @@ -0,0 +1,236 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster gRPC API Guide + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This document describes the ScalarDB Cluster gRPC API. + + + +ScalarDB Cluster provides a Java API that uses the gRPC API internally. +If you use Java or a JVM language, you can use the Java API instead of the ScalarDB Cluster gRPC API directly. +For details about the Java API, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +For details about the services and messages for the ScalarDB Cluster gRPC API, see the definitions in the `scalardb-cluster.proto` file. For ScalarDB Cluster users who have a commercial license, please [contact support](https://www.scalar-labs.com/support) if you need the `scalardb-cluster.proto` file. + +ScalarDB Cluster gRPC API is composed of the following services: + +- `scalardb.cluster.rpc.v1.DistributedTransaction`: Provides a distributed transaction capability for ScalarDB Cluster. +- `scalardb.cluster.rpc.v1.TwoPhaseCommitTransaction`: Provides a two-phase commit transaction capability for ScalarDB Cluster. +- `scalardb.cluster.rpc.v1.DistributedTransactionAdmin`: Provides comprehensive administrative operations. + +The following sections describe how to use each service. + +## Overview of error handling in ScalarDB Cluster gRPC API + +Before describing how to use each service, this section explains how error handling works in ScalarDB Cluster gRPC API. + +ScalarDB Cluster gRPC API employs [Richer error model](https://grpc.io/docs/guides/error/#richer-error-model) for error handling. +This model enables servers to return and enables clients to consume additional error details expressed as one or more protobuf messages. +ScalarDB Cluster gRPC API uses `google.rpc.ErrorInfo`, which is one of the [standard set of error message types](https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto), and puts additional error details in `ErrorInfo` fields. + +`ErrorInfo` has the following fields: + +- `reason`: A string that provides a short description of the error. The following sections describe the possible values of `reason` in each service. +- `domain`: A string that indicates the error's origin. In ScalarDB Cluster gRPC API, this string is always set to `com.scalar.db.cluster`. +- `metadata`: A map of metadata for the specific error. In ScalarDB Cluster gRPC API, a transaction ID with the `transactionId` key in the map is put if the error is related to a transaction. + +If you encounter an error, you can retrieve `ErrorInfo` from `google.rpc.Status` in the gRPC response, but the method for doing so depends on the programming language. +Please refer to the appropriate documentation to understand how to get `ErrorInfo` in your specific programming language. + +## How to use the `DistributedTransaction` service + +The `DistributedTransaction` service provides the following RPCs: + +- `Begin`: Begins a transaction. +- `Get`: Retrieves a record. +- `Scan`: Scans records. +- `Put`: Puts a record. +- `Delete`: Deletes a record. +- `Mutate` Mutates (puts and deletes) multiple records. +- `Commit`: Commits a transaction. +- `Rollback`: Rolls back a transaction. + +First, you call `Begin` to initiate a transaction. +Then, you can call `Get` and `Scan` to read records, `Put` and `Mutate` to write records, and `Delete` and `Mutate` to delete records. +To finalize the transaction, call `Commit`. +Alternatively, you can call `Rollback` at any time before the transaction is committed to cancel it. +By calling `Begin`, you receive a transaction ID in the response, which you can then use to call `Get`, `Scan`, `Put`, `Delete`, `Mutate`, `Commit`, and `Rollback`. + +When you call `Begin`, you can optionally specify a transaction ID. +If you specify a transaction ID, the user is responsible for guaranteeing the uniqueness of the ID. +If you do not specify a transaction ID, ScalarDB Cluster will generate a transaction ID for the transaction. + +You need to set `RequestHeader` for each RPC request. +`RequestHeader` contains a `hop_limit` field, which restricts the number of hops for a request. +The purpose of the `hop_limit` is to prevent infinite loops within the cluster. +Each time a request is forwarded to another cluster node, the `hop_limit` decreases by one. +If the `hop_limit` reaches zero, the request will be rejected. + +### Error handling + +The table below shows the status code and the possible values of `reason` in `ErrorInfo` in each RPC in the `DistributedTransaction` service: + +| RPC | Status code | `reason` in `ErrorInfo` | Description | +|--------------------------------|---------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Begin | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Begin | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Begin | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Begin | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Get, Scan, Put, Delete, Mutate | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Get, Scan, Put, Delete, Mutate | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Get, Scan, Put, Delete, Mutate | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Get, Scan, Put, Delete, Mutate | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Get, Scan, Put, Delete, Mutate | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Get, Scan, Put, Delete, Mutate | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Put, Delete, Mutate | FAILED_PRECONDITION | UNSATISFIED_CONDITION | The mutation condition is not satisfied. | +| Commit | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Commit | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Commit | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Commit | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Commit | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Commit | INTERNAL | UNKNOWN_TRANSACTION_STATUS | The status of the transaction is unknown (it is uncertain whether the transaction was successfully committed or not). In this situation, you need to check whether the transaction was successfully committed, and if not, to retry it. The responsibility for determining the transaction status rests with the users. It may be beneficial to create a transaction status table and update it in conjunction with other application data so that you can determine the status of a transaction from the table itself. | +| Commit | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Rollback | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Rollback | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Rollback | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. In case of a rollback, you do not need to retry the transaction because the transaction will expire automatically. | +| Rollback | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. In case of a rollback, you do not need to retry the transaction because the transaction will expire automatically. | +| Rollback | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | + +If you encounter an error, you should roll back the transaction, except in the case of `Begin`. +Then, you can retry the transaction from the beginning for the errors that can be resolved by retrying. + +Besides the errors listed above, you may encounter errors returned by the gRPC library. +In these cases, the response will not contain `ErrorInfo`. +For details, refer to the [gRPC documentation](https://grpc.io/docs/guides/error/#error-status-codes). + +You can set a deadline for each RPC in gRPC. +If the deadline is exceeded, you will receive a `DEADLINE_EXCEEDED` error. +In general, you should roll back the transaction in this situation, unless the RPC is `Begin` or `Commit`. +In the case of `Commit`, the situation is equivalent to `UNKNOWN_TRANSACTION_STATUS` (it is uncertain whether the transaction was successfully committed or not), and you must handle the error in the same way. + +## How to use the `TwoPhaseCommitTransaction` service + +The `TwoPhaseCommitTransaction` service provides the following RPCs: + +- `Begin`: Begins a transaction. +- `Join`: Joins a transaction. +- `Get`: Retrieves a record. +- `Scan`: Scans records. +- `Put`: Puts a record. +- `Delete`: Deletes a record. +- `Mutate`: Mutates (puts and deletes) multiple records. +- `Prepare`: Prepares a transaction. +- `Validate`: Validates a transaction. +- `Commit`: Commits a transaction. +- `Rollback`: Rolls back a transaction. + +First, you call `Begin` to initiate a transaction if you are the coordinator process. +Alternatively, if you are a participant process, you can call `Join` to take part in a transaction that the coordinator has already begun. +Then, you can call `Get` and `Scan` to read records, `Put` and `Mutate` to write records, and `Delete` and `Mutate` to delete records. +To finalize the transaction, call `Prepare`, `Validate`, and then `Commit` in order. +Alternatively, you can call `Rollback` at any time before the transaction is committed to cancel it. +By calling `Begin` or `Join`, you receive a transaction ID in the response, which you can then use to call `Get`, `Scan`, `Put`, `Delete`, `Mutate`, `Prepare`, `Validate`, `Commit`, and `Rollback`. + +When you call `Begin`, you can optionally specify a transaction ID. +If you specify a transaction ID, the user is responsible for guaranteeing the uniqueness of the ID. +If you do not specify a transaction ID, ScalarDB Cluster will generate a transaction ID for the transaction. + +You need to set `RequestHeader` for each RPC request. +`RequestHeader` contains a `hop_limit` field, which restricts the number of hops for a request. +The purpose of the `hop_limit` is to prevent infinite loops within the cluster. +Each time a request is forwarded to another cluster node, the `hop_limit` decreases by one. +If the `hop_limit` reaches zero, the request will be rejected. + +### Error handling + +The table below shows the status code and the possible values of `reason` in `ErrorInfo` in each RPC in the `TwoPhaseCommitTransaction` service: + +| RPC | Status code | `reason` in `ErrorInfo` | Description | +|--------------------------------|---------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Begin, Join | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Begin, Join | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Begin, Join | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Begin, Join | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Get, Scan, Put, Delete, Mutate | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Get, Scan, Put, Delete, Mutate | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Get, Scan, Put, Delete, Mutate | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Get, Scan, Put, Delete, Mutate | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Get, Scan, Put, Delete, Mutate | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Get, Scan, Put, Delete, Mutate | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Put, Delete, Mutate | FAILED_PRECONDITION | UNSATISFIED_CONDITION | The mutation condition is not satisfied. | +| Prepare, Validate | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Prepare, Validate | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Prepare, Validate | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Prepare, Validate | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Prepare, Validate | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Prepare, Validate | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Commit | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Commit | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Commit | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Commit | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Commit | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Commit | INTERNAL | UNKNOWN_TRANSACTION_STATUS | The status of the transaction is unknown (it is uncertain whether the transaction was successfully committed or not). In this situation, you need to check whether the transaction was successfully committed, and if not, to retry it. The responsibility for determining the transaction status rests with the users. It may be beneficial to create a transaction status table and update it in conjunction with other application data so that you can determine the status of a transaction from the table itself. | +| Commit | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Rollback | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Rollback | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Rollback | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. In case of a rollback, you do not need to retry the transaction because the transaction will expire automatically. | +| Rollback | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. In case of a rollback, you do not need to retry the transaction because the transaction will expire automatically. | +| Rollback | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | + +If you encounter an error, you should roll back the transaction, except in the case of `Begin` or `Join`. +Then, you can retry the transaction from the beginning for the errors that can be resolved by retrying. + +Besides the errors listed above, you may encounter errors returned by the gRPC library. +In these cases, the response will not contain `ErrorInfo`. +For details, refer to the [gRPC documentation](https://grpc.io/docs/guides/error/#error-status-codes). + +You can set a deadline for each RPC in gRPC. +If the deadline is exceeded, you will receive a `DEADLINE_EXCEEDED` error. +In general, you should roll back the transaction in this situation, unless the RPC is `Begin`, `Join`, or `Commit`. +In the case of `Commit`, the situation is equivalent to `UNKNOWN_TRANSACTION_STATUS` (it is uncertain whether the transaction was successfully committed or not), and you must handle the error in the same way. + +## How to use the `DistributedTransactionAdmin` service + +The `DistributedTransactionAdmin` service provides the following RPCs: + +- `CreateNamespace`: Creates a namespace. +- `DropNamespace`: Drops a namespace. +- `NamespaceExists`: Returns whether the specified namespace exists or not. +- `CreateTable`: Creates a table. +- `DropTable`: Drops a table. +- `TruncateTable`: Truncates a table. +- `TableExists`: Returns whether the specified table exists or not. +- `CreateIndex`: Creates an index. +- `DropIndex`: Drops an index. +- `IndexExists`: Returns whether the specified index exists or not. +- `RepairTable`: Repairs a namespace that may be in an unknown state. +- `AddNewColumnToTable`: Adds a new column to a table. +- `CreateCoordinatorTables`: Creates the Coordinator tables. +- `DropCoordinatorTables`: Drops the Coordinator tables. +- `TruncateCoordinatorTables`: Truncates the Coordinator tables. +- `CoordinatorTablesExist`: Returns whether the Coordinator tables exist or not. +- `RepairCoordinatorTables`: Repairs the Coordinator tables. +- `GetTableMetadata`: Returns table metadata of the specified table. +- `GetNamespaceTableNames`: Returns tables in the specified namespace. +- `ImportTable`: Imports an existing table that is not managed by ScalarDB. + +### Error handling + +The table below shows the status code and the possible values of `reason` in `ErrorInfo` for all RPCs in the `DistributedTransactionAdmin` service: + +| Status code | `reason` in `ErrorInfo` | Description | +|---------------------|----------------------------|-------------------------------------------------| +| INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| INTERNAL | INTERNAL_ERROR | The operation has failed. | + +Besides the errors listed above, you may encounter errors returned by the gRPC library. +In these cases, the response will not contain `ErrorInfo`. +For details, refer to the [gRPC documentation](https://grpc.io/docs/guides/error/#error-status-codes). diff --git a/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide.mdx b/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide.mdx new file mode 100644 index 00000000..4901626b --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-sql-grpc-api-guide.mdx @@ -0,0 +1,219 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster SQL gRPC API Guide + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This document describes the ScalarDB Cluster SQL gRPC API. + + + +ScalarDB Cluster SQL provides a Java API that uses the gRPC API internally. +If you use Java or a JVM language, you can use the Java API instead of the ScalarDB Cluster SQL gRPC API directly. +For details about the Java API, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). + +For details about the services and messages for the ScalarDB Cluster SQL gRPC API, see the definitions in the `scalardb-cluster-sql.proto` file. For ScalarDB Cluster users who have a commercial license, please [contact support](https://www.scalar-labs.com/support) if you need the `scalardb-cluster-sql.proto` file. + +ScalarDB Cluster SQL gRPC API is composed of the following services: + +- `scalardb.cluster.rpc.v1.sql.SqlTransaction`: Provides a transaction capability for ScalarDB Cluster SQL. +- `scalardb.cluster.rpc.v1.sql.SqlTwoPhaseCommitTransaction`: Provides a two-phase commit transaction capability for ScalarDB Cluster SQL. +- `scalardb.cluster.rpc.v1.sql.Metadata`: Provides a metadata view of ScalarDB Cluster SQL. + +The following sections describe how to use each service. + +## Overview of error handling in ScalarDB Cluster SQL gRPC API + +Before describing how to use each service, this section explains how error handling works in ScalarDB Cluster SQL gRPC API. + +ScalarDB Cluster SQL gRPC API employs [Richer error model](https://grpc.io/docs/guides/error/#richer-error-model) for error handling. +This model enables servers to return and enables clients to consume additional error details expressed as one or more protobuf messages. +ScalarDB Cluster SQL gRPC API uses `google.rpc.ErrorInfo`, which is one of the [standard set of error message types](https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto), and puts additional error details in `ErrorInfo` fields. + +`ErrorInfo` has the following fields: + +- `reason`: A string that provides a short description of the error. The following sections describe the possible values of `reason` in each service. +- `domain`: A string that indicates the error's origin. In ScalarDB Cluster SQL gRPC API, this string is always set to `com.scalar.db.cluster.sql`. +- `metadata`: A map of metadata for the specific error. In ScalarDB Cluster SQL gRPC API, a transaction ID with the `transactionId` key in the map is put if the error is related to a transaction. + +If you encounter an error, you can retrieve `ErrorInfo` from `google.rpc.Status` in the gRPC response, but the method for doing so depends on the programming language. +Please refer to the appropriate documentation to understand how to get `ErrorInfo` in your specific programming language. + +## How to use the `SqlTransaction` service + +The `SqlTransaction` service provides the following RPCs: + +- `Begin`: Begins a transaction. +- `Execute` Executes a SQL statement. +- `Commit`: Commits a transaction. +- `Rollback`: Rolls back a transaction. + +First, you call `Begin` to initiate a transaction. +Following that, you can call `Execute` to read, write, and delete records. +To finalize the transaction, call `Commit`. +Alternatively, you can call `Rollback` at any time before the transaction is committed to cancel it. +By calling `Begin`, you receive a transaction ID in the response, which you can then use to call `Execute`, `Commit`, and `Rollback`. + +Also, you can call `Execute` without a transaction ID to execute a one-shot transaction. +In this case, the transaction is automatically committed after it is executed. +You can use this method to execute DDL statements as well. +For details on the supported SQL statements, refer to [ScalarDB SQL Grammar](../scalardb-sql/grammar.mdx). +Please note, however, that `Execute` supports only DML and DDL statements. + +When you call `Begin`, you can optionally specify a transaction ID. +If you specify a transaction ID, the user is responsible for guaranteeing the uniqueness of the ID. +If you do not specify a transaction ID, ScalarDB Cluster will generate a transaction ID for the transaction. + +You need to set `RequestHeader` for each RPC request. +`RequestHeader` contains a `hop_limit` field, which restricts the number of hops for a request. +The purpose of the `hop_limit` is to prevent infinite loops within the cluster. +Each time a request is forwarded to another cluster node, the `hop_limit` decreases by one. +If the `hop_limit` reaches zero, the request will be rejected. + +### Error handling + +The table below shows the status code and the possible values of `reason` in `ErrorInfo` in each RPC in the `SqlTransaction` service: + +| RPC | Status code | `reason` in `ErrorInfo` | Description | +|----------|---------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Begin | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Begin | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Begin | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Begin | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Execute | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Execute | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Execute | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Execute | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Execute | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Execute | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Commit | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Commit | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Commit | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Commit | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Commit | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Commit | INTERNAL | UNKNOWN_TRANSACTION_STATUS | The status of the transaction is unknown (it is uncertain whether the transaction was successfully committed or not). In this situation, you need to check whether the transaction was successfully committed, and if not, to retry it. The responsibility for determining the transaction status rests with the users. It may be beneficial to create a transaction status table and update it in conjunction with other application data so that you can determine the status of a transaction from the table itself. | +| Commit | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Rollback | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Rollback | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Rollback | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. In case of a rollback, you do not need to retry the transaction because the transaction will expire automatically. | +| Rollback | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. In case of a rollback, you do not need to retry the transaction because the transaction will expire automatically. | +| Rollback | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | + +If you encounter an error, you should roll back the transaction, except in the case of `Begin`. +Then, you can retry the transaction from the beginning for the errors that can be resolved by retrying. + +Besides the errors listed above, you may encounter errors returned by the gRPC library. +In these cases, the response will not contain `ErrorInfo`. +For details, refer to the [gRPC documentation](https://grpc.io/docs/guides/error/#error-status-codes). + +You can set a deadline for each RPC in gRPC. +If the deadline is exceeded, you will receive a `DEADLINE_EXCEEDED` error. +In general, you should roll back the transaction in this situation, unless the RPC is `Begin` or `Commit`. +In the case of `Commit`, the situation is equivalent to `UNKNOWN_TRANSACTION_STATUS` (it is uncertain whether the transaction was successfully committed or not), and you must handle the error in the same way. + +## How to use the `SqlTwoPhaseCommitTransaction` service + +The `SqlTwoPhaseCommitTransaction` service provides the following RPCs: + +- `Begin`: Begins a transaction. +- `Join`: Joins a transaction. +- `Execute` Executes a SQL statement. +- `Prepare`: Prepares a transaction. +- `Validate`: Validates a transaction. +- `Commit`: Commits a transaction. +- `Rollback`: Rolls back a transaction. + +First, you call `Begin` to initiate a transaction if you are the coordinator process. +Alternatively, if you are a participant process, you can call `Join` to take part in a transaction that the coordinator has already begun. +Following that, you can call `Execute` to read, write, and delete records. +To finalize the transaction, call `Prepare`, `Validate`, and then `Commit` in order. +Alternatively, you can call `Rollback` at any time before the transaction is committed to cancel it. +By calling `Begin` or `Join`, you receive a transaction ID in the response, which you can then use to call `Execute`, `Prepare`, `Validate`, `Commit`, and `Rollback`. + +In addition, you can call `Execute` without a transaction ID to execute a one-shot transaction. +In this case, the transaction is automatically committed after it is executed. +You can use this method to execute DDL statements as well. For details on the supported SQL statements, refer to [ScalarDB SQL Grammar](../scalardb-sql/grammar.mdx). +Please note, however, that `Execute` supports only DML and DDL statements. + +When you call `Begin`, you can optionally specify a transaction ID. +If you specify a transaction ID, the user is responsible for guaranteeing the uniqueness of the ID. +If you do not specify a transaction ID, ScalarDB Cluster will generate a transaction ID for the transaction. + +You need to set `RequestHeader` for each RPC request. +`RequestHeader` contains a `hop_limit` field, which restricts the number of hops for a request. +The purpose of the `hop_limit` is to prevent infinite loops within the cluster. +Each time a request is forwarded to another cluster node, the `hop_limit` decreases by one. +If the `hop_limit` reaches zero, the request will be rejected. + +### Error handling + +The table below shows the status code and the possible values of `reason` in `ErrorInfo` in each RPC in the `SqlTwoPhaseCommitTransaction` service: + +| RPC | Status code | `reason` in `ErrorInfo` | Description | +|-------------------|---------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Begin, Join | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Begin, Join | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Begin, Join | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Begin, Join | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Execute | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Execute | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Execute | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Execute | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Execute | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Execute | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Prepare, Validate | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Prepare, Validate | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Prepare, Validate | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Prepare, Validate | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Prepare, Validate | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Prepare, Validate | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Commit | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Commit | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Commit | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. This error indicates that the transaction has expired or the routing information has been updated due to cluster topology changes. In this case, please retry the transaction from the beginning. | +| Commit | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. This occurs when the routing information between cluster nodes is inconsistent. The error is usually resolved in a short amount of time, so you can retry the transaction from the beginning after some time has passed since encountering this error. | +| Commit | FAILED_PRECONDITION | TRANSACTION_CONFLICT | A transaction conflict occurred. If you encounter this error, please retry the transaction from the beginning. | +| Commit | INTERNAL | UNKNOWN_TRANSACTION_STATUS | The status of the transaction is unknown (it is uncertain whether the transaction was successfully committed or not). In this situation, you need to check whether the transaction was successfully committed, and if not, to retry it. The responsibility for determining the transaction status rests with the users. It may be beneficial to create a transaction status table and update it in conjunction with other application data so that you can determine the status of a transaction from the table itself. | +| Commit | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | +| Rollback | INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| Rollback | FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| Rollback | NOT_FOUND | TRANSACTION_NOT_FOUND | The transaction associated with the specified transaction ID was not found. In case of a rollback, you do not need to retry the transaction because the transaction will expire automatically. | +| Rollback | INTERNAL | HOP_LIMIT_EXCEEDED | The hop limit was exceeded. In case of a rollback, you do not need to retry the transaction because the transaction will expire automatically. | +| Rollback | INTERNAL | INTERNAL_ERROR | The operation has failed due to transient or nontransient faults. You can try retrying the transaction from the beginning, but the transaction may still fail if the cause is nontransient. | + +If you encounter an error, you should roll back the transaction, except in the case of `Begin` or `Join`. +Then, you can retry the transaction from the beginning for the errors that can be resolved by retrying. + +Besides the errors listed above, you may encounter errors returned by the gRPC library. +In these cases, the response will not contain `ErrorInfo`. +For details, refer to the [gRPC documentation](https://grpc.io/docs/guides/error/#error-status-codes). + +You can set a deadline for each RPC in gRPC. +If the deadline is exceeded, you will receive a `DEADLINE_EXCEEDED` error. +In general, you should roll back the transaction in this situation, unless the RPC is `Begin`, `Join`, or `Commit`. +In the case of `Commit`, the situation is equivalent to `UNKNOWN_TRANSACTION_STATUS` (it is uncertain whether the transaction was successfully committed or not), and you must handle the error in the same way. + +## How to use the `Metadata` service + +The `Metadata` service provides the following RPCs: + +- `GetNamespaceMetadata`: Retrieves namespace metadata of the specified namespace. +- `ListTableMetadataInNamespace`: Retrieves table metadata of tables in the specified namespace. +- `GetTableMetadata`: Retrieves table metadata of the specified table. + +### Error handling + +The table below shows the status code and the possible values of `reason` in `ErrorInfo` for all RPCs in the `Metadata` service: + +| Status code | `reason` in `ErrorInfo` | Description | +|---------------------|----------------------------|-------------------------------------------------| +| INVALID_ARGUMENT | ILLEGAL_ARGUMENT | The argument in the request message is invalid. | +| FAILED_PRECONDITION | ILLEGAL_STATE | The RPC was called in an invalid state. | +| INTERNAL | INTERNAL_ERROR | The operation has failed. | + +Besides the errors listed above, you may encounter errors returned by the gRPC library. +In these cases, the response will not contain `ErrorInfo`. +For details, refer to the [gRPC documentation](https://grpc.io/docs/guides/error/#error-status-codes). diff --git a/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-status-codes.mdx b/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-status-codes.mdx new file mode 100644 index 00000000..0005c1fa --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/scalardb-cluster-status-codes.mdx @@ -0,0 +1,558 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster Error Codes + +This page provides a list of error codes in ScalarDB Cluster. + +## Error code classes and descriptions + +| Class | Description | +|:-------------------|:------------------------------------------| +| `DB-CLUSTER-1xxxx` | Errors for the user error category | +| `DB-CLUSTER-2xxxx` | Errors for the concurrency error category | +| `DB-CLUSTER-3xxxx` | Errors for the internal error category | + +## `DB-CLUSTER-1xxxx` status codes + +The following are status codes and messages for the user error category. + +### `DB-CLUSTER-10000` + +**Message** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-CLUSTER-10001` + +**Message** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-CLUSTER-10002` + +**Message** + +```markdown +The user does not exist. User: %s +``` + +### `DB-CLUSTER-10003` + +**Message** + +```markdown +ClusterConfig is not specified +``` + +### `DB-CLUSTER-10004` + +**Message** + +```markdown +The get type is unspecified +``` + +### `DB-CLUSTER-10005` + +**Message** + +```markdown +The get type is unrecognized +``` + +### `DB-CLUSTER-10006` + +**Message** + +```markdown +The value of the column is not set. Column: %s +``` + +### `DB-CLUSTER-10007` + +**Message** + +```markdown +The scan type is unspecified +``` + +### `DB-CLUSTER-10008` + +**Message** + +```markdown +The scan type is unrecognized +``` + +### `DB-CLUSTER-10009` + +**Message** + +```markdown +The order is unspecified +``` + +### `DB-CLUSTER-10010` + +**Message** + +```markdown +The order is unrecognized +``` + +### `DB-CLUSTER-10011` + +**Message** + +```markdown +The clustering order is unspecified +``` + +### `DB-CLUSTER-10012` + +**Message** + +```markdown +The clustering order is unrecognized +``` + +### `DB-CLUSTER-10013` + +**Message** + +```markdown +The put condition type is unspecified +``` + +### `DB-CLUSTER-10014` + +**Message** + +```markdown +The put condition type is unrecognized +``` + +### `DB-CLUSTER-10015` + +**Message** + +```markdown +The delete condition type is unspecified +``` + +### `DB-CLUSTER-10016` + +**Message** + +```markdown +The delete condition type is unrecognized +``` + +### `DB-CLUSTER-10017` + +**Message** + +```markdown +The operator is unspecified +``` + +### `DB-CLUSTER-10018` + +**Message** + +```markdown +The operator is unrecognized +``` + +### `DB-CLUSTER-10019` + +**Message** + +```markdown +The mutation is not set +``` + +### `DB-CLUSTER-10020` + +**Message** + +```markdown +The data type is unspecified +``` + +### `DB-CLUSTER-10021` + +**Message** + +```markdown +The data type is unrecognized +``` + +### `DB-CLUSTER-10022` + +**Message** + +```markdown +The user option is unspecified +``` + +### `DB-CLUSTER-10023` + +**Message** + +```markdown +The user option is unrecognized +``` + +### `DB-CLUSTER-10024` + +**Message** + +```markdown +The privilege is unspecified +``` + +### `DB-CLUSTER-10025` + +**Message** + +```markdown +The privilege is unrecognized +``` + +### `DB-CLUSTER-10026` + +**Message** + +```markdown +The username is not set +``` + +### `DB-CLUSTER-10027` + +**Message** + +```markdown +This feature is not supported in ScalarDB Cluster +``` + +### `DB-CLUSTER-10028` + +**Message** + +```markdown +The property 'scalar.db.contact_points' must not be empty +``` + +### `DB-CLUSTER-10029` + +**Message** + +```markdown +The property 'scalar.db.contact_points' must be prefixed with 'indirect:' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10030` + +**Message** + +```markdown +The format of the property 'scalar.db.contact_points' for direct-kubernetes client mode is 'direct-kubernetes:/' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10031` + +**Message** + +```markdown +The property 'scalar.db.sql.cluster_mode.contact_points' must not be empty +``` + +### `DB-CLUSTER-10032` + +**Message** + +```markdown +The property 'scalar.db.sql.cluster_mode.contact_points' must be prefixed with 'indirect:' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10033` + +**Message** + +```markdown +The format of the property 'scalar.db.sql.cluster_mode.contact_points' for direct-kubernetes client mode is 'direct-kubernetes:/' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10034` + +**Message** + +```markdown +ClusterNodeManagerFactory is not specified +``` + +### `DB-CLUSTER-10035` + +**Message** + +```markdown +The update condition type is unspecified +``` + +### `DB-CLUSTER-10036` + +**Message** + +```markdown +The update condition type is unrecognized +``` + +### `DB-CLUSTER-10037` + +**Message** + +```markdown +The two-phase commit interface is not supported +``` + +### `DB-CLUSTER-10038` + +**Message** + +```markdown +Membership is not specified +``` + +### `DB-CLUSTER-10039` + +**Message** + +```markdown +The policy state is unspecified +``` + +### `DB-CLUSTER-10040` + +**Message** + +```markdown +The policy state is unrecognized +``` + +### `DB-CLUSTER-10041` + +**Message** + +```markdown +The access mode is unspecified +``` + +### `DB-CLUSTER-10042` + +**Message** + +```markdown +The access mode is unrecognized +``` + +### `DB-CLUSTER-10043` + +**Message** + +```markdown +The service does not exist. Service Class: %s +``` + +### `DB-CLUSTER-10044` + +**Message** + +```markdown +The policy does not exist. Policy: %s +``` + +### `DB-CLUSTER-10045` + +**Message** + +```markdown +The property 'scalar.db.embedding.client.contact_points' must not be empty +``` + +### `DB-CLUSTER-10046` + +**Message** + +```markdown +The property 'scalar.db.embedding.client.contact_points' must be prefixed with 'indirect:' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10047` + +**Message** + +```markdown +The format of the property 'scalar.db.embedding.client.contact_points' for direct-kubernetes client mode is 'direct-kubernetes:/' or 'direct-kubernetes:' +``` + +### `DB-CLUSTER-10048` + +**Message** + +```markdown +The embeddings must be provided +``` + +### `DB-CLUSTER-10049` + +**Message** + +```markdown +Only one embedding can be added with an embedding ID +``` + +### `DB-CLUSTER-10050` + +**Message** + +```markdown +Text segments cannot be provided when adding an embedding with an embedding ID +``` + +### `DB-CLUSTER-10051` + +**Message** + +```markdown +Both embedding IDs and a filter cannot be provided +``` + +### `DB-CLUSTER-10052` + +**Message** + +```markdown +Unsupported embedding store type. Type: %s +``` + +### `DB-CLUSTER-10053` + +**Message** + +```markdown +Unsupported embedding model type. Type: %s +``` + +### `DB-CLUSTER-10054` + +**Message** + +```markdown +The filter is not set +``` + +### `DB-CLUSTER-10055` + +**Message** + +```markdown +Unsupported metadata value type. Type: %s +``` + +### `DB-CLUSTER-10056` + +**Message** + +```markdown +The metadata value is not set +``` + +## `DB-CLUSTER-2xxxx` status codes + +The following are status codes and messages for the concurrency error category. + +### `DB-CLUSTER-20000` + +**Message** + +```markdown +The hop limit is exceeded +``` + +### `DB-CLUSTER-20001` + +**Message** + +```markdown +A transaction associated with the specified transaction ID is not found. The transaction might have expired, or the cluster node that handled the transaction might have been restarted. Transaction ID: %s +``` + +## `DB-CLUSTER-3xxxx` status codes + +The following are status codes and messages for the internal error category. + +### `DB-CLUSTER-30000` + +**Message** + +```markdown +Getting local IP addresses failed +``` + +### `DB-CLUSTER-30001` + +**Message** + +```markdown +Getting a cluster node object from the cache failed. Cluster Node IP Address: %s +``` + +### `DB-CLUSTER-30002` + +**Message** + +```markdown +The ring is empty +``` + +### `DB-CLUSTER-30003` + +**Message** + +```markdown +Getting the Kubernetes API client failed +``` + +### `DB-CLUSTER-30004` + +**Message** + +```markdown +Reading the Kubernetes endpoint failed. Namespace: %s; Name: %s; Code: %d; Response Headers: %s; Response Body: %s +``` + +### `DB-CLUSTER-30005` + +**Message** + +```markdown +Configuring TLS failed +``` + +### `DB-CLUSTER-30006` + +**Message** + +```markdown +No nearest cluster nodes are found +``` diff --git a/versioned_docs/version-3.15/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx b/versioned_docs/version-3.15/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx new file mode 100644 index 00000000..a62e6578 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart.mdx @@ -0,0 +1,256 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to Deploy ScalarDB Cluster Locally + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This guide provides instructions on how to deploy ScalarDB Cluster by using a Helm Chart on a local Kubernetes cluster, specifically designed for a test environment. + +## Prerequisites + +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later +- Kubernetes cluster (either [minikube](https://minikube.sigs.k8s.io/docs/start/) or [kind](https://kind.sigs.k8s.io/docs/user/quick-start/#installation)) +- [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) +- [Helm](https://helm.sh/docs/intro/install/) + + + +## What you will create + +You will be deploying the following components on a local Kubernetes cluster as depicted below: + +``` ++---------------------------------------------------------------------------------------------------------------------------------------+ +| [Kubernetes Cluster] | +| | +| [Pod] [Pod] [Pod] | +| | +| +-------+ | +| +---> | Envoy | ---+ | +| | +-------+ | | +| | | | +| +---------+ | +-------+ | +--------------------+ | +| | Service | ---+---> | Envoy | ---+---------> | Service | ---+ | +| | (Envoy) | | +-------+ | | (ScalarDB Cluster) | | | +| +---------+ | | +--------------------+ | +-----------------------+ | +| | +-------+ | | +---> | ScalarDB Cluster Node | ---+ | +| +---> | Envoy | ---+ | | +-----------------------+ | | +| +-------+ | | | | +| | | +-----------------------+ | +------------+ | +| +---+---> | ScalarDB Cluster Node | ---+---> | PostgreSQL | | +| | | +-----------------------+ | +------------+ | +| | | | | +| | | +-----------------------+ | | +| | +---> | ScalarDB Cluster Node | ---+ | +| | +-----------------------+ | +| +----------------------------+ | | +| | Service | ---+ | +| | (ScalarDB Cluster GraphQL) | | +| +----------------------------+ | +| | ++---------------------------------------------------------------------------------------------------------------------------------------+ +``` + +## Step 1. Start a PostgreSQL container + +ScalarDB Cluster must use some kind of database system as its backend database. The database that is used in this guide is PostgreSQL. + +You can deploy PostgreSQL on the Kubernetes cluster as follows. + +1. Add the Bitnami Helm repository by running the following command: + + ```console + helm repo add bitnami https://charts.bitnami.com/bitnami + ``` + +2. Deploy PostgreSQL by running the following command: + + ```console + helm install postgresql-scalardb-cluster bitnami/postgresql \ + --set auth.postgresPassword=postgres \ + --set primary.persistence.enabled=false + ``` + +3. Check if the PostgreSQL container is running by running the following command: + + ```console + kubectl get pod + ``` + + You should see the following output: + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 17s + ``` + +## Step 2. Deploy ScalarDB Cluster on the Kubernetes cluster by using a Helm Chart + +1. Add the Scalar Helm Charts repository by running the following command: + + ```console + helm repo add scalar-labs https://scalar-labs.github.io/helm-charts + ``` + +2. Set your license key and certificate as environment variables. If you don't have a license key, please [contact us](https://www.scalar-labs.com/contact). For details about the value for ``, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + + ```console + SCALAR_DB_CLUSTER_LICENSE_KEY='' + SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM='' + ``` + +3. Create a custom values file for ScalarDB Cluster (`scalardb-cluster-custom-values.yaml`) by running the following command: + + ```console + cat << 'EOF' > scalardb-cluster-custom-values.yaml + envoy: + enabled: true + service: + type: "LoadBalancer" + + scalardbCluster: + + image: + repository: "ghcr.io/scalar-labs/scalardb-cluster-node-byol-premium" + + scalardbClusterNodeProperties: | + # ScalarDB Cluster configurations + scalar.db.cluster.membership.type=KUBERNETES + scalar.db.cluster.membership.kubernetes.endpoint.namespace_name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAMESPACE_NAME} + scalar.db.cluster.membership.kubernetes.endpoint.name=${env:SCALAR_DB_CLUSTER_MEMBERSHIP_KUBERNETES_ENDPOINT_NAME} + + # Storage configurations + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgresql-scalardb-cluster.default.svc.cluster.local:5432/postgres + scalar.db.username=${env:SCALAR_DB_CLUSTER_POSTGRES_USERNAME} + scalar.db.password=${env:SCALAR_DB_CLUSTER_POSTGRES_PASSWORD} + + # For ScalarDB Cluster GraphQL tutorial. + scalar.db.graphql.enabled=true + scalar.db.graphql.namespaces=emoney + + # For ScalarDB Cluster SQL tutorial. + scalar.db.sql.enabled=true + + ### License key configurations + scalar.db.cluster.node.licensing.license_key=${env:SCALAR_DB_CLUSTER_LICENSE_KEY} + scalar.db.cluster.node.licensing.license_check_cert_pem=${env:SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} + graphql: + enabled: true + service: + type: "LoadBalancer" + + secretName: "scalardb-credentials-secret" + EOF + ``` + +:::note + + For the purpose of this guide, the service type for ScalarDB Cluster GraphQL and Envoy is set to `LoadBalancer`. + +::: + +4. Create a secret resource named `scalardb-credentials-secret` that includes credentials and license keys. + + ```console + kubectl create secret generic scalardb-credentials-secret \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_USERNAME=postgres \ + --from-literal=SCALAR_DB_CLUSTER_POSTGRES_PASSWORD=postgres \ + --from-literal=SCALAR_DB_CLUSTER_LICENSE_KEY="${SCALAR_DB_CLUSTER_LICENSE_KEY}" \ + --from-file=SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM=<(echo ${SCALAR_DB_CLUSTER_LICENSE_CHECK_CERT_PEM} | sed 's/\\n/\ + /g') \ + -n default + ``` + +5. Set the chart version of ScalarDB Cluster. + + ```console + SCALAR_DB_CLUSTER_VERSION=3.15.4 + SCALAR_DB_CLUSTER_CHART_VERSION=$(helm search repo scalar-labs/scalardb-cluster -l | grep -F "${SCALAR_DB_CLUSTER_VERSION}" | awk '{print $2}' | sort --version-sort -r | head -n 1) + ``` + +6. Deploy ScalarDB Cluster. + + ```console + helm install scalardb-cluster scalar-labs/scalardb-cluster -f scalardb-cluster-custom-values.yaml --version ${SCALAR_DB_CLUSTER_CHART_VERSION} -n default + ``` + +7. Check if the ScalarDB Cluster pods are deployed: + + ```console + kubectl get pod + ``` + + You should see the following output: + + ```console + NAME READY STATUS RESTARTS AGE + postgresql-scalardb-cluster-0 1/1 Running 0 84s + scalardb-cluster-envoy-59899dc588-477tg 1/1 Running 0 35s + scalardb-cluster-envoy-59899dc588-dpvhx 1/1 Running 0 35s + scalardb-cluster-envoy-59899dc588-lv9hx 1/1 Running 0 35s + scalardb-cluster-node-866c756c79-5v2tk 1/1 Running 0 35s + scalardb-cluster-node-866c756c79-9zhq5 1/1 Running 0 35s + scalardb-cluster-node-866c756c79-t6v86 1/1 Running 0 35s + ``` + + If the ScalarDB Cluster Node Pods and the Envoy Pods are deployed properly, the `STATUS` for each pod will be `Running`. + +6. Check if the service resources of ScalarDB Cluster are deployed by running the following command: + + ```console + kubectl get svc + ``` + + You should see the following output: + + ```console + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + kubernetes ClusterIP 10.96.0.1 443/TCP 260d + postgresql-scalardb-cluster ClusterIP 10.110.97.40 5432/TCP 86s + postgresql-scalardb-cluster-hl ClusterIP None 5432/TCP 86s + scalardb-cluster-envoy LoadBalancer 10.105.121.51 localhost 60053:30641/TCP 49s + scalardb-cluster-envoy-metrics ClusterIP 10.111.131.189 9001/TCP 49s + scalardb-cluster-graphql LoadBalancer 10.105.74.214 localhost 8080:30514/TCP 49s + scalardb-cluster-headless ClusterIP None 60053/TCP 49s + scalardb-cluster-metrics ClusterIP 10.110.132.22 9080/TCP 49s + ``` + + If the service resources of ScalarDB Cluster and Envoy are deployed properly, the private IP addresses in the `CLUSTER-IP` column will be displayed. + + :::note + + `scalardb-cluster-headless` has no `CLUSTER-IP` address. + + ::: + + You can also see `EXTERNAL-IP` addresses assigned to the service resource of ScalarDB Cluster GraphQL (`scalardb-cluster-graphql`) and the service resource of Envoy (`scalardb-cluster-envoy`) with `TYPE` set to `LoadBalancer`. + + In addition, the access method to the `LoadBalancer` service from your environment depends on each Kubernetes distribution. For example: + + - If you're using minikube, you can use the [`minikube tunnel` command](https://minikube.sigs.k8s.io/docs/commands/tunnel/). + - If you're using kind, you can use [Cloud Provider KIND](https://kind.sigs.k8s.io/docs/user/loadbalancer/). + + For details on how to access the `LoadBalancer` service, see the official documentation for the Kubernetes distribution that you're using. + +## Delete all resources + +You can delete all resources created in this guide by running the following command: + +```console +helm uninstall scalardb-cluster postgresql-scalardb-cluster +``` + +## Learn more + +To get familiar with other use cases for ScalarDB Cluster, try the following tutorials: + +- [Getting Started with ScalarDB Cluster](getting-started-with-scalardb-cluster.mdx) +- [Getting Started with ScalarDB Cluster GraphQL](getting-started-with-scalardb-cluster-graphql.mdx) +- [Getting Started with ScalarDB Cluster SQL via JDBC](getting-started-with-scalardb-cluster-sql-jdbc.mdx) +- [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) diff --git a/versioned_docs/version-3.15/scalardb-cluster/standalone-mode.mdx b/versioned_docs/version-3.15/scalardb-cluster/standalone-mode.mdx new file mode 100644 index 00000000..fdfb7be4 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-cluster/standalone-mode.mdx @@ -0,0 +1,236 @@ +--- +tags: + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Cluster Standalone Mode + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +Instead of setting up a Kubernetes cluster and deploying ScalarDB Cluster on top of it by using a Helm Chart, you can run ScalarDB Cluster in standalone mode, which simplifies development and testing processes. A primary use case for this would be when you want to start ScalarDB Cluster in standalone mode via Docker on your local machine and use it for development and testing. + +To run ScalarDB Cluster in standalone mode, you need to set the `scalar.db.cluster.node.standalone_mode.enabled` property to `true`: + +```properties +scalar.db.cluster.node.standalone_mode.enabled=true +``` + +## Run ScalarDB Cluster in standalone mode on Docker Compose + +This section explains how to start ScalarDB Cluster in standalone mode on Docker Compose. + + + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the necessary files by running the following command: + +```console +cd scalardb-samples/scalardb-cluster-standalone-mode/ +``` + +### Set up your database for ScalarDB Cluster + +Select your database, and follow the instructions to configure it for ScalarDB Cluster. + +For a list of databases that ScalarDB supports, see [Databases](../requirements.mdx#databases). + + + +

Run MySQL locally

+ + You can run MySQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start MySQL, run the following command: + + ```console + docker compose up -d mysql + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for MySQL in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For MySQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:mysql://mysql-1:3306/ + scalar.db.username=root + scalar.db.password=mysql + ``` +
+ +

Run PostgreSQL locally

+ + You can run PostgreSQL in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start PostgreSQL, run the following command: + + ```console + docker compose up -d postgres + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for PostgreSQL in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For PostgreSQL + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:postgresql://postgres-1:5432/ + scalar.db.username=postgres + scalar.db.password=postgres + ``` +
+ +

Run Oracle Database locally

+ + You can run Oracle Database in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Oracle Database, run the following command: + + ```console + docker compose up -d oracle + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Oracle Database in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Oracle + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:oracle:thin:@//oracle-1:1521/FREEPDB1 + scalar.db.username=SYSTEM + scalar.db.password=Oracle + ``` +
+ +

Run SQL Server locally

+ + You can run SQL Server in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start SQL Server, run the following command: + + ```console + docker compose up -d sqlserver + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for SQL Server in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For SQL Server + scalar.db.storage=jdbc + scalar.db.contact_points=jdbc:sqlserver://sqlserver-1:1433;encrypt=true;trustServerCertificate=true + scalar.db.username=sa + scalar.db.password=SqlServer22 + ``` +
+ +

Run Amazon DynamoDB Local

+ + You can run Amazon DynamoDB Local in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Amazon DynamoDB Local, run the following command: + + ```console + docker compose up -d dynamodb + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Amazon DynamoDB Local in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For DynamoDB Local + scalar.db.storage=dynamo + scalar.db.contact_points=sample + scalar.db.username=sample + scalar.db.password=sample + scalar.db.dynamo.endpoint_override=http://dynamodb-1:8000 + ``` +
+ + To use Azure Cosmos DB for NoSQL, you must have an Azure account. If you don't have an Azure account, visit [Create an Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-portal#create-account). + +

Configure Cosmos DB for NoSQL

+ + Set the **default consistency level** to **Strong** according to the official document at [Configure the default consistency level](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-manage-consistency#configure-the-default-consistency-level). + +

Configure ScalarDB Cluster

+ + The following instructions assume that you have properly installed and configured the JDK in your local environment and properly configured your Cosmos DB for NoSQL account in Azure. + + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Be sure to change the values for `scalar.db.contact_points` and `scalar.db.password` as described. + + ```properties + # For Cosmos DB + scalar.db.storage=cosmos + scalar.db.contact_points= + scalar.db.password= + ``` + +:::note + +You can use the primary key or the secondary key in your Azure Cosmos DB account as the value for `scalar.db.password`. + +::: +
+ +

Run Cassandra locally

+ + You can run Apache Cassandra in Docker Compose by using the `docker-compose.yaml` file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory. + + To start Apache Cassandra, run the following command: + + ```console + docker compose up -d cassandra + ``` + +

Configure ScalarDB Cluster

+ + The **scalardb-cluster-node.properties** file in the `scalardb-samples/scalardb-cluster-standalone-mode` directory contains database configurations for ScalarDB Cluster. Please uncomment the properties for Cassandra in the **scalardb-cluster-node.properties** file so that the configuration looks as follows: + + ```properties + # For Cassandra + scalar.db.storage=cassandra + scalar.db.contact_points=cassandra-1 + scalar.db.username=cassandra + scalar.db.password=cassandra + ``` +
+
+ +### Set the license key + +Set the license key (trial license or commercial license) for the ScalarDB Clusters in the configuration file `scalardb-cluster-node.properties`. For details, see [How to Configure a Product License Key](../scalar-licensing/index.mdx). + +### Start ScalarDB Cluster in standalone mode + +To start ScalarDB Cluster in standalone mode, run the following command: + +:::note + +If you want to change other configurations for ScalarDB Cluster, update the `scalardb-cluster-node.properties` file before running the command below. + +::: + +```console +docker compose up -d scalardb-cluster-node +``` + +## Client configurations for the ScalarDB Cluster Java API + +You can use the `indirect` client mode to connect to ScalarDB Cluster in standalone mode. For details about client configurations for the ScalarDB Cluster Java API, see [Developer Guide for ScalarDB Cluster with the Java API](developer-guide-for-scalardb-cluster-with-java-api.mdx). diff --git a/versioned_docs/version-3.15/scalardb-core-status-codes.mdx b/versioned_docs/version-3.15/scalardb-core-status-codes.mdx new file mode 100644 index 00000000..1bac0c42 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-core-status-codes.mdx @@ -0,0 +1,2060 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Core Error Codes + +This page provides a list of error codes in ScalarDB Core. + +## Error code classes and descriptions + +| Class | Description | +|:----------------|:---------------------------------------------------------| +| `DB-CORE-1xxxx` | Errors for the user error category | +| `DB-CORE-2xxxx` | Errors for the concurrency error category | +| `DB-CORE-3xxxx` | Errors for the internal error category | +| `DB-CORE-4xxxx` | Errors for the unknown transaction status error category | + +## `DB-CORE-1xxxx` status codes + +The following are status codes and messages for the user error category. + +### `DB-CORE-10000` + +**Message** + +```markdown +Only a single-column index is supported. Operation: %s +``` + +### `DB-CORE-10001` + +**Message** + +```markdown +The column of the specified index key is not indexed. Operation: %s +``` + +### `DB-CORE-10002` + +**Message** + +```markdown +The index key is not properly specified. Operation: %s +``` + +### `DB-CORE-10003` + +**Message** + +```markdown +Clustering keys cannot be specified when using an index. Operation: %s +``` + +### `DB-CORE-10004` + +**Message** + +```markdown +Orderings cannot be specified when using an index. Operation: %s +``` + +### `DB-CORE-10005` + +**Message** + +```markdown +The limit cannot be negative. Operation: %s +``` + +### `DB-CORE-10006` + +**Message** + +```markdown +Cross-partition scan is not enabled. Operation: %s +``` + +### `DB-CORE-10007` + +**Message** + +```markdown +Cross-partition scan ordering is not enabled. Operation: %s +``` + +### `DB-CORE-10008` + +**Message** + +```markdown +Cross-partition scan filtering is not enabled. Operation: %s +``` + +### `DB-CORE-10009` + +**Message** + +```markdown +The specified projection is not found. Projection: %s, Operation: %s +``` + +### `DB-CORE-10010` + +**Message** + +```markdown +The clustering key boundary is not properly specified. Operation: %s +``` + +### `DB-CORE-10011` + +**Message** + +```markdown +The start clustering key is not properly specified. Operation: %s +``` + +### `DB-CORE-10012` + +**Message** + +```markdown +The end clustering key is not properly specified. Operation: %s +``` + +### `DB-CORE-10013` + +**Message** + +```markdown +Orderings are not properly specified. Operation: %s +``` + +### `DB-CORE-10014` + +**Message** + +```markdown +The specified ordering column is not found. Ordering: %s, Operation: %s +``` + +### `DB-CORE-10015` + +**Message** + +```markdown +The condition is not properly specified. Operation: %s +``` + +### `DB-CORE-10016` + +**Message** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-CORE-10017` + +**Message** + +```markdown +The column value is not properly specified. Column: %s, Operation: %s +``` + +### `DB-CORE-10018` + +**Message** + +```markdown +The mutations are empty +``` + +### `DB-CORE-10019` + +**Message** + +```markdown +Mutations that span multiple partitions are not supported. Mutations: %s +``` + +### `DB-CORE-10020` + +**Message** + +```markdown +The partition key is not properly specified. Operation: %s +``` + +### `DB-CORE-10021` + +**Message** + +```markdown +The clustering key is not properly specified. Operation: %s +``` + +### `DB-CORE-10022` + +**Message** + +```markdown +The authentication and authorization feature is not enabled. To use this feature, you must enable it. Note that this feature is supported only in the ScalarDB Enterprise edition +``` + +### `DB-CORE-10023` + +**Message** + +```markdown +This condition is not allowed for the PutIf operation. Condition: %s +``` + +### `DB-CORE-10024` + +**Message** + +```markdown +This condition is not allowed for the DeleteIf operation. Condition: %s +``` + +### `DB-CORE-10025` + +**Message** + +```markdown +Operator must be LIKE or NOT_LIKE. Operator: %s +``` + +### `DB-CORE-10026` + +**Message** + +```markdown +An escape character must be a string of a single character or an empty string +``` + +### `DB-CORE-10027` + +**Message** + +```markdown +The LIKE pattern must not be null +``` + +### `DB-CORE-10028` + +**Message** + +```markdown +The LIKE pattern must not include only an escape character +``` + +### `DB-CORE-10029` + +**Message** + +```markdown +The LIKE pattern must not end with an escape character +``` + +### `DB-CORE-10030` + +**Message** + +```markdown +The column %s does not exist +``` + +### `DB-CORE-10031` + +**Message** + +```markdown +This operation is not supported when getting records of a database without using an index +``` + +### `DB-CORE-10032` + +**Message** + +```markdown +This operation is not supported when getting records of a database by using an index +``` + +### `DB-CORE-10033` + +**Message** + +```markdown +This operation is not supported when scanning all the records of a database or scanning records of a database by using an index +``` + +### `DB-CORE-10034` + +**Message** + +```markdown +This operation is supported only when scanning records of a database by using an index +``` + +### `DB-CORE-10035` + +**Message** + +```markdown +This operation is not supported when scanning records of a database by using an index +``` + +### `DB-CORE-10037` + +**Message** + +```markdown +This operation is supported only when no conditions are specified. If you want to modify a condition, please use clearConditions() to remove all existing conditions first +``` + +### `DB-CORE-10038` + +**Message** + +```markdown +One or more columns must be specified. +``` + +### `DB-CORE-10039` + +**Message** + +```markdown +One or more partition keys must be specified. +``` + +### `DB-CORE-10040` + +**Message** + +```markdown +The column definition must be specified since %s is specified as a partition key +``` + +### `DB-CORE-10041` + +**Message** + +```markdown +The column definition must be specified since %s is specified as a clustering key +``` + +### `DB-CORE-10042` + +**Message** + +```markdown +Invalid ID specified. ID: %d +``` + +### `DB-CORE-10043` + +**Message** + +```markdown +The transaction is not active. Status: %s +``` + +### `DB-CORE-10044` + +**Message** + +```markdown +The transaction has already been committed or rolled back. Status: %s +``` + +### `DB-CORE-10045` + +**Message** + +```markdown +The transaction has not been prepared. Status: %s +``` + +### `DB-CORE-10046` + +**Message** + +```markdown +The transaction has not been prepared or validated. Status: %s +``` + +### `DB-CORE-10047` + +**Message** + +```markdown +The transaction already exists +``` + +### `DB-CORE-10048` + +**Message** + +```markdown +A transaction associated with the specified transaction ID is not found. The transaction might have expired +``` + +### `DB-CORE-10049` + +**Message** + +```markdown +%s is the system namespace name +``` + +### `DB-CORE-10050` + +**Message** + +```markdown +The namespace already exists. Namespace: %s +``` + +### `DB-CORE-10051` + +**Message** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-CORE-10052` + +**Message** + +```markdown +The table already exists. Table: %s +``` + +### `DB-CORE-10053` + +**Message** + +```markdown +The namespace is not empty. Namespace: %s; Tables in the namespace: %s +``` + +### `DB-CORE-10054` + +**Message** + +```markdown +The column does not exist. Table: %s; Column: %s +``` + +### `DB-CORE-10055` + +**Message** + +```markdown +The index already exists. Table: %s; Column: %s +``` + +### `DB-CORE-10056` + +**Message** + +```markdown +The index does not exist. Table: %s; Column: %s +``` + +### `DB-CORE-10057` + +**Message** + +```markdown +The column already exists. Table: %s; Column: %s +``` + +### `DB-CORE-10058` + +**Message** + +```markdown +The operation does not have the target namespace or table name. Operation: %s +``` + +### `DB-CORE-10059` + +**Message** + +```markdown +The specified value of the property '%s' is not a number. Value: %s +``` + +### `DB-CORE-10060` + +**Message** + +```markdown +The specified value of the property '%s' is not a boolean. Value: %s +``` + +### `DB-CORE-10061` + +**Message** + +```markdown +Reading the file failed. File: %s +``` + +### `DB-CORE-10062` + +**Message** + +```markdown +The property 'scalar.db.cross_partition_scan.enabled' must be set to true to use cross-partition scan with filtering or ordering +``` + +### `DB-CORE-10063` + +**Message** + +```markdown +This column value is out of range for BigInt. Value: %s +``` + +### `DB-CORE-10064` + +**Message** + +```markdown +This type is not supported. Name: %s, Type: %s +``` + +### `DB-CORE-10065` + +**Message** + +```markdown +Storage '%s' is not found +``` + +### `DB-CORE-10066` + +**Message** + +```markdown +Transaction manager '%s' is not found +``` + +### `DB-CORE-10068` + +**Message** + +```markdown +Please use scan() for non-exact match selection. Operation: %s +``` + +### `DB-CORE-10069` + +**Message** + +```markdown +Import-related functionality is not supported in Cassandra +``` + +### `DB-CORE-10070` + +**Message** + +```markdown +The %s network strategy does not exist +``` + +### `DB-CORE-10071` + +**Message** + +```markdown +The property 'scalar.db.contact_port' must be greater than or equal to zero +``` + +### `DB-CORE-10073` + +**Message** + +```markdown +The BLOB type is not supported for clustering keys in Cosmos DB. Column: %s +``` + +### `DB-CORE-10074` + +**Message** + +```markdown +Import-related functionality is not supported in Cosmos DB +``` + +### `DB-CORE-10075` + +**Message** + +```markdown +The property 'scalar.db.contact_points' must not be empty +``` + +### `DB-CORE-10076` + +**Message** + +```markdown +Cosmos DB supports only EQ, NE, IS_NULL, and IS_NOT_NULL operations for the BLOB type in conditions. Mutation: %s +``` + +### `DB-CORE-10077` + +**Message** + +```markdown +The specified consistency level is not supported. Consistency level: %s +``` + +### `DB-CORE-10078` + +**Message** + +```markdown +0x00 bytes are not accepted in BLOB values in DESC order +``` + +### `DB-CORE-10079` + +**Message** + +```markdown +Cannot encode a Text value that contains '\u0000' +``` + +### `DB-CORE-10081` + +**Message** + +```markdown +An index column cannot be set to null or an empty value for Text or Blob in DynamoDB. Operation: %s +``` + +### `DB-CORE-10082` + +**Message** + +```markdown +DynamoDB supports only EQ, NE, IS_NULL, and IS_NOT_NULL operations for the BOOLEAN type in conditions. Mutation: %s +``` + +### `DB-CORE-10083` + +**Message** + +```markdown +Nested multi-storage definitions are not supported. Storage: %s +``` + +### `DB-CORE-10084` + +**Message** + +```markdown +Storage not found. Storage: %s +``` + +### `DB-CORE-10085` + +**Message** + +```markdown +The namespace name is not acceptable. Namespace: %s +``` + +### `DB-CORE-10086` + +**Message** + +```markdown +The table name is not acceptable. Table: %s +``` + +### `DB-CORE-10087` + +**Message** + +```markdown +Importing tables is not allowed in the RDB engine. RDB engine: %s +``` + +### `DB-CORE-10088` + +**Message** + +```markdown +The %s table must have a primary key +``` + +### `DB-CORE-10089` + +**Message** + +```markdown +The RDB engine is not supported. JDBC connection URL: %s +``` + +### `DB-CORE-10090` + +**Message** + +```markdown +Data type %s(%d) is not supported: %s +``` + +### `DB-CORE-10091` + +**Message** + +```markdown +Data type %s is not supported: %s +``` + +### `DB-CORE-10092` + +**Message** + +```markdown +Getting a transaction state is not supported in JDBC transactions +``` + +### `DB-CORE-10093` + +**Message** + +```markdown +Rolling back a transaction is not supported in JDBC transactions +``` + +### `DB-CORE-10094` + +**Message** + +```markdown +Coordinator tables already exist +``` + +### `DB-CORE-10095` + +**Message** + +```markdown +Coordinator tables do not exist +``` + +### `DB-CORE-10096` + +**Message** + +```markdown +The namespace %s is reserved. Any operations on this namespace are not allowed +``` + +### `DB-CORE-10097` + +**Message** + +```markdown +Mutating transaction metadata columns is not allowed. Table: %s; Column: %s +``` + +### `DB-CORE-10098` + +**Message** + +```markdown +A %s condition is not allowed on Put operations +``` + +### `DB-CORE-10099` + +**Message** + +```markdown +A %s condition is not allowed on Delete operations +``` + +### `DB-CORE-10100` + +**Message** + +```markdown +The condition is not allowed to target transaction metadata columns. Column: %s +``` + +### `DB-CORE-10101` + +**Message** + +```markdown +The column '%s' is reserved as transaction metadata +``` + +### `DB-CORE-10102` + +**Message** + +```markdown +Non-primary key columns with the 'before_' prefix, '%s', are reserved as transaction metadata +``` + +### `DB-CORE-10103` + +**Message** + +```markdown +Put cannot have a condition when the target record is unread and implicit pre-read is disabled. Please read the target record beforehand or enable implicit pre-read: %s +``` + +### `DB-CORE-10104` + +**Message** + +```markdown +Writing already-deleted data is not allowed +``` + +### `DB-CORE-10105` + +**Message** + +```markdown +Getting data neither in the read set nor the delete set is not allowed +``` + +### `DB-CORE-10106` + +**Message** + +```markdown +Reading already-written data is not allowed +``` + +### `DB-CORE-10107` + +**Message** + +```markdown +The transaction is not validated. When using the EXTRA_READ serializable strategy, you need to call validate() before calling commit() +``` + +### `DB-CORE-10108` + +**Message** + +```markdown +DynamoDB cannot batch more than 100 mutations at once +``` + +### `DB-CORE-10109` + +**Message** + +```markdown +The partition keys of the table %s.%s were modified, but altering partition keys is not supported +``` + +### `DB-CORE-10110` + +**Message** + +```markdown +The clustering keys of the table %s.%s were modified, but altering clustering keys is not supported +``` + +### `DB-CORE-10111` + +**Message** + +```markdown +The clustering ordering of the table %s.%s were modified, but altering clustering ordering is not supported +``` + +### `DB-CORE-10112` + +**Message** + +```markdown +The column %s of the table %s.%s has been deleted. Column deletion is not supported when altering a table +``` + +### `DB-CORE-10113` + +**Message** + +```markdown +The data type of the column %s of the table %s.%s was modified, but altering data types is not supported +``` + +### `DB-CORE-10114` + +**Message** + +```markdown +Specifying the '--schema-file' option is required when using the '--repair-all' option +``` + +### `DB-CORE-10115` + +**Message** + +```markdown +Specifying the '--schema-file' option is required when using the '--alter' option +``` + +### `DB-CORE-10116` + +**Message** + +```markdown +Specifying the '--schema-file' option is required when using the '--import' option +``` + +### `DB-CORE-10117` + +**Message** + +```markdown +Specifying the '--coordinator' option with the '--import' option is not allowed. Create Coordinator tables separately +``` + +### `DB-CORE-10118` + +**Message** + +```markdown +Reading the configuration file failed. File: %s +``` + +### `DB-CORE-10119` + +**Message** + +```markdown +Reading the schema file failed. File: %s +``` + +### `DB-CORE-10120` + +**Message** + +```markdown +Parsing the schema JSON failed. Details: %s +``` + +### `DB-CORE-10121` + +**Message** + +```markdown +The table name must contain the namespace and the table. Table: %s +``` + +### `DB-CORE-10122` + +**Message** + +```markdown +The partition key must be specified. Table: %s +``` + +### `DB-CORE-10123` + +**Message** + +```markdown +Invalid clustering-key format. The clustering key must be in the format of 'column_name' or 'column_name ASC/DESC'. Table: %s; Clustering key: %s +``` + +### `DB-CORE-10124` + +**Message** + +```markdown +Columns must be specified. Table: %s +``` + +### `DB-CORE-10125` + +**Message** + +```markdown +Invalid column type. Table: %s; Column: %s; Type: %s +``` + +### `DB-CORE-10126` + +**Message** + +```markdown +The mutation type is not supported. Only the Put or Delete type is supported. Mutation: %s +``` + +### `DB-CORE-10127` + +**Message** + +```markdown +This condition is not allowed for the UpdateIf operation. Condition: %s +``` + +### `DB-CORE-10128` + +**Message** + +```markdown +Cross-partition scan with ordering is not supported in Cassandra +``` + +### `DB-CORE-10129` + +**Message** + +```markdown +Cross-partition scan with ordering is not supported in Cosmos DB +``` + +### `DB-CORE-10130` + +**Message** + +```markdown +Cross-partition scan with ordering is not supported in DynamoDB +``` + +### `DB-CORE-10131` + +**Message** + +```markdown +The directory '%s' does not have write permissions. Please ensure that the current user has write access to the directory. +``` + +### `DB-CORE-10132` + +**Message** + +```markdown +Failed to create the directory '%s'. Please check if you have sufficient permissions and if there are any file system restrictions. Details: %s +``` + +### `DB-CORE-10133` + +**Message** + +```markdown +Directory path cannot be null or empty. +``` + +### `DB-CORE-10134` + +**Message** + +```markdown +No file extension was found on the provided file name %s. +``` + +### `DB-CORE-10135` + +**Message** + +```markdown +Invalid file extension: %s. Allowed extensions are: %s +``` + +### `DB-CORE-10136` + +**Message** + +```markdown +Getting a transaction state is not supported in single CRUD operation transactions +``` + +### `DB-CORE-10137` + +**Message** + +```markdown +Rolling back a transaction is not supported in single CRUD operation transactions +``` + +### `DB-CORE-10138` + +**Message** + +```markdown +Multiple mutations are not supported in single CRUD operation transactions +``` + +### `DB-CORE-10139` + +**Message** + +```markdown +Beginning a transaction is not allowed in single CRUD operation transactions +``` + +### `DB-CORE-10140` + +**Message** + +```markdown +Resuming a transaction is not allowed in single CRUD operation transactions +``` + +### `DB-CORE-10141` + +**Message** + +```markdown +Using the group commit feature on the Coordinator table with a two-phase commit interface is not allowed +``` + +### `DB-CORE-10142` + +**Message** + +```markdown +This operation is supported only when no conditions are specified. If you want to modify a condition, please use clearConditions() to remove all existing conditions first +``` + +### `DB-CORE-10143` + +**Message** + +```markdown +The encryption feature is not enabled. To encrypt data at rest, you must enable this feature. Note that this feature is supported only in the ScalarDB Enterprise edition +``` + +### `DB-CORE-10144` + +**Message** + +```markdown +The variable key column size must be greater than or equal to 64 +``` + +### `DB-CORE-10145` + +**Message** + +```markdown +The value of the column %s in the primary key contains an illegal character. Primary-key columns must not contain any of the following characters in Cosmos DB: ':', '/', '\', '#', '?'. Value: %s +``` + +### `DB-CORE-10146` + +**Message** + +```markdown +Inserting already-written data is not allowed +``` + +### `DB-CORE-10147` + +**Message** + +```markdown +Deleting already-inserted data is not allowed +``` + +### `DB-CORE-10148` + +**Message** + +```markdown +Invalid key: Column %s does not exist in the table %s in namespace %s. +``` + +### `DB-CORE-10149` + +**Message** + +```markdown +Invalid base64 encoding for blob value for column %s in table %s in namespace %s +``` + +### `DB-CORE-10150` + +**Message** + +```markdown +Invalid number specified for column %s in table %s in namespace %s +``` + +### `DB-CORE-10151` + +**Message** + +```markdown +Method null argument not allowed +``` + +### `DB-CORE-10152` + +**Message** + +```markdown +The attribute-based access control feature is not enabled. To use this feature, you must enable it. Note that this feature is supported only in the ScalarDB Enterprise edition +``` + +### `DB-CORE-10153` + +**Message** + +```markdown +The provided clustering key %s was not found +``` + +### `DB-CORE-10154` + +**Message** + +```markdown +The column '%s' was not found +``` + +### `DB-CORE-10155` + +**Message** + +```markdown +The provided partition key is incomplete. Required key: %s +``` + +### `DB-CORE-10156` + +**Message** + +```markdown +The provided clustering key order does not match the table schema. Required order: %s +``` + +### `DB-CORE-10157` + +**Message** + +```markdown +The provided partition key order does not match the table schema. Required order: %s +``` + +### `DB-CORE-10158` + +**Message** + +```markdown +This DATE column value is out of the valid range. It must be between 1000-01-01 and 9999-12-12. Value: %s +``` + +### `DB-CORE-10159` + +**Message** + +```markdown +This TIME column value precision cannot be shorter than one microsecond. Value: %s +``` + +### `DB-CORE-10160` + +**Message** + +```markdown +This TIMESTAMP column value is out of the valid range. It must be between 1000-01-01T00:00:00.000 and 9999-12-31T23:59:59.999. Value: %s +``` + +### `DB-CORE-10161` + +**Message** + +```markdown +This TIMESTAMP column value precision cannot be shorter than one millisecond. Value: %s +``` + +### `DB-CORE-10162` + +**Message** + +```markdown +This TIMESTAMPTZ column value is out of the valid range. It must be between 1000-01-01T00:00:00.000Z to 9999-12-31T23:59:59.999Z. Value: %s +``` + +### `DB-CORE-10163` + +**Message** + +```markdown +This TIMESTAMPTZ column value precision cannot be shorter than one millisecond. Value: %s +``` + +### `DB-CORE-10164` + +**Message** + +```markdown +The underlying-storage data type %s is not supported as the ScalarDB %s data type: %s +``` + +### `DB-CORE-10165` + +**Message** + +```markdown +Missing namespace or table: %s, %s +``` + +### `DB-CORE-10166` + +**Message** + +```markdown +Failed to retrieve table metadata. Details: %s +``` + +### `DB-CORE-10167` + +**Message** + +```markdown +Duplicate data mappings found for table '%s' in the control file +``` + +### `DB-CORE-10168` + +**Message** + +```markdown +No mapping found for column '%s' in table '%s' in the control file. Control file validation set at 'FULL'. All columns need to be mapped. +``` + +### `DB-CORE-10169` + +**Message** + +```markdown +The control file is missing data mappings +``` + +### `DB-CORE-10170` + +**Message** + +```markdown +The target column '%s' for source field '%s' could not be found in table '%s' +``` + +### `DB-CORE-10171` + +**Message** + +```markdown +The required partition key '%s' is missing in the control file mapping for table '%s' +``` + +### `DB-CORE-10172` + +**Message** + +```markdown +The required clustering key '%s' is missing in the control file mapping for table '%s' +``` + +### `DB-CORE-10173` + +**Message** + +```markdown +Duplicated data mappings found for column '%s' in table '%s' +``` + +### `DB-CORE-10174` + +**Message** + +```markdown +Missing required field or column mapping for clustering key %s +``` + +### `DB-CORE-10175` + +**Message** + +```markdown +Missing required field or column mapping for partition key %s +``` + +### `DB-CORE-10176` + +**Message** + +```markdown +Missing field or column mapping for %s +``` + +## `DB-CORE-2xxxx` status codes + +The following are status codes and messages for the concurrency error category. + +### `DB-CORE-20000` + +**Message** + +```markdown +No mutation was applied +``` + +### `DB-CORE-20001` + +**Message** + +```markdown +Logging failed in the batch +``` + +### `DB-CORE-20002` + +**Message** + +```markdown +The operation failed in the batch with type %s +``` + +### `DB-CORE-20003` + +**Message** + +```markdown +An error occurred in the batch. Details: %s +``` + +### `DB-CORE-20004` + +**Message** + +```markdown +A Paxos phase in the CAS operation failed +``` + +### `DB-CORE-20005` + +**Message** + +```markdown +The learn phase in the CAS operation failed +``` + +### `DB-CORE-20006` + +**Message** + +```markdown +A simple write operation failed +``` + +### `DB-CORE-20007` + +**Message** + +```markdown +An error occurred in the mutation. Details: %s +``` + +### `DB-CORE-20008` + +**Message** + +```markdown +A RetryWith error occurred in the mutation. Details: %s +``` + +### `DB-CORE-20009` + +**Message** + +```markdown +A transaction conflict occurred in the mutation. Details: %s +``` + +### `DB-CORE-20010` + +**Message** + +```markdown +A transaction conflict occurred in the mutation. Details: %s +``` + +### `DB-CORE-20011` + +**Message** + +```markdown +A conflict occurred. Please try restarting the transaction. Details: %s +``` + +### `DB-CORE-20012` + +**Message** + +```markdown +The %s condition of the %s operation is not satisfied. Targeting column(s): %s +``` + +### `DB-CORE-20013` + +**Message** + +```markdown +The record being prepared already exists +``` + +### `DB-CORE-20014` + +**Message** + +```markdown +A conflict occurred when preparing records +``` + +### `DB-CORE-20015` + +**Message** + +```markdown +The committing state in the coordinator failed. The transaction has been aborted +``` + +### `DB-CORE-20016` + +**Message** + +```markdown +A conflict occurred during implicit pre-read +``` + +### `DB-CORE-20017` + +**Message** + +```markdown +This record needs to be recovered +``` + +### `DB-CORE-20018` + +**Message** + +```markdown +The record does not exist, so the %s condition is not satisfied +``` + +### `DB-CORE-20019` + +**Message** + +```markdown +The record exists, so the %s condition is not satisfied +``` + +### `DB-CORE-20020` + +**Message** + +```markdown +The condition on the column '%s' is not satisfied +``` + +### `DB-CORE-20021` + +**Message** + +```markdown +Reading empty records might cause a write skew anomaly, so the transaction has been aborted for safety purposes +``` + +### `DB-CORE-20022` + +**Message** + +```markdown +An anti-dependency was found. The transaction has been aborted +``` + +### `DB-CORE-20023` + +**Message** + +```markdown +A transaction conflict occurred in the Insert operation +``` + +### `DB-CORE-20024` + +**Message** + +```markdown +The %s condition of the %s operation is not satisfied. Targeting column(s): %s +``` + +### `DB-CORE-20025` + +**Message** + +```markdown +A transaction conflict occurred in the Insert operation +``` + +## `DB-CORE-3xxxx` status codes + +The following are status codes and messages for the internal error category. + +### `DB-CORE-30000` + +**Message** + +```markdown +Creating the namespace failed. Namespace: %s +``` + +### `DB-CORE-30001` + +**Message** + +```markdown +Dropping the namespace failed. Namespace: %s +``` + +### `DB-CORE-30002` + +**Message** + +```markdown +Creating the table failed. Table: %s +``` + +### `DB-CORE-30003` + +**Message** + +```markdown +Dropping the table failed. Table: %s +``` + +### `DB-CORE-30004` + +**Message** + +```markdown +Truncating the table failed. Table: %s +``` + +### `DB-CORE-30005` + +**Message** + +```markdown +Creating the index failed. Table: %s, Column: %s +``` + +### `DB-CORE-30006` + +**Message** + +```markdown +Dropping the index failed. Table: %s, Column: %s +``` + +### `DB-CORE-30007` + +**Message** + +```markdown +Getting the table metadata failed. Table: %s +``` + +### `DB-CORE-30008` + +**Message** + +```markdown +Getting the table names in the namespace failed. Namespace: %s +``` + +### `DB-CORE-30009` + +**Message** + +```markdown +Checking the namespace existence failed. Namespace: %s +``` + +### `DB-CORE-30010` + +**Message** + +```markdown +Checking the table existence failed. Table: %s +``` + +### `DB-CORE-30011` + +**Message** + +```markdown +Checking the index existence failed. Table: %s; Column: %s +``` + +### `DB-CORE-30012` + +**Message** + +```markdown +Repairing the namespace failed. Namespace: %s +``` + +### `DB-CORE-30013` + +**Message** + +```markdown +Repairing the table failed. Table: %s +``` + +### `DB-CORE-30014` + +**Message** + +```markdown +Adding a new column to the table failed. Table: %s; Column: %s; ColumnType: %s +``` + +### `DB-CORE-30015` + +**Message** + +```markdown +Getting the namespace names failed +``` + +### `DB-CORE-30016` + +**Message** + +```markdown +Getting the table metadata of the table being imported failed. Table: %s +``` + +### `DB-CORE-30017` + +**Message** + +```markdown +Importing the table failed. Table: %s +``` + +### `DB-CORE-30018` + +**Message** + +```markdown +Adding the raw column to the table failed. Table: %s; Column: %s; ColumnType: %s +``` + +### `DB-CORE-30019` + +**Message** + +```markdown +Upgrading the ScalarDB environment failed +``` + +### `DB-CORE-30020` + +**Message** + +```markdown +Something wrong because WriteType is neither CAS nor SIMPLE +``` + +### `DB-CORE-30021` + +**Message** + +```markdown +An error occurred in the selection. Details: %s +``` + +### `DB-CORE-30022` + +**Message** + +```markdown +An error occurred in the mutation. Details: %s +``` + +### `DB-CORE-30023` + +**Message** + +```markdown +An error occurred in the selection. Details: %s +``` + +### `DB-CORE-30024` + +**Message** + +```markdown +An error occurred in the mutation. Details: %s +``` + +### `DB-CORE-30025` + +**Message** + +```markdown +An error occurred in the selection. Details: %s +``` + +### `DB-CORE-30026` + +**Message** + +```markdown +An error occurred in the mutation. Details: %s +``` + +### `DB-CORE-30027` + +**Message** + +```markdown +An error occurred in the selection. Details: %s +``` + +### `DB-CORE-30028` + +**Message** + +```markdown +Fetching the next result failed +``` + +### `DB-CORE-30029` + +**Message** + +```markdown +Rolling back the transaction failed. Details: %s +``` + +### `DB-CORE-30030` + +**Message** + +```markdown +Committing the transaction failed. Details: %s +``` + +### `DB-CORE-30031` + +**Message** + +```markdown +The Get operation failed. Details: %s +``` + +### `DB-CORE-30032` + +**Message** + +```markdown +The Scan operation failed. Details: %s +``` + +### `DB-CORE-30033` + +**Message** + +```markdown +The Put operation failed. Details: %s +``` + +### `DB-CORE-30034` + +**Message** + +```markdown +The Delete operation failed. Details: %s +``` + +### `DB-CORE-30035` + +**Message** + +```markdown +Beginning a transaction failed. Details: %s +``` + +### `DB-CORE-30036` + +**Message** + +```markdown +Preparing records failed +``` + +### `DB-CORE-30037` + +**Message** + +```markdown +Validation failed +``` + +### `DB-CORE-30038` + +**Message** + +```markdown +Executing implicit pre-read failed +``` + +### `DB-CORE-30039` + +**Message** + +```markdown +Reading a record from the underlying storage failed +``` + +### `DB-CORE-30040` + +**Message** + +```markdown +Scanning records from the underlying storage failed +``` + +### `DB-CORE-30041` + +**Message** + +```markdown +Rollback failed because the transaction has already been committed +``` + +### `DB-CORE-30042` + +**Message** + +```markdown +Rollback failed +``` + +### `DB-CORE-30043` + +**Message** + +```markdown +The Insert operation failed. Details: %s +``` + +### `DB-CORE-30044` + +**Message** + +```markdown +The Upsert operation failed. Details: %s +``` + +### `DB-CORE-30045` + +**Message** + +```markdown +The Update operation failed. Details: %s +``` + +### `DB-CORE-30046` + +**Message** + +```markdown +Handling the before-preparation snapshot hook failed. Details: %s +``` + +### `DB-CORE-30047` + +**Message** + +```markdown +Something went wrong while trying to save the data. Details: %s +``` + +### `DB-CORE-30048` + +**Message** + +```markdown +Something went wrong while scanning. Are you sure you are running in the correct transaction mode? Details: %s +``` + +## `DB-CORE-4xxxx` status codes + +The following are status codes and messages for the unknown transaction status error category. + +### `DB-CORE-40000` + +**Message** + +```markdown +Rolling back the transaction failed. Details: %s +``` + +### `DB-CORE-40001` + +**Message** + +```markdown +Committing state failed with NoMutationException, but the coordinator status does not exist +``` + +### `DB-CORE-40002` + +**Message** + +```markdown +The state cannot be retrieved +``` + +### `DB-CORE-40003` + +**Message** + +```markdown +The coordinator status is unknown +``` + +### `DB-CORE-40004` + +**Message** + +```markdown +Aborting state failed with NoMutationException, but the coordinator status does not exist +``` diff --git a/versioned_docs/version-3.15/scalardb-data-loader/getting-started-export.mdx b/versioned_docs/version-3.15/scalardb-data-loader/getting-started-export.mdx new file mode 100644 index 00000000..9cea0e4f --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-data-loader/getting-started-export.mdx @@ -0,0 +1,62 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting started with Export + +This document explains how you can get started with the ScalarDB Data Loader Export function. + +## Features + +The ScalarDB Data Loader allows you to export data in the following formats: + +- JSON +- JSONLines +- CSV + +Each export will run a ScalarDB scan operation based on the provided CLI arguments when running data loader. + +## Usage + +The data loader export function can be started with the following minimal configuration: + +```console +./scalardb-data-loader export --config scalardb.properties --namespace namespace --table tableName +``` + + + +- --config: the path to the scalardb connection properties file +- --namespace: the namespace of the table that contains the data +- --table: name of the table that contains the data + +By default, the data loader will create the output file in the working directory if the `--output-file` argument is omitted as well. + +### Command-line flags + +Here is a list of flags (options) that can be used with the scalardb data loader. + +| Flag | Description | Usage | +| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------ | +| --config | The path to the scalardb.properties file. If omitted the tool looks for a file named `scalardb.properties` in the current folder | `scalardb-data-loader --config scalardb.properties` | +| --namespace | Namespace to export table data from. Required. | `scalardb-data-loader --namespace namespace` | +| --table | Name of table to export data from. Required. | `scalardb-data-loader --table tableName` | +| --key | Export data of specific Partition key. By default, it exports all data from the specified table. | `scalardb-data-loader --key columnName=value` | +| --sort | Specify a column to sort on. The column needs to be a clustering key. The argument can be repeated to provide multiple sortings. This flag is only applicable to `--key`. | `scalardb-data-loader --sort columnName=desc` | +| --projection | Limit the columns that are exported by providing a projection. The argument can be repeated to provide multiple projections. | `scalardb-data-loader --projection columnName` | +| --start | Clustering key to mark scan start. This flag is only applicable to `--key`. | `scalardb-data-loader --start columnName=value` | +| --start-exclusive | Is the scan start exclusive or not. If omitted, the default value is `false`. This flag is only applicable to `--key` | `scalardb-data-loader --start-exclusive` | +| --end | Clustering key to mark scan end. This flag is only applicable to `--key`. | `scalardb-data-loader --end columnName=value` | +| --end-exclusive | Is the scan start exclusive or not. If omitted, the default value is `false`. This flag is only applicable to `--key` | `scalardb-data-loader --end-exclusive` | +| --limit | Limit the results of the scan. If omitted, the default value is `0` which means their is no limit. | `scalardb-data-loader --limit 1000` | +| --output-file | The name and path of the output file. If omitted, the tool will save the file in the current folder with the following name format:
`export_namespace.tableName_timestamp.json` or `export_namespace.tableName_timestamp.csv`

The ouput folder needs to exists. The dataloader does not create the output folder for you. | `scalardb-data-loader --output-file ./out/output.json` | +| --format | The output format. By default `json` is selected. | `scalardb-data-loader --format json` | +| --metadata | When set to true the transaction metadata is included in the export. By default this is set to `false` | `scalardb-data-loader --metadata` | +| --delimiter | The delimiter used in CSV files. Default value is `;` | `scalardb-data-loader --delimiter ;` | +| --no-headers | Exclude header row in CSV file. Default is `false` | `scalardb-data-loader --no-headers` | +| --threads | Thread count for concurrent processing | `scalardb-data-loader --threads 500` | + diff --git a/versioned_docs/version-3.15/scalardb-data-loader/getting-started-import.mdx b/versioned_docs/version-3.15/scalardb-data-loader/getting-started-import.mdx new file mode 100644 index 00000000..d93e5ec2 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-data-loader/getting-started-import.mdx @@ -0,0 +1,293 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Getting started with Import + +This document explains how you can get started with the ScalarDB Data Loader Import function. + +## Features + +- Import data from JSON or JSONLines files +- Automatic data mapping based on source field name mapping +- Custom Data mapping via a JSON control file +- Import data from one record or line into multiple tables +- Support for INSERT, UPDATE and UPSERT + +## Usage + +The data loader import function can be started with the following minimal configuration: + +```console +./scalardb-data-loader import --config scalardb.properties --namespace namespace --table tableName +``` + +The above configuration starts an import process where no control file is used and the data mapping is applied automatically. + + + +Execute the following steps to successfully import new or existing data + +- Prepare a source file containing data that needs to be imported. + +- Choose the right import mode. By default, the import is done in `upsert` mode which means that data + will be inserted if new or updated if the partition key and/or clustering key is found. Other + options are `insert` mode or `update` mode. + +- Find the correct `namespace` and `table` name to import data to. + +- Determine if you want to run an `all required columns` check for each data row. If enabled data + rows with missing columns will be treated as failed and not imported. + +- Specify the pathnames for the `success` and `failed` output files. By default the data loader + creates the files in the working directory. + +- When dealing with JSON data, determine if you want the JSON output for the success or failed log files to + be in `pretty print` or not. By default, this option is disabled for performance + +- Optionally specify the `threads` argument to tweak performance + +- Run the import from the command line to start importing your data. Make sure to run the ScalarDB Data + Loader in the correct `storage` or `transaction` mode depending on your running ScalarDB instance. + +### Command-line flags + +Here is a list of flags (options) that can be used with the data loader: + +| Flag | Description | Usage | +|---------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------| +| --mode | The mode in which ScalarDB is running. If omitted, the default value is `storage` | `scalardb-data-loader --mode transaction` | +| --config | the path to the scalardb.properties file. If omitted the tool looks for a file named `scalardb.properties` in the current folder | `scalardb-data-loader --config scalardb.properties` | +| --namespace | Namespace to export table data from. Required when no control file is provided. | `scalardb-data-loader --namespace namespace` | +| --table | name of the table to export data from. Required when no control file is provided. | `scalardb-data-loader --table tableName` | +| --import-mode | Mode to import the data into the ScalarDB table. Supported modes are `insert`, `update` and `upsert`. Optional. Default the value is set to `upsert` | `scalardb-data-loader --import-mode=upsert` | +| --all-columns-required | If set, data rows cannot be imported if they are missing columns. Optional. By default, the check is not executed. | `scalardb-data-loader --all-columns-required` | +| --file | Specify the path to the file that will be imported. Required | `scalardb-data-loader --file ` | +| --success | The path to the file that is created to write the succeed import results to. Both succeed and failed import results will be written to a different file.
Optional. By default, the a new file will be created in the current working directory.

Note: if the file already exists, it will be overridden. | `scalardb-data-loader --success ` | +| --failed | The path to the file that will be created to write the failed import results to.
Optional. By default, the a new file will be created in the current working directory.

Note: if the file already exists, it will be overridden. | `scalardb-data-loader --failed ` | +| --threads | Thread count for concurrent processing | `scalardb-data-loader --threads 500` | +| --format | The format of the import file. `json` and `jsonl` files are supported. Optional, default the value `json` is selected. | `scalardb-data-loader --format json` | +| --ignore-null | The null values in the source file will be ignored, which means that the existing data will not be overwritten. Optional, default the value is `false`. | `scalardb-data-loader --ignore-null` | +| --pretty | When set, the output to the success and failed files is done in `pretty print` mode. By default the option is not enabled. | `scalardb-data-loader --pretty` | +| --control-file | The path to the JSON control file specifying the rules for the custom data mapping and/or multi-table import. | `scalardb-data-loader --control-file control.json` | +| --control-file-validation-level | The validation level for the control file. `MAPPED`, `KEYS` or` FULL`.

Optional and by default the level is set to `MAPPED` | `scalardb-data-loader --control-file-validation-level FULL` | +| --log-put-value | Wether the value that was used in the ScalarDB `PUT` operation is included in the log files or not.
Optional and disabled by default. | `scalardb-data-loader --log-put-value` | +| --error-file-required | To export an optional error file of type JSON when the import file contains CSV data. By default, this option is disabled. | `scalardb-data-loader --error-file-required` | +| --error | To specify an optional error file when the import file contains CSV data. | `scalardb-data-loader --error ` | +| --delimiter | To specify a custom delimiter if the import file contains CSV data. | `scalardb-data-loader --delimiter ` | +| --header | To specify the header row data if the import file contains CSV data and does not have a header row. | `scalardb-data-loader --header ` | + +## Import mode + +The data loader supports the following import modes: + +| Mode | Description | +| ------ | ------------------------------------------------------------ | +| INSERT | Each source record is treated as new data. If the data already exists in the ScalarDB table, based on the partition and clustering key, the import for this source data will fail. | +| UPDATE | Each source record is treated as an update for existing data in the ScalarDB table. If the data does not exist in the table, based on the partition key and clustering key, the import for this source data will fail. | +| UPSERT | If the target ScalarDB table already contains the data, the import will be done via an UPDATE. If the target data is missing, it will be treated as an INSERT. | + +*Note*: + + In the case of `INSERT`, it is required to have matching fields in the source files for each target column via automatic or custom mapping via the control file. This also applies to an `UPSERT` that turns into an `INSERT`. + +## Data mapping + +### Automatic mapping + +When no control file is provided, the data loader will automatically map the fields in the source JSON data to the available columns in the ScalarDB table. If the name does not match, and if all columns are required, it will be treated as a validation error. In this case, the import for this record will fail and the result will be added to the failed output log. + +### Custom mapping + +When the source fields do not match the target column name, it is necessary to use a control file. In this control, file you can specify the custom mapping rules for the field names. + +e.g. the following control file to map the field `custom_id` in the source file to `id` in the target table. + +```json +{ + "tables": [{ + "namespace": "sample", + "table_name": "table1", + "mappings": [{ + "source_field": "custom_id", + "target_column": "id" + }] + } + ] +} +``` + +## Control file + +To allow for custom data mapping or multi-table importing, the data loader supports configuration via a JSON control file. This file needs to be passed in via the `--control-file` argument when starting the data loader. + +### Control file validation levels + +To enforce validation on the control file, the data loader allows you to specify the validation level. Based on the set level, the data loader will run a pre-check and validate the control file based on the level rules. + +The following levels are supported: + +| Level | Description | +| ------ | ------------------------------------------------------------ | +| FULL | This validation makes sure that the control file has mappings for each column in the target ScalarDB table. | +| KEYS | This validation makes sure that mappings are available for each ScalarDB table partition and, if available, clustering keys columns in the control file mappings. | +| MAPPED | The validation makes sure that the provided source fields and target columns exist for only the mappings that are provided in the control file.
No other fields are checked. | + +The validation level is optional and can be set via the `--control-file-validation-level` argument when starting the data loader. + +*Note*: + +This validation is run as a pre-check and does not mean the import process will automatically succeed. + +e.g. If the level is set to mapped and the control file does not contain mappings for each column for an INSERT, the import process will still fail as all columns are required to be mapped for an INSERT. + +## Multi-table import + +The data loader supports multi-table target importing. + +One single row in a JSON or JSONLine file can be imported into multiple tables by specifying table mapping rules in the control file. Currently, multi-table import is not supported without a control file. + +When using multi-table import in ScalarDB transaction mode, a transaction is created for each table import. e.g. If the source record is mapped to 3 tables in the control file, 3 separate transactions are created. + +e.g. The import the following source record into `table1` and `table2` we execute the following steps: + +| Table1 | Table2 | +| ------ | ------ | +| Id | Id | +| price | amount | + +**Source record** + +```json +[{ + "custom_id": 1, + "custom_price": 1000, + "custom_amount": 100 + +}] +``` + +**Control file** + +```json +{ + "tables": [{ + "namespace": "sample", + "table_name": "table1", + "mappings": [{ + "source_field": "custom_id", + "target_column": "id" + }, { + "source_field": "custom_price", + "target_column": "price" + }] + }, + { + "namespace": "sample", + "table_name": "table2", + "mappings": [{ + "source_field": "custom_id", + "target_column": "id" + }, { + "source_field": "custom_amount", + "target_column": "amount" + }] + } + ] +} +``` + + + +## Output logs + +When starting an import task, the data loader logs the import results in two files. One file contains the import data that is successfully imported and one file contains the data that cannot be imported. The failed data will contain an added field that explains why the data could not be imported. This field is called `data_loader_import_status`. + +The file containing the failed imports can be edited to correct the problems and used as the source file for a new import task as is. It is not required to first remove the `data_loader_import_status` field containing the error. This field will be ignored during the import process and the original value will not be included in the new version of the success or failed output file. + +The file with the successfully imported data also contains the `data_loader_import_status` field. In this file, each imported data row has a status message for the data. Whether a new row was created or existing data was updated. + +### Log format + +| Field | Description | +| -------------- | ------------------------------------------------------------ | +| action | The result of the import process for the data record. UPDATE, INSERT or FAILED_DURING_VALIDATION | +| namespace | The name of the namespace of the table that the data is imported in | +| tablename | The name of the table that the data is imported in | +| is_data_mapped | Whether custom data mapping was applied or not based on an available control file. | +| tx_id | The id of the transaction. Only available if the data loader is run in `transaction` mode. | +| value | The final value, after optional data mapping, that the data loader uses in the `PUT` operation. | +| row_number | The line number or record number of the source data. | +| Errors | A list of validation or other errors for things that went wrong during the import process. | + +Example of a JSON formatted success log file: + +```json +[{ + "column_1": 1, + "column_2": 2, + "column_n": 3, + "data_loader_import_status": { + "results": [{ + "action": "UPDATE", + "namespace": "namespace1", + "tableName": "table1", + "is_data_mapped": true, + "tx_id": "value", + "value": "value", + "row_number": "value" + }] + } +}] +``` + + + +Example of a JSON formatted failed log file: + +```json +[{ + "column_1": 1, + "column_2": 2, + "column_n": 3, + "data_loader_import_status": { + "results": [{ + "action": "FAILED_DURING_VALIDATION", + "namespace": "namespace1", + "tableName": "table1", + "is_data_mapped": false, + "value": "value", + "row_number": "value", + "errors": [ + "missing columns found during validation" + ] + }] + } +}] +``` + +## Data duplicates + +The data loader does not handle duplicates by itself. In ScalarDB transaction mode, trying to +update the same target data in fast succession will cause `No Mutation` errors and these are not +handled by the data loader. These failed data rows will be added to the failed import result output +file and can be re-tried for import later. + +However, it is recommended to make sure the import file does not contain updates or inserts on the +same partition keys and/or clustering keys as the correct state cannot be guaranteed by the data +loader. + + + +## Storage vs transaction mode + +ScalarDB supports both storage and transaction mode and this support is included in the data loader import process. + +When the loader is started in storage mode, each import is executed in a non-transactional way. + +Starting the loader in transaction mode will use transactions to import the data. Currently, each row is imported via a separate transaction. When importing a single record into multiple tables, a separate transaction is created for each table import. + diff --git a/versioned_docs/version-3.15/scalardb-graphql/how-to-run-two-phase-commit-transaction.mdx b/versioned_docs/version-3.15/scalardb-graphql/how-to-run-two-phase-commit-transaction.mdx new file mode 100644 index 00000000..85dfdbbc --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-graphql/how-to-run-two-phase-commit-transaction.mdx @@ -0,0 +1,157 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to run two-phase commit transaction + +ScalarDB GraphQL supports two-phase commit style transactions +called [Two-phase Commit Transactions](../two-phase-commit-transactions.mdx). +With Two-phase Commit Transactions, you can execute a transaction that spans multiple +processes/applications (e.g., Microservices). +We name the application that starts a transaction "coordinator" while the applications that +join the transaction are named "participants". +Every two-phase commit operation requires annotating the mutation or query operation with +a `@twoPhaseCommit` directive. Below is a description of such operations. + +## Start a transaction + +To start a transaction, add the `@twoPhaseCommit` directive without setting parameters. + +```graphql +query some_query @twoPhaseCommit { + # some query +} +``` + +The transaction ID of the started transaction will be returned in the extensions object that is part +of the result. + +```json +{ + "data": { + ... + }, + "extensions": { + "transaction": { + "id": "the_transaction_id" + } + } +} +``` + +## Join a transaction (for participants) + +In a participant application, to join the transaction started by a coordinator application, set the +transaction ID with the `id` parameter and set the `join` parameter to true. + +```graphql +query some_query_from_participant @twoPhaseCommit(id:"the_transaction_id", join:true) { + # some query +} +``` + +## Resume a transaction + +To continue executing operations in the started or joined transaction, set the transaction ID value in +the `id` parameter of `@twoPhaseCommit` directive. + +```graphql +mutation some_mutation @twoPhaseCommit(id:"the_transaction_id") { + # some mutation +} +``` + +## Prepare, validate and commit a transaction + +After finishing the query and mutation operations, you need to commit the transaction. Like a +well-known +two-phase commit protocol, there are two phases: prepare and commit. +You first need to prepare the transaction in all the coordinator/participant applications, and then +you +need to commit the transaction in all the coordinator/participant applications. + +If the Consensus Commit transaction manager is configured with the `EXTRA_READ` serializable strategy +in `SERIALIZABLE` isolation level, an extra "validate" phase is required between prepare and +commit phases. +Similarly to prepare and commit, validate need to be executed in all the coordinator/participants +applications. + +Prepare, validate and commit can be executed in parallel with all the coordinator/participants +applications. + +### Prepare a transaction + +Two options are possible to prepare a two-phase commit transaction. + +#### Via the directive parameter + +By using the `prepare` parameter of the directive, the transaction will be prepared after the +execution of the operation fields and only if they do not raise an error. + +```graphql +mutation some_mutation_then_prepare_tx @twoPhaseCommit(id:"the_transaction_id", prepare:true) { + mutation1 : ... + mutation2 : ... + # the transaction will be prepared after the execution of the mutation1 and mutation2 fields +} +``` + +#### Via the mutation field + +Add a `prepare` field in a mutation operation. This field will trigger the transaction +preparation. + +```graphql +mutation prepare_tx @twoPhaseCommit(id:"the_transaction_id") { + prepare +} +``` + +### Validate a transaction + +Add a `validate` field in a mutation operation. This field will trigger the transaction +validation. + +```graphql +mutation validate_tx @twoPhaseCommit(id:"the_transaction_id") { + validate +} +``` + +### Commit a transaction + +Add a `commit` field in a mutation operation. This field will trigger the transaction commit. + +```graphql +mutation commit_tx @twoPhaseCommit(id:"the_transaction_id") { + commit +} +``` + +### Abort/Rollback a transaction + +When you need to abort/rollback a transaction explicitly, you can use the `abort` or `rollback` +mutation fields interchangeably (both have the same effect and usage). Note that you cannot mix it +with any other operations, so you must specify it alone. + +```graphql +mutation AbortTx @twoPhaseCommit(id: "the_transaction_id") { + abort +} +``` + +or + +```graphql +mutation RollbackTx @twoPhaseCommit(id: "the_transaction_id") { + rollback +} +``` + +## Error handling + +If an exception is thrown by a `@twoPhaseCommit` operation, ScalarDB GraphQL triggers a rollback procedure that recovers the transaction. +For more details about the exception handling in two-phase commit transaction, please refer to +the [exception handling guide for ScalarDB two-phase commit transaction](../two-phase-commit-transactions.mdx#handle-exceptions). diff --git a/versioned_docs/version-3.15/scalardb-graphql/index.mdx b/versioned_docs/version-3.15/scalardb-graphql/index.mdx new file mode 100644 index 00000000..c325ea85 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-graphql/index.mdx @@ -0,0 +1,23 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB GraphQL Overview + +ScalarDB GraphQL is an interface layer that allows client applications to communicate with ScalarDB Cluster by using GraphQL. It enables you to take advantage the benefits of GraphQL, such as flexible data retrieval and type safety, while benefiting from the transaction management and data access features in ScalarDB. + +By using ScalarDB GraphQL, you can create GraphQL schemas automatically based on the ScalarDB schemas, perform CRUD operations, and execute complex transactions across multiple databases. The interface simplifies backend development by providing a unified querying mechanism, making it particularly useful for modern applications expecting advanced and responsive data interactions. + +## Getting started with GraphQL in ScalarDB Cluster + +ScalarDB GraphQL is designed to be intuitive and user-friendly, enabling developers to easily create GraphQL schemas automatically based on the ScalarDB schemas and interact with the underlying databases. + +For details on how to set up ScalarDB Cluster with GraphQL support, see [Getting Started with ScalarDB Cluster GraphQL](../scalardb-cluster/getting-started-with-scalardb-cluster-graphql.mdx). + +## Transactions with a two-phase commit + +ScalarDB GraphQL supports executing transactions with a two-phase commit interface. By using the two-phase commit interface, you can execute a transaction that spans multiple processes/applications (for example, microservices applications). + +For details on how to execute transactions by using the two-phase commit interface in ScalarDB GraphQL, see [How to Run Two-Phase Commit Transactions](./how-to-run-two-phase-commit-transaction.mdx). diff --git a/versioned_docs/version-3.15/scalardb-graphql/scalardb-graphql-status-codes.mdx b/versioned_docs/version-3.15/scalardb-graphql/scalardb-graphql-status-codes.mdx new file mode 100644 index 00000000..db653dbc --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-graphql/scalardb-graphql-status-codes.mdx @@ -0,0 +1,243 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB GraphQL Error Codes + +This page provides a list of error codes in ScalarDB GraphQL. + +## Error code classes and descriptions + +| Class | Description | +|:-------------------|:-----------------------------------| +| `DB-GRAPHQL-1xxxx` | Errors for the user error category | + +## `DB-GRAPHQL-1xxxx` status codes + +The following are status codes and messages for the user error category. + +### `DB-GRAPHQL-10000` + +**Message** + +```markdown +A long value was expected +``` + +### `DB-GRAPHQL-10001` + +**Message** + +```markdown +The value is out of range for BigIntValue +``` + +### `DB-GRAPHQL-10002` + +**Message** + +```markdown +A long, integer, or string value was expected +``` + +### `DB-GRAPHQL-10003` + +**Message** + +```markdown +The AST type `IntValue` was expected +``` + +### `DB-GRAPHQL-10004` + +**Message** + +```markdown +A float value was expected +``` + +### `DB-GRAPHQL-10005` + +**Message** + +```markdown +An integer or float value was expected +``` + +### `DB-GRAPHQL-10006` + +**Message** + +```markdown +The AST type `IntValue` or `FloatValue` was expected +``` + +### `DB-GRAPHQL-10007` + +**Message** + +```markdown +The type is not supported. Type: %s +``` + +### `DB-GRAPHQL-10008` + +**Message** + +```markdown +The field `%s` requires a `@transaction` or `@twoPhaseCommit` directive with proper arguments +``` + +### `DB-GRAPHQL-10009` + +**Message** + +```markdown +The field `%s` cannot be used together with other fields +``` + +### `DB-GRAPHQL-10010` + +**Message** + +```markdown +The `@twoPhaseCommit` directive with the `id` argument is required to `%s` the transaction +``` + +### `DB-GRAPHQL-10011` + +**Message** + +```markdown +`%s` and `prepare` cannot be run simultaneously +``` + +### `DB-GRAPHQL-10012` + +**Message** + +```markdown +`%s` and `join` cannot be run simultaneously +``` + +### `DB-GRAPHQL-10013` + +**Message** + +```markdown +The `@transaction` directive with the `id` argument is required to `%s` the transaction +``` + +### `DB-GRAPHQL-10014` + +**Message** + +```markdown +`%s` and `commit` cannot be run simultaneously +``` + +### `DB-GRAPHQL-10015` + +**Message** + +```markdown +An object cannot be annotated with both `@transaction` and `@twoPhaseCommit` directives +``` + +### `DB-GRAPHQL-10016` + +**Message** + +```markdown +The `join` argument of the `@twoPhaseCommit` directive requires a transaction `id` argument +``` + +### `DB-GRAPHQL-10017` + +**Message** + +```markdown +`%s` requires the mutation object to be annotated with a `@twoPhaseCommit` directive +``` + +### `DB-GRAPHQL-10018` + +**Message** + +```markdown +The `%s` clustering key must have only one of the following: %s +``` + +### `DB-GRAPHQL-10019` + +**Message** + +```markdown +A string variable is expected but got %s +``` + +### `DB-GRAPHQL-10020` + +**Message** + +```markdown +Unexpected value of id: %s +``` + +### `DB-GRAPHQL-10021` + +**Message** + +```markdown +A Boolean variable is expected but got %s +``` + +### `DB-GRAPHQL-10022` + +**Message** + +```markdown +Unexpected value of %s: %s +``` + +### `DB-GRAPHQL-10023` + +**Message** + +```markdown +Invalid column. Column: %s; Type: %s +``` + +### `DB-GRAPHQL-10024` + +**Message** + +```markdown +Unexpected value of type: %s +``` + +### `DB-GRAPHQL-10025` + +**Message** + +```markdown +Only one of the following can be specified: %s +``` + +### `DB-GRAPHQL-10026` + +**Message** + +```markdown +Unexpected mutation field: %s +``` + +### `DB-GRAPHQL-10027` + +**Message** + +```markdown +Invalid type: %s +``` diff --git a/versioned_docs/version-3.15/scalardb-samples/README.mdx b/versioned_docs/version-3.15/scalardb-samples/README.mdx new file mode 100644 index 00000000..a2157779 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-samples/README.mdx @@ -0,0 +1,19 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Run Sample Applications Overview + +In this sub-category, you can learn how to run various sample applications that take advantage of ScalarDB. + +To set up and run the sample applications, see the following guides: + +- [Multi-storage Transaction Sample](multi-storage-transaction-sample/README.mdx) +- [Microservice Transaction Sample](microservice-transaction-sample/README.mdx) +- [Spring Data JDBC for ScalarDB with Multi-storage Transaction Sample](spring-data-multi-storage-transaction-sample/README.mdx) +- [Spring Data JDBC for ScalarDB with Microservice Transaction Sample](spring-data-microservice-transaction-sample/README.mdx) +- [Analytical Queries by Using ScalarDB Analytics with PostgreSQL](scalardb-analytics-postgresql-sample/README.mdx) diff --git a/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/README.mdx b/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/README.mdx new file mode 100644 index 00000000..40766fb4 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/README.mdx @@ -0,0 +1,534 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Create a Sample Application That Supports Microservice Transactions + +This tutorial describes how to create a sample application that supports microservice transactions in ScalarDB. + +## Overview + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit through [transactions with a two-phase commit interface](../../two-phase-commit-transactions.mdx) in ScalarDB. + +The sample application has two microservices called the *Customer Service* and the *Order Service* based on the [database-per-service pattern](https://microservices.io/patterns/data/database-per-service.html): + +- The **Customer Service** manages customer information, including line-of-credit information, credit limit, and credit total. +- The **Order Service** is responsible for order operations like placing an order and getting order histories. + +Each service has gRPC endpoints. Clients call the endpoints, and the services call each endpoint as well. + +The databases that you will be using in the sample application are Cassandra and MySQL. The Customer Service and the Order Service use Cassandra and MySQL, respectively, through ScalarDB. + +![Overview](images/overview.png) + +As shown in the diagram, both services access a small Coordinator database used for the Consensus Commit protocol. The database is service-independent and exists for managing transaction metadata for Consensus Commit in a highly available manner. + +In the sample application, for ease of setup and explanation, we co-locate the Coordinator database in the same Cassandra instance of the Order Service. Alternatively, you can manage the Coordinator database as a separate database. + +:::note + +Since the focus of the sample application is to demonstrate using ScalarDB, application-specific error handling, authentication processing, and similar functions are not included in the sample application. For details about exception handling in ScalarDB, see [How to handle exceptions](../../api-guide.mdx#how-to-handle-exceptions). + +Additionally, for the purpose of the sample application, each service has one container so that you can avoid using request routing between the services. However, for production use, because each service typically has multiple servers or hosts for scalability and availability, you should consider request routing between the services in transactions with a two-phase commit interface. For details about request routing, see [Request routing in transactions with a two-phase commit interface](../../two-phase-commit-transactions.mdx#request-routing-in-transactions-with-a-two-phase-commit-interface). + +::: + +### Service endpoints + +The endpoints defined in the services are as follows: + +- Customer Service + - `getCustomerInfo` + - `payment` + - `prepare` + - `validate` + - `commit` + - `rollback` + - `repayment` + +- Order Service + - `placeOrder` + - `getOrder` + - `getOrders` + +### What you can do in this sample application + +The sample application supports the following types of transactions: + +- Get customer information through the `getCustomerInfo` endpoint of the Customer Service. +- Place an order by using a line of credit through the `placeOrder` endpoint of the Order Service and the `payment`, `prepare`, `validate`, `commit`, and `rollback` endpoints of the Customer Service. + - Checks if the cost of the order is below the customer's credit limit. + - If the check passes, records the order history and updates the amount the customer has spent. +- Get order information by order ID through the `getOrder` endpoint of the Order Service and the `getCustomerInfo`, `prepare`, `validate`, `commit`, and `rollback` endpoints of the Customer Service. +- Get order information by customer ID through the `getOrders` endpoint of the Order Service and the `getCustomerInfo`, `prepare`, `validate`, `commit`, and `rollback` endpoints of the Customer Service. +- Make a payment through the `repayment` endpoint of the Customer Service. + - Reduces the amount the customer has spent. + +:::note + +The `getCustomerInfo` endpoint works as a participant service endpoint when receiving a transaction ID from the coordinator. + +::: + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../../requirements.mdx). + +::: + +## Set up ScalarDB + +The following sections describe how to set up the sample application that supports microservices transactions in ScalarDB. + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/microservice-transaction-sample +``` + +### Start Cassandra and MySQL + +Cassandra and MySQL are already configured for the sample application, as shown in [`database-cassandra.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/database-cassandra.properties) and [`database-mysql.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/database-mysql.properties), respectively. For details about configuring the multi-storage transactions feature in ScalarDB, see [How to configure ScalarDB to support multi-storage transactions](../../multi-storage-transactions.mdx#how-to-configure-scalardb-to-support-multi-storage-transactions). + +To start Cassandra and MySQL, which are included in the Docker container for the sample application, run the following command: + +```console +docker-compose up -d mysql cassandra +``` + +:::note + +Starting the Docker container may take more than one minute depending on your development environment. + +::: + +### Load the schema + +The database schema (the method in which the data will be organized) for the sample application has already been defined in [`customer-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service-schema.json) for the Customer Service and [`order-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service-schema.json) for the Order Service. + +To apply the schema, go to the [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) page and download the ScalarDB Schema Loader that matches the version of ScalarDB that you want to use to the `scalardb-samples/microservice-transaction-sample` folder. + +#### MySQL + +To load the schema for [`customer-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service-schema.json) into MySQL, run the following command, replacing `` with the version of the ScalarDB Schema Loader that you downloaded: + +```console +java -jar scalardb-schema-loader-.jar --config database-mysql.properties --schema-file customer-service-schema.json +``` + +#### Cassandra + +To load the schema for [`order-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service-schema.json) into Cassandra, run the following command, replacing `` with the version of the ScalarDB Schema Loader that you downloaded: + +```console +java -jar scalardb-schema-loader-.jar --config database-cassandra.properties --schema-file order-service-schema.json --coordinator +``` + +#### Schema details + +As shown in [`customer-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service-schema.json), all the tables for the Customer Service are created in the `customer_service` namespace. + +- `customer_service.customers`: a table that manages customers' information + - `credit_limit`: the maximum amount of money a lender will allow each customer to spend when using a line of credit + - `credit_total`: the amount of money that each customer has already spent by using their line of credit + +As shown in [`order-service-schema.json`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service-schema.json), all the tables for the Order Service are created in the `order_service` namespace. + +- `order_service.orders`: a table that manages order information +- `order_service.statements`: a table that manages order statement information +- `order_service.items`: a table that manages information of items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/ERD.png) + +### Load the initial data by starting the microservices + +Before starting the microservices, build the Docker images of the sample application by running the following command: + +```console +./gradlew docker +``` + +Then, start the microservices by running the following command: + +```console +docker-compose up -d customer-service order-service +``` + +After starting the microservices and the initial data has loaded, the following records should be stored in the `customer_service.customers` table: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +And the following records should be stored in the `order_service.items` table: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Execute transactions and retrieve data in the sample application + +The following sections describe how to execute transactions and retrieve data in the sample e-commerce application. + +### Get customer information + +Start with getting information about the customer whose ID is `1` by running the following command: + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +``` + +You should see the following output: + +```console +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000} +... +``` + +At this time, `credit_total` isn't shown, which means the current value of `credit_total` is `0`. + +### Place an order + +Then, have customer ID `1` place an order for three apples and two oranges by running the following command: + +:::note + +The order format in this command is `./gradlew run --args="PlaceOrder :,:,..."`. + +::: + +```console +./gradlew :client:run --args="PlaceOrder 1 1:3,2:2" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "4ccdb21c-ac03-4b48-bcb7-cad57eac1e79"} +... +``` + +### Check order details + +Check details about the order by running the following command, replacing `` with the UUID for the `order_id` that was shown after running the previous command: + +```console +./gradlew :client:run --args="GetOrder " +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`: + +```console +... +{"order": {"order_id": "4ccdb21c-ac03-4b48-bcb7-cad57eac1e79","timestamp": 1631605253126,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +### Place another order + +Place an order for one melon that uses the remaining amount in `credit_total` for customer ID `1` by running the following command: + +```console +./gradlew :client:run --args="PlaceOrder 1 5:1" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "0b10db66-faa6-4323-8a7a-474e8534a7ee"} +... +``` + +### Check order history + +Get the history of all orders for customer ID `1` by running the following command: + +```console +./gradlew :client:run --args="GetOrders 1" +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`, which shows the history of all orders for customer ID `1` in descending order by timestamp: + +```console +... +{"order": [{"order_id": "0b10db66-faa6-4323-8a7a-474e8534a7ee","timestamp": 1631605501485,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000},{"order_id": "4ccdb21c-ac03-4b48-bcb7-cad57eac1e79","timestamp": 1631605253126,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}]} +... +``` + +### Check credit total + +Get the credit total for customer ID `1` by running the following command: + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +``` + +You should see the following output, which shows that customer ID `1` has reached their `credit_limit` in `credit_total` and cannot place anymore orders: + +```console +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000,"credit_total": 10000} +... +``` + +Try to place an order for one grape and one mango by running the following command: + +```console +./gradlew :client:run --args="PlaceOrder 1 3:1,4:1" +``` + +You should see the following output, which shows that the order failed because the `credit_total` amount would exceed the `credit_limit` amount: + +```console +... +io.grpc.StatusRuntimeException: FAILED_PRECONDITION: Credit limit exceeded + at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:271) + at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:252) + at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:165) + at sample.rpc.OrderServiceGrpc$OrderServiceBlockingStub.placeOrder(OrderServiceGrpc.java:296) + at sample.client.command.PlaceOrderCommand.call(PlaceOrderCommand.java:38) + at sample.client.command.PlaceOrderCommand.call(PlaceOrderCommand.java:12) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.client.Client.main(Client.java:39) +... +``` + +### Make a payment + +To continue making orders, customer ID `1` must make a payment to reduce the `credit_total` amount. + +Make a payment by running the following command: + +```console +./gradlew :client:run --args="Repayment 1 8000" +``` + +Then, check the `credit_total` amount for customer ID `1` by running the following command: + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +``` + +You should see the following output, which shows that a payment was applied to customer ID `1`, reducing the `credit_total` amount: + +```console +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000,"credit_total": 2000} +... +``` + +Now that customer ID `1` has made a payment, place an order for one grape and one melon by running the following command: + +```console +./gradlew :client:run --args="PlaceOrder 1 3:1,4:1" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "dd53dd9d-aaf4-41db-84b2-56951fed6425"} +... +``` + +## Stop the sample application + +To stop the sample application, you need to stop the Docker containers that are running Cassandra, MySQL, and the microservices. To stop the Docker containers, run the following command: + +```console +docker-compose down +``` + +## Reference - How the microservice transaction is achieved + +The transactions for placing an order, getting a single order, and getting the history of orders achieve the microservice transaction. This section focuses on how the transactions that span the Customer Service and the Order Service are implemented by placing an order as an example. + +The following sequence diagram shows the transaction for placing an order: + +![Microservice transaction sequence diagram](images/sequence_diagram.png) + +### 1. Transaction with a two-phase commit interface is started + +When a client sends a request to place an order to the Order Service, `OrderService.placeOrder()` is called, and the microservice transaction starts. + +At first, the Order Service starts a transaction with a two-phase commit interface with `start()` as follows. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +transaction = twoPhaseCommitTransactionManager.start(); +``` + +### 2. CRUD operations are executed + +After the transaction with a two-phase commit interface starts, CRUD operations are executed. The Order Service puts the order information in the `order_service.orders` table and the detailed information in the `order_service.statements` table as follows. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java): + +```java +// Put the order info into the `orders` table. +Order.put(transaction, orderId, request.getCustomerId(), System.currentTimeMillis()); + +int amount = 0; +for (ItemOrder itemOrder : request.getItemOrderList()) { + // Put the order statement into the `statements` table. + Statement.put(transaction, orderId, itemOrder.getItemId(), itemOrder.getCount()); + + // Retrieve the item info from the `items` table. + Optional item = Item.get(transaction, itemOrder.getItemId()); + if (!item.isPresent()) { + responseObserver.onError( + Status.NOT_FOUND.withDescription("Item not found").asRuntimeException()); + return; + } + + // Calculate the total amount. + amount += item.get().price * itemOrder.getCount(); +} +``` + +Then, the Order Service calls the `payment` gRPC endpoint of the Customer Service along with the transaction ID. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +customerServiceStub.payment( + PaymentRequest.newBuilder() + .setTransactionId(transactionId) + .setCustomerId(customerId) + .setAmount(amount) + .build()); +``` + +The `payment` endpoint of the Customer Service first joins the transaction with `join()` as follows. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +private void execOperationsAsParticipant(String funcName, String transactionId, + TransactionFunction operations, + StreamObserver responseObserver) { + try { + // Join the transaction + TwoPhaseCommitTransaction transaction = twoPhaseCommitTransactionManager.join(transactionId); + + // Execute operations + T response = operations.apply(transaction); +``` + +The endpoint then gets the customer information and checks if the customer's credit total exceeds the credit limit after the payment. If the credit total does not exceed the credit limit, the endpoint updates the customer's credit total. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +execOperationsAsParticipant("Payment", request.getTransactionId(), + transaction -> { + // Retrieve the customer info for the customer ID + Optional result = Customer.get(transaction, request.getCustomerId()); + if (!result.isPresent()) { + throw Status.NOT_FOUND.withDescription("Customer not found").asRuntimeException(); + } + + int updatedCreditTotal = result.get().creditTotal + request.getAmount(); + + // Check if the credit total exceeds the credit limit after payment + if (updatedCreditTotal > result.get().creditLimit) { + throw Status.FAILED_PRECONDITION + .withDescription("Credit limit exceeded") + .asRuntimeException(); + } + + // Update `credit_total` for the customer + Customer.updateCreditTotal(transaction, request.getCustomerId(), updatedCreditTotal); + + return Empty.getDefaultInstance(); + }, responseObserver +); +``` + +### 3. Transaction is committed by using the two-phase commit protocol + +After the Order Service receives the update that the payment succeeded, the Order Service tries to commit the transaction. + +To commit the transaction, the Order Service starts with preparing the transaction. The Order Service calls `prepare()` from its transaction object and calls the `prepare` gRPC endpoint of the Customer Service. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java): + +```java +transaction.prepare(); +callPrepareEndpoint(transaction.getId()); +``` + +In this endpoint, the Customer Service resumes the transaction and calls `prepare()` from its transaction object, as well. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java): + +```java +// Resume the transaction. +transaction = twoPhaseCommitTransactionManager.resume(request.getTransactionId()); + +// Prepare the transaction. +transaction.prepare(); +``` + +Similarly, the Order Service and the Customer Service call `validate()` from their transaction objects. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) and [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). For details about `validate()`, see [Validate the transaction](../../two-phase-commit-transactions.mdx#validate-the-transaction). + +After preparing and validating the transaction succeeds in both the Order Service and the Customer Service, the transaction can be committed. In this case, the Order Service calls `commit()` from its transaction object and then calls the `commit` gRPC endpoint of the Customer Service. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +transaction.commit(); +callCommitEndpoint(transaction.getId()); +``` + +In this endpoint, the Customer Service resumes the transaction and calls `commit()` from its transaction object, as well. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +// Resume the transaction. +transaction = twoPhaseCommitTransactionManager.resume(request.getTransactionId()); + +// Commit the transaction. +transaction.commit(); +``` + +### Error handling + +If an error happens while executing a transaction, you will need to roll back the transaction. In this case, the Order Service calls `rollback()` from its transaction object and then calls the `rollback` gRPC endpoint of the Customer Service. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +transaction.rollback(); +callRollbackEndpoint(transaction.getId()); +``` + +In this endpoint, the Customer Service resumes the transaction and calls `rollback()` from its transaction object, as well. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +// Resume the transaction. +TwoPhaseCommitTransaction transaction = + twoPhaseCommitTransactionManager.resume(request.getTransactionId()); + +// Roll back the transaction. +transaction.rollback(); +``` + +For details about how to handle exceptions in ScalarDB, see [How to handle exceptions](../../api-guide.mdx#how-to-handle-exceptions). diff --git a/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/ERD.png b/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/ERD.png new file mode 100644 index 00000000..c0468efa Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/ERD.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/overview.png b/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/overview.png new file mode 100644 index 00000000..4340b4f5 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/overview.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/sequence_diagram.png b/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/sequence_diagram.png new file mode 100644 index 00000000..0317b5f3 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/microservice-transaction-sample/images/sequence_diagram.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/README.mdx b/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/README.mdx new file mode 100644 index 00000000..6fe2af65 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/README.mdx @@ -0,0 +1,314 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Create a Sample Application That Supports Multi-Storage Transactions + +This tutorial describes how to create a sample application that supports the multi-storage transactions feature in ScalarDB. + +## Overview + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit by using the [multi-storage transactions](../../multi-storage-transactions.mdx) feature in ScalarDB. + +In this tutorial, you will build an application that uses both Cassandra and MySQL. By using the multi-storage transactions feature in ScalarDB, you can execute a transaction that spans both Cassandra and MySQL. + +![Overview](images/overview.png) + +:::note + +Since the focus of the sample application is to demonstrate using ScalarDB, application-specific error handling, authentication processing, and similar functions are not included in the sample application. For details about exception handling in ScalarDB, see [How to handle exceptions](../../api-guide.mdx#how-to-handle-exceptions). + +::: + +### What you can do in this sample application + +The sample application supports the following types of transactions: + +- Get customer information. +- Place an order by using a line of credit. + - Checks if the cost of the order is below the customer's credit limit. + - If the check passes, records the order history and updates the amount the customer has spent. +- Get order information by order ID. +- Get order information by customer ID. +- Make a payment. + - Reduces the amount the customer has spent. + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../../requirements.mdx). + +::: + +## Set up ScalarDB + +The following sections describe how to set up the sample application that supports the multi-storage transactions feature in ScalarDB. + +### Clone the ScalarDB samples repository + +Open **Terminal**, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/multi-storage-transaction-sample +``` + +### Start Cassandra and MySQL + +Cassandra and MySQL are already configured for the sample application, as shown in [`database.properties`](https://github.com/scalar-labs/scalardb-samples/tree/master/multi-storage-transaction-sample/database.properties). For details about configuring the multi-storage transactions feature in ScalarDB, see [How to configure ScalarDB to support multi-storage transactions](../../multi-storage-transactions.mdx#how-to-configure-scalardb-to-support-multi-storage-transactions). + +To start Cassandra and MySQL, which are included in the Docker container for the sample application, make sure Docker is running and then run the following command: + +```console +docker-compose up -d +``` + +:::note + +Starting the Docker container may take more than one minute depending on your development environment. + +::: + +### Load the schema + +The database schema (the method in which the data will be organized) for the sample application has already been defined in [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/master/multi-storage-transaction-sample/schema.json). + +To apply the schema, go to the [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) page and download the ScalarDB Schema Loader that matches the version of ScalarDB that you want to use to the `scalardb-samples/multi-storage-transaction-sample` folder. + +Then, run the following command, replacing `` with the version of the ScalarDB Schema Loader that you downloaded: + +```console +java -jar scalardb-schema-loader-.jar --config database.properties --schema-file schema.json --coordinator +``` + +#### Schema details + +As shown in [`schema.json`](https://github.com/scalar-labs/scalardb-samples/tree/master/multi-storage-transaction-sample/schema.json) for the sample application, all the tables are created in the `customer` and `order` namespaces. + +- `customer.customers`: a table that manages customers' information + - `credit_limit`: the maximum amount of money a lender will allow each customer to spend when using a line of credit + - `credit_total`: the amount of money that each customer has already spent by using their line of credit +- `order.orders`: a table that manages order information +- `order.statements`: a table that manages order statement information +- `order.items`: a table that manages information of items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/ERD.png) + +### Load the initial data + +After the Docker container has started, load the initial data by running the following command: + +```console +./gradlew run --args="LoadInitialData" +``` + +After the initial data has loaded, the following records should be stored in the tables. + +**`customer.customers` table** + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +**`order.items` table** + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Execute transactions and retrieve data in the sample application + +The following sections describe how to execute transactions and retrieve data in the sample e-commerce application. + +### Get customer information + +Start with getting information about the customer whose ID is `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 0} +... +``` + +### Place an order + +Then, have customer ID `1` place an order for three apples and two oranges by running the following command: + +:::note + +The order format in this command is `./gradlew run --args="PlaceOrder :,:,..."`. + +::: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e"} +... +``` + +### Check order details + +Check details about the order by running the following command, replacing `` with the UUID for the `order_id` that was shown after running the previous command: + +```console +./gradlew run --args="GetOrder " +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`: + +```console +... +{"order": {"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +### Place another order + +Place an order for one melon that uses the remaining amount in `credit_total` for customer ID `1` by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 5:1" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d"} +... +``` + +### Check order history + +Get the history of all orders for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetOrders 1" +``` + +You should see a similar output as below, with different UUIDs for `order_id` and `timestamp`, which shows the history of all orders for customer ID `1` in descending order by timestamp: + +```console +... +{"order": [{"order_id": "dea4964a-ff50-4ecf-9201-027981a1566e","timestamp": 1650948340914,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000},{"order_id": "bcc34150-91fa-4bea-83db-d2dbe6f0f30d","timestamp": 1650948412766,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000}]} +... +``` + +### Check credit total + +Get the credit total for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output, which shows that customer ID `1` has reached their `credit_limit` in `credit_total` and cannot place anymore orders: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 10000} +... +``` + +Try to place an order for one grape and one mango by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +You should see the following output, which shows that the order failed because the `credit_total` amount would exceed the `credit_limit` amount: + +```console +... +java.lang.RuntimeException: Credit limit exceeded + at sample.Sample.placeOrder(Sample.java:205) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:33) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:8) + at picocli.CommandLine.executeUserObject(CommandLine.java:1783) + at picocli.CommandLine.access$900(CommandLine.java:145) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2141) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2108) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:1975) + at picocli.CommandLine.execute(CommandLine.java:1904) + at sample.command.SampleCommand.main(SampleCommand.java:35) +... +``` + +### Make a payment + +To continue making orders, customer ID `1` must make a payment to reduce the `credit_total` amount. + +Make a payment by running the following command: + +```console +./gradlew run --args="Repayment 1 8000" +``` + +Then, check the `credit_total` amount for customer ID `1` by running the following command: + +```console +./gradlew run --args="GetCustomerInfo 1" +``` + +You should see the following output, which shows that a payment was applied to customer ID `1`, reducing the `credit_total` amount: + +```console +... +{"id": 1, "name": "Yamada Taro", "credit_limit": 10000, "credit_total": 2000} +... +``` + +Now that customer ID `1` has made a payment, place an order for one grape and one melon by running the following command: + +```console +./gradlew run --args="PlaceOrder 1 3:1,4:1" +``` + +You should see a similar output as below, with a different UUID for `order_id`, which confirms that the order was successful: + +```console +... +{"order_id": "8911cab3-1c2b-4322-9386-adb1c024e078"} +... +``` + +## Stop the sample application + +To stop the sample application, stop the Docker container by running the following command: + +```console +docker-compose down +``` diff --git a/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/ERD.png b/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/ERD.png new file mode 100644 index 00000000..02100437 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/ERD.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/overview.png b/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/overview.png new file mode 100644 index 00000000..16749f3b Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/multi-storage-transaction-sample/images/overview.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/scalardb-analytics-postgresql-sample/README.mdx b/versioned_docs/version-3.15/scalardb-samples/scalardb-analytics-postgresql-sample/README.mdx new file mode 100644 index 00000000..d29a7a24 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-samples/scalardb-analytics-postgresql-sample/README.mdx @@ -0,0 +1,305 @@ +--- +tags: + - Community +displayed_sidebar: docsEnglish +--- + +# Run Analytical Queries on Sample Data by Using ScalarDB Analytics with PostgreSQL + +This tutorial describes how to run analytical queries on sample data by using ScalarDB Analytics with PostgreSQL. + +## Overview + +This sample tutorial shows how you can run two types of queries: a single-table query and a multi-table query. + +### What you can do in this sample tutorial + +This sample tutorial shows how you can run the following types of queries: + +- Read data and calculate summaries. +- Join tables that span multiple storages. + +:::note + +You can run any arbitrary query that PostgreSQL supports on the imported tables in this sample tutorial. Since ScalarDB Analytics with PostgreSQL supports all queries that PostgreSQL supports, you can use not only join, aggregation, filtering, and ordering as shown in the example, but also the window function, lateral join, or various analytical operations. + +To see which types of queries PostgreSQL supports, see the [PostgreSQL documentation](https://www.postgresql.org/docs/current/index.html). + +::: + +## Prerequisites + +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later +- [psql](https://www.postgresql.org/docs/current/app-psql.html) + +## Set up ScalarDB Analytics with PostgreSQL + +First, you must set up the database to run analytical queries with ScalarDB Analytics with PostgreSQL. If you haven't set up the database yet, please follow the instructions in [Getting Started](../../scalardb-analytics-postgresql/getting-started.mdx). + +### Schema details in ScalarDB + +In this sample tutorial, you have tables with the following schema in the ScalarDB database: + +```mermaid +erDiagram + "dynamons.customer" ||--|{ "postgresns.orders" : "custkey" + "dynamons.customer" { + int c_custkey + text c_name + text c_address + int c_nationkey + text c_phone + double c_acctbal + text c_mktsegment + text c_comment + } + "postgresns.orders" ||--|{ "cassandrans.lineitem" : "orderkey" + "postgresns.orders" { + int o_orderkey + int o_custkey + text o_orderstatus + double o_totalprice + text o_orderdate + text o_orderpriority + text o_clerk + int o_shippriority + text o_comment + } + "cassandrans.lineitem" { + int l_orderkey + int l_partkey + int l_suppkey + int l_linenumber + double l_quantity + double l_extendedprice + double l_discount + double l_tax + text l_returnflag + text l_linestatus + text l_shipdate + text l_commitdate + text l_receiptdate + text l_shipinstruct + text l_shipmode + text l_comment + } +``` + +For reference, this diagram shows the following: + +- `dynamons`, `postgresns`, and `cassandrans`. Namespaces that are mapped to the back-end storages of DynamoDB, PostgreSQL, and Cassandra, respectively. +- `dynamons.customer`. A table that represents information about customers. This table includes attributes like customer key, name, address, phone number, and account balance. +- `postgresns.orders`. A table that contains information about orders that customers have placed. This table includes attributes like order key, customer key, order status, order date, and order priority. +- `cassandrans.lineitem`. A table that represents line items associated with orders. This table includes attributes such as order key, part key, supplier key, quantity, price, and shipping date. + +### Schema details in PostgreSQL + +By running the Schema Importer when setting up ScalarDB, you can import the table schema in the ScalarDB database into the PostgreSQL database. More precisely, for each `namespace_name.table_name` table in the ScalarDB database, you will have a foreign table for `namespace_name._table_name` and a view for `namespace_name.table_name` in the PostgreSQL database. + +The created foreign table contains columns that are identical to the ScalarDB table and the transaction metadata columns that ScalarDB manages internally. Since the created view is defined to exclude the transaction metadata columns from the foreign table, the created view contains only the same columns as the ScalarDB table. + +You can find the schema of the ScalarDB tables in `schema.json`. For example, the `dynamons.customer` table is defined as follows: + +```json + "dynamons.customer": { + "transaction": true, + "partition-key": [ + "c_custkey" + ], + "columns": { + "c_custkey": "INT", + "c_name": "TEXT", + "c_address": "TEXT", + "c_nationkey": "INT", + "c_phone": "TEXT", + "c_acctbal": "DOUBLE", + "c_mktsegment": "TEXT", + "c_comment": "TEXT" + } + }, +``` + +To see the foreign table for `dynamons._customer` in the PostgreSQL database, run the following command and enter your PostgreSQL user password when prompted: + +```console +psql -U postgres -h localhost test -c '\d dynamons._customer'; +``` + +After entering your password, you should see the following output, which shows the same `c_` columns as in the `dynamons.customer` table: + +```console + Foreign table "dynamons._customer" + Column | Type | Collation | Nullable | Default | FDW options +------------------------+------------------+-----------+----------+---------+------------- + c_custkey | integer | | | | + c_name | text | | | | + c_address | text | | | | + c_nationkey | integer | | | | + c_phone | text | | | | + c_acctbal | double precision | | | | + c_mktsegment | text | | | | + c_comment | text | | | | + tx_id | text | | | | + tx_version | integer | | | | + tx_state | integer | | | | + tx_prepared_at | bigint | | | | + tx_committed_at | bigint | | | | + before_tx_id | text | | | | + before_tx_version | integer | | | | + before_tx_state | integer | | | | + before_tx_prepared_at | bigint | | | | + before_tx_committed_at | bigint | | | | + before_c_name | text | | | | + before_c_address | text | | | | + before_c_nationkey | integer | | | | + before_c_phone | text | | | | + before_c_acctbal | double precision | | | | + before_c_mktsegment | text | | | | + before_c_comment | text | | | | +Server: multi_storage_dynamodb +FDW options: (namespace 'dynamons', table_name 'customer') +``` + +As you can see in the foreign table, the table also contains the transaction metadata columns. These columns are required to ensure the Read Committed isolation level. + +To see the view for `dynamons.customer`, run the following command and enter your PostgreSQL user password when prompted: + +```console +psql -U postgres -h localhost test -c '\d dynamons.customer'; +``` + +After entering your password, you should see the following output: + +```console + View "dynamons.customer" + Column | Type | Collation | Nullable | Default +--------------+------------------+-----------+----------+--------- + c_custkey | integer | | | + c_name | text | | | + c_address | text | | | + c_nationkey | integer | | | + c_phone | text | | | + c_acctbal | double precision | | | + c_mktsegment | text | | | + c_comment | text | | | +``` + +The column definitions in this view are the same as the original table in the ScalarDB database. This view is created based on the foreign table explained above to expose only the valid data with the Read Committed isolation level by interpreting the transaction metadata columns. + +:::note + +Normally, you don't need to access the foreign tables directly. Instead, you can equate the views with the tables in the ScalarDB database. + +::: + +For details about type mapping between ScalarDB and PostgreSQL, see [Data-type mapping between ScalarDB and other databases](../../schema-loader.mdx#data-type-mapping-between-scalardb-and-other-databases). + +## Run analytical queries + +The following sections describe how to read data, calculate summaries, and join tables that span multiple storages. + +### Read data and calculate summaries + +You can run a query that reads data from `cassandrans.lineitem`, with the actual data stored in the Cassandra back-end, and calculates several summaries of the ordered line items by aggregating the data. + +To run the query, log in to the psql terminal by running the following command: + +```console +psql -U postgres -h localhost test +``` + +After entering your password, enter the following query into the psql terminal: + +```console +SELECT + l_returnflag, + l_linestatus, + sum(l_quantity) AS sum_qty, + sum(l_extendedprice) AS sum_base_price, + sum(l_extendedprice * (1 - l_discount)) AS sum_disc_price, + sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) AS sum_charge, + avg(l_quantity) AS avg_qty, + avg(l_extendedprice) AS avg_price, + avg(l_discount) AS avg_disc, + count(*) AS count_order +FROM + cassandrans.lineitem +WHERE + to_date(l_shipdate, 'YYYY-MM-DD') <= date '1998-12-01' - 3 +GROUP BY + l_returnflag, + l_linestatus +ORDER BY + l_returnflag, + l_linestatus; +``` + +You should see the following output: + +```console + l_returnflag | l_linestatus | sum_qty | sum_base_price | sum_disc_price | sum_charge | avg_qty | avg_price | avg_disc | count_order +--------------+--------------+---------+--------------------+--------------------+--------------------+---------------------+--------------------+---------------------+------------- + A | F | 1519 | 2374824.6560430005 | 1387363.5818635763 | 1962762.9341866106 | 26.6491228070175439 | 41663.590456894744 | 0.4150182982456142 | 57 + N | F | 98 | 146371.22954200002 | 85593.92837883368 | 121041.52567369482 | 32.6666666666666667 | 48790.409847333336 | 0.4098473333333333 | 3 + N | O | 5374 | 8007373.247144971 | 4685645.630765834 | 6624209.157932242 | 24.4272727272727273 | 36397.15112338623 | 0.414759749999999 | 220 + R | F | 1461 | 2190869.967642001 | 1284177.8484816086 | 1814150.7929095028 | 25.1896551724137931 | 37773.62013175864 | 0.41323520689655185 | 58 +(4 rows) +``` + +### Join tables that span multiple storages + +You can also run a query to join tables that are connected to the three back-end storages and calculate the unshipped orders with the highest revenue on a particular date. + +To run the query, log in to the psql terminal by running the following command: + +```console +psql -U postgres -h localhost test +``` + +After entering your password, enter the following query into the psql terminal: + +```console +SELECT + l_orderkey, + sum(l_extendedprice * (1 - l_discount)) AS revenue, + o_orderdate, + o_shippriority +FROM + dynamons.customer, + postgresns.orders, + cassandrans.lineitem +WHERE + c_mktsegment = 'AUTOMOBILE' + AND c_custkey = o_custkey + AND l_orderkey = o_orderkey + AND o_orderdate < '1995-03-15' + AND l_shipdate > '1995-03-15' +GROUP BY + l_orderkey, + o_orderdate, + o_shippriority +ORDER BY + revenue DESC, + o_orderdate, + l_orderkey +LIMIT 10; +``` + +You should see the following output: + +```console + l_orderkey | revenue | o_orderdate | o_shippriority +------------+--------------------+-------------+---------------- + 1071617 | 128186.94002748765 | 1995-03-10 | 0 + 1959075 | 33104.49713665398 | 1994-12-23 | 0 + 430243 | 19476.107574179696 | 1994-12-24 | 0 +(3 rows) +``` + +## Stop ScalarDB Analytics with PostgreSQL and the database + +To stop ScalarDB Analytics with PostgreSQL and the database, stop the Docker container by running the following command: + +```console +docker-compose down +``` diff --git a/versioned_docs/version-3.15/scalardb-samples/scalardb-analytics-spark-sample/README.mdx b/versioned_docs/version-3.15/scalardb-samples/scalardb-analytics-spark-sample/README.mdx new file mode 100644 index 00000000..93581b2e --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-samples/scalardb-analytics-spark-sample/README.mdx @@ -0,0 +1,455 @@ +--- +tags: + - Enterprise Option +displayed_sidebar: docsEnglish +--- + +# Getting Started with ScalarDB Analytics + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This tutorial describes how to run analytical queries on sample data by using ScalarDB Analytics. The source code is available at [https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-analytics-spark-sample](https://github.com/scalar-labs/scalardb-samples/tree/main/scalardb-analytics-spark-sample). + +ScalarDB Analytics in its current version leverages Apache Spark as its execution engine. It provides a unified view of ScalarDB-managed and non-ScalarDB-managed data sources by using a Spark custom catalog. By using ScalarDB Analytics, you can treat tables from these data sources as native Spark tables. This allows you to execute arbitrary Spark SQL queries seamlessly. For example, you can join a table stored in Cassandra with a table in PostgreSQL to perform cross-database analysis with ease. + +## Overview of the sample application + +This sample tutorial demonstrates how to configure Spark to enable ScalarDB Analytics and perform interactive analyses using `spark-sql` on tables provided by ScalarDB Analytics. + +## Prerequisites for this sample application + +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + + + +## Step 1: Set up ScalarDB Analytics + +### Clone the ScalarDB samples repository + +Open **Terminal**, and clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory that contains the sample application by running the following command: + +```console +cd scalardb-samples/scalardb-analytics-spark-sample +``` + +### Set your license information + +ScalarDB Analytics requires valid license information to be specified in the Spark configuration. You can provide your license details in the **spark-defaults.conf** file. + + +Open the **spark-defaults.conf** file located in the **conf** directory of your Spark installation. Then, replace `` with your license key and `` with the PEM-encoded contents of your license certificate. + +```console +spark.sql.catalog.test_catalog.license.key +spark.sql.catalog.test_catalog.license.cert_pem +``` + +For additional configuration details required in the **spark-defaults.conf** file for setting up ScalarDB Analytics, refer to [ScalarDB Analytics configuration](#scalardb-analytics-configuration). + +## Step 2: Set up the sample databases + +To set up the sample databases, run the following command: + +```console +docker compose up -d --wait +``` + +This command starts three services locally: PostgreSQL, Cassandra, and MySQL. + +- **PostgreSQL:** Used independently (non-ScalarDB-managed). +- **Cassandra and MySQL:** Used as backend databases for ScalarDB (ScalarDB-managed). + +In this guide, PostgreSQL is referred to as a **non-ScalarDB-managed database**, which is not managed by ScalarDB transactions, while Cassandra and DynamoDB are referred to as **ScalarDB-managed databases**, which are managed by ScalarDB transactions. + +For non-ScalarDB-managed databases, sample data is automatically loaded when the Docker container is initialized, so no additional steps are required. For ScalarDB-managed databases, run the following command to load the sample data after starting the containers: + +```console +docker compose run --rm sample-data-loader +``` + +After completing the setup, the following tables should be available: + +- In PostgreSQL: + - `sample_ns.customer` +- In ScalarDB (backed by Cassandra): + - `cassandrans.lineitem` +- In ScalarDB (backed by MySQL): + - `mysqlns.order` + +According to the above, within ScalarDB, `cassandrans` and `mysqlns` are mapped to Cassandra and MySQL, respectively. + +For details about the table schema, including column definitions and data types, refer to [Schema details](#schema-details). Ensure that the sample data has been successfully loaded into these tables. + +## Step 3: Launch the Spark SQL console + +To launch the Spark SQL console, run the following command: + +```console +docker compose run --rm spark-sql +``` + +While launching the Spark SQL console, the ScalarDB Analytics catalog is initialized with the configuration in **spark-defaults.conf** and is registered as a Spark catalog named `test_catalog`. + +### Namespace mapping + +The following tables in the configured data sources are mapped to Spark SQL tables, allowing seamless querying across different data sources: + +- For PostgreSQL: + - `test_catalog.postgresql.sample_ns.customer` +- For ScalarDB (backed by Cassandra): + - `test_catalog.scalardb.cassandrans.lineitem` +- For ScalarDB (backed by MySQL): + - `test_catalog.scalardb.mysqlns.orders` + +For more details about how tables are mapped to Spark SQL tables, refer to [Namespace-mapping details](#namespace-mapping-details). + +Additionally, ScalarDB Analytics offers WAL-interpreted views for ScalarDB tables, simplifying common use cases. In this sample application, you have the following WAL-interpreted views available: + +- For ScalarDB (backed by Cassandra): + - `test_catalog.view.scalardb.cassandrans.lineitem` +- For ScalarDB (backed by MySQL): + - `test_catalog.view.scalardb.mysqlns.orders` + +In most cases, WAL-interpreted views are preferred over raw tables. In this tutorial, we will use the WAL-interpreted views for the ScalarDB tables. For detailed information on WAL-interpreted views, including their use cases and benefits, see [WAL-interpreted views for ScalarDB tables](#wal-interpreted-views-for-scalardb-tables). + +## Step 4: Run analytical queries + +Now, everything is set up, and you can run analytical queries on the sample data using the Spark SQL console. + +### Read data and calculate summaries + +You can run the following query to retrieve data from `test_catalog.scalardb.cassandrans.lineitem` in Cassandra and calculate aggregated metrics, including total quantity, average price, and total revenue for line items grouped by their return flag and line status. + +```sql +SELECT + l_returnflag, + l_linestatus, + sum(l_quantity) AS sum_qty, + sum(l_extendedprice) AS sum_base_price, + sum(l_extendedprice * (1 - l_discount)) AS sum_disc_price, + sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) AS sum_charge, + avg(l_quantity) AS avg_qty, + avg(l_extendedprice) AS avg_price, + avg(l_discount) AS avg_disc, + count(*) AS count_order +FROM + test_catalog.view.scalardb.cassandrans.lineitem +WHERE + to_date(l_shipdate, 'yyyy-MM-dd') <= date '1998-12-01' - 3 +GROUP BY + l_returnflag, + l_linestatus +ORDER BY + l_returnflag, + l_linestatus; +``` + +You should see the following output: + +```console +A F 1519 2374824.6560278563 1387364.2207725341 1962763.4654265852 26.649122807017545 41663.590456629056 0.41501802923479575 57 +N F 98 146371.2295412012 85593.96776336085 121041.55837332775 32.666666666666664 48790.409847067065 0.40984706454007996 3 +N O 5374 8007373.247086477 4685647.785126835 6624210.945739046 24.427272727272726 36397.15112312035 0.4147594809559689 220 +R F 1461 2190869.9676265526 1284178.4378283697 1814151.2807494882 25.189655172413794 37773.62013149229 0.41323493790730753 58 +``` + +### Join tables that span multiple data sources + +You can also run the following query to join tables from multiple data sources, including both ScalarDB-managed and non-ScalarDB-managed tables. This query joins customer, order, and line item data from PostgreSQL, MySQL, and Cassandra, identifying the top unshipped orders with the highest revenue on a specific date. This analysis helps prioritize shipments for maximum financial impact. + +```sql +SELECT + l_orderkey, + sum(l_extendedprice * (1 - l_discount)) AS revenue, + o_orderdate, + o_shippriority +FROM + test_catalog.postgresql.sample_ns.customer, + test_catalog.scalardb.mysqlns.orders, + test_catalog.scalardb.cassandrans.lineitem +WHERE + c_mktsegment = 'AUTOMOBILE' + AND c_custkey = o_custkey + AND l_orderkey = o_orderkey + AND o_orderdate < '1995-03-15' + AND l_shipdate > '1995-03-15' +GROUP BY + l_orderkey, + o_orderdate, + o_shippriority +ORDER BY + revenue DESC, + o_orderdate, + l_orderkey +LIMIT 10; +``` + +You should see the following output: + +```console +1071617 128186.99915996166 1995-03-10 0 +1959075 33104.51278645416 1994-12-23 0 +430243 19476.115819260962 1994-12-24 0 +``` + +:::note + +You can also run any arbitrary query that Apache Spark and Spark SQL support on the imported tables in this sample tutorial. Since ScalarDB Analytics supports all queries that Spark SQL supports, you can do not only selections (filtering), joins, aggregations, and ordering, as shown in the example, but also window functions, lateral joins, and other various operations. + +To see which types of queries Spark SQL supports, see the [Spark SQL documentation](https://spark.apache.org/docs/latest/sql-ref.html). + +::: + +## Step 5: Stop the sample application + +To stop the sample application and remove all associated volumes, run the following command. This action shuts down all services and deletes any persisted data stored in the volumes, resetting the application state: + +```console +docker compose down -v +``` + +## Reference + +This section contains other details related to ScalarDB Analytics, like configurations and schema details. + +### ScalarDB Analytics configuration + +You can configure ScalarDB Analytics in the Spark configuration, such as in the `spark-defaults.conf` file. This section contains brief explanations of the configurations for ScalarDB Analytics in this sample application. + +#### Common configurations + +The following are common configurations for ScalarDB Analytics: + +```console +spark.sql.catalog.test_catalog com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog +spark.sql.extensions com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions +``` + +The first line specifies the Spark catalog plugin implementation class. You must always set this to `com.scalar.db.analytics.spark.ScalarDbAnalyticsCatalog` to enable the ScalarDB Analytics catalog in Spark SQL. + +:::note + +You can set an arbitrary string as the catalog name, which is `test_catalog` in this example. The configured catalog name will be used as a part of the table identifier in the Spark SQL query. + +::: + +The second line specifies the Spark SQL extension implementation class. You must always set this to `com.scalar.db.analytics.spark.extension.ScalarDbAnalyticsExtensions`, along with the `spark.sql.catalog.test_catalog` configuration, mentioned above. + +#### License information + +The following are the license configurations for ScalarDB Analytics: + +```apacheconf +spark.sql.catalog.test_catalog.license.key +spark.sql.catalog.test_catalog.license.cert_pem +``` + +These lines provide the license information for ScalarDB Analytics. As explained above, you must replace the placeholders with your license information before launching the Spark SQL console. + +#### Data source configurations for ScalarDB-managed databases + +The following are the data source configurations for ScalarDB-managed databases for ScalarDB Analytics: + +```apacheconf +spark.sql.catalog.test_catalog.data_source.scalardb.type scalardb +spark.sql.catalog.test_catalog.data_source.scalardb.config_path /etc/scalardb.properties +``` + +The first line specifies the data source type. You must always set this to `scalardb` to configure the data source for ScalarDB-managed databases. The second line specifies the path to the configuration file for the ScalarDB data source, which is the only required configuration for the ScalarDB data source. + +:::note + +You can set an arbitrary string as the data source name, which is `scalardb` in this example. The configured data source names will be used as a part of the table identifier in the Spark SQL query. + +::: + +#### Data source configurations for non-ScalarDB-managed databases + +The following are the data source configurations for non-ScalarDB-managed databases for ScalarDB Analytics: + +```apacheconf +spark.sql.catalog.test_catalog.data_source.postgresql.type postgresql +spark.sql.catalog.test_catalog.data_source.postgresql.host postgres +spark.sql.catalog.test_catalog.data_source.postgresql.port 5432 +spark.sql.catalog.test_catalog.data_source.postgresql.username postgres +spark.sql.catalog.test_catalog.data_source.postgresql.password postgres +spark.sql.catalog.test_catalog.data_source.postgresql.database sampledb +``` + +These lines configure the data source PostgreSQL as a non-ScalarDB-managed database. The first line specifies the data source type, and the rest of the lines specify the data source-specific configurations, which is the connection information for the PostgreSQL data source. The data source–specific configurations may vary depending on the data source type. + +:::note + +You can set an arbitrary string as the data source name, which is `postgresql` in this example, in the same way as the ScalarDB data source. + +::: + +### Schema details + +The following entity relationship diagram illustrates the relationships between the tables across PostgreSQL, MySQL, and Cassandra, with foreign keys linking customers, orders, and line items. + +```mermaid +erDiagram + "postgresql.sample_ns.customer" ||--|{ "scalardb.mysqlns.orders" : "custkey" + "postgresql.sample_ns.customer" { + int c_custkey + text c_name + text c_address + int c_nationkey + text c_phone + double c_acctbal + text c_mktsegment + text c_comment + } + "scalardb.mysqlns.orders" ||--|{ "scalardb.cassandrans.lineitem" : "orderkey" + "scalardb.mysqlns.orders" { + int o_orderkey + int o_custkey + text o_orderstatus + double o_totalprice + text o_orderdate + text o_orderpriority + text o_clerk + int o_shippriority + text o_comment + } + "scalardb.cassandrans.lineitem" { + int l_orderkey + int l_partkey + int l_suppkey + int l_linenumber + double l_quantity + double l_extendedprice + double l_discount + double l_tax + text l_returnflag + text l_linestatus + text l_shipdate + text l_commitdate + text l_receiptdate + text l_shipinstruct + text l_shipmode + text l_comment + } +``` + +- `postgresql.sample_ns.customer` comes from PostgreSQL, which is not managed by ScalarDB. +- `scalardb.mysqlns.orders` and `scalardb.cassandrans.lineitem` come from ScalarDB, which are backed by MySQL and Cassandra, respectively. + +The following are brief descriptions of the tables: + +- **`postgresql.sample_ns.customer`.** A table that represents information about customers. This table includes attributes like customer key, name, address, phone number, and account balance. +- **`scalardb.mysqlns.orders`.** A table that contains information about orders that customers have placed. This table includes attributes like order key, customer key, order status, order date, and order priority. +- **`scalardb.cassandrans.lineitem`.** A table that represents line items associated with orders. This table includes attributes such as order key, part key, supplier key, quantity, price, and shipping date. + +### Namespace-mapping details + +The tables of each configured data source are mapped to the Spark SQL identifier by using the following format: + +```console +...`. +``` + +The following explains each part of the table identifier: + +- **``.** The catalog name configured in spark-defaults.conf. This identifies the ScalarDB Analytics catalog in Spark SQL. +- **``.** The data source name configured in spark-defaults.conf, representing the specific type of data source, such as postgresql or scalardb. +- **``.** The namespace name in the data source. For example: + - In an RDBMS like PostgreSQL or MySQL, this corresponds to the schema. + - In NoSQL databases like Cassandra, this may refer to a keyspace. +- **``.** The name of the table in the namespace. + +In this example, the following tables are available: + +- For PostgreSQL: + - test_catalog.postgresql.sample_ns.customer +- For ScalarDB (backed by Cassandra): + - test_catalog.scalardb.cassandrans.lineitem +- For ScalarDB (backed by MySQL): + - test_catalog.scalardb.mysqlns.orders + +This mapping allows you to access and query tables from different data sources seamlessly by using Spark SQL. + +### WAL-interpreted views for ScalarDB tables + +ScalarDB tables that are transaction-enabled include transaction metadata columns in the raw tables stored in the underlying data sources. Since ScalarDB Analytics maps these raw tables directly to Spark SQL tables, you will see transaction metadata columns when describing these tables in Spark SQL. You can see these columns by running the following command: + +```sql +DESCRIBE test_catalog.scalardb.mysqlns.orders; +``` + +You should see the following output: + +```console +o_orderkey int +o_custkey int +o_orderstatus string +o_totalprice double +o_orderdate string +o_orderpriority string +o_clerk string +o_shippriority int +o_comment string +tx_id string +tx_state int +tx_version int +tx_prepared_at bigint +tx_committed_at bigint +before_tx_id string +before_tx_state int +before_tx_version int +before_tx_prepared_at bigint +before_tx_committed_at bigint +before_o_orderstatus string +before_o_clerk string +before_o_orderdate string +before_o_shippriority int +before_o_custkey int +before_o_totalprice double +before_o_comment string +before_o_orderpriority string +``` + +In many cases, you may not need the transaction metadata columns in your queries. To simplify this, ScalarDB Analytics provides WAL-interpreted views. WAL-interpreted views hide transaction metadata columns and expose only user-defined columns, simplifying queries. For example, use WAL-interpreted views when performing read-only analytics or when transaction metadata is not needed for analysis. Additionally, WAL-interpreted views guarantee read-committed consistency by interpreting the transaction metadata columns internally. + +#### WAL-interpreted view naming convention in Spark SQL + +WAL-interpreted views are prefixed with `view.` before the data source part of the table identifier. For example, the following WAL-interpreted views are available for ScalarDB tables: + +- For ScalarDB (backed by Cassandra): + - test_catalog.view.scalardb.cassandrans.lineitem +- For ScalarDB (backed by MySQL): + - test_catalog.view.scalardb.mysqlns.orders + +For example, to see the WAL-interpreted view for the ScalarDB table backed by Cassandra, run the following command: + +```sql +DESCRIBE test_catalog.view.scalardb.cassandrans.lineitem; +``` + +You should see the following output: + +```console +l_orderkey int +l_linenumber int +l_comment string +l_commitdate string +l_discount double +l_extendedprice double +l_linestatus string +l_partkey int +l_quantity int +l_receiptdate string +l_returnflag string +l_shipdate string +l_shipinstruct string +l_shipmode string +l_suppkey int +l_tax double +``` diff --git a/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/README.mdx b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/README.mdx new file mode 100644 index 00000000..08a602db --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/README.mdx @@ -0,0 +1,529 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Sample application of Spring Data JDBC for ScalarDB with Microservice Transactions + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This tutorial describes how to create a sample Spring Boot application for microservice transactions by using Spring Data JDBC for ScalarDB. + +For details about these features, see [Two-phase Commit Transactions](../../two-phase-commit-transactions.mdx) and [Guide of Spring Data JDBC for ScalarDB](../../scalardb-sql/spring-data-guide.mdx). + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../../requirements.mdx). + +::: + + + +## Sample application + +### Overview + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit through [transactions with a two-phase commit interface](../../two-phase-commit-transactions.mdx) in ScalarDB. + +There are two microservices called the *Customer Service* and the *Order Service* based on the [*Database-per-service* pattern](https://microservices.io/patterns/data/database-per-service.html) in this sample application. + +The Customer Service manages customers' information including credit card information like a credit limit and a credit total. +The Order Service is responsible for order operations like placing an order and getting order histories. +Each service has gRPC endpoints. Clients call the endpoints, and the services call the endpoints each other as well. +The Customer Service and the Order Service use MySQL and Cassandra through ScalarDB, respectively. + +![Overview](images/overview.png) + +Each service accesses the databases through its own dedicated ScalarDB Cluster. + +:::note +Both ScalarDB Clusters access a small coordinator database used for the Consensus Commit protocol. In this sample application, for ease of setup and explanation, the coordinator database is co-located in the same Cassandra instance of the Order Service, but of course, the coordinator database can be managed as a separate database. + +Also, application-specific error handling, authentication processing, etc. are omitted in the sample application since it focuses on explaining how to use ScalarDB. +For details about handling exceptions in ScalarDB, see [How to handle exceptions](../../two-phase-commit-transactions.mdx#how-to-handle-exceptions). + +::: + +### Service endpoints + +The endpoints defined in the services are as follows: + +- Customer Service + - `getCustomerInfo` + - `payment` + - `prepare` + - `validate` + - `commit` + - `rollback` + - `repayment` + +- Order Service + - `placeOrder` + - `getOrder` + - `getOrders` + +### What you can do in this sample application + +The sample application supports the following types of transactions: + +- Get customer information through the `getCustomerInfo` endpoint of the Customer Service. +- Place an order by using a line of credit through the `placeOrder` endpoint of the Order Service and the `payment`, `prepare`, `validate`, `commit`, and `rollback` endpoints of the Customer Service. + - Checks if the cost of the order is below the customer's credit limit. + - If the check passes, records the order history and updates the amount the customer has spent. +- Get order information by order ID through the `getOrder` endpoint of the Order Service and the `getCustomerInfo`, `prepare`, `validate`, `commit`, and `rollback` endpoints of the Customer Service. +- Get order information by customer ID through the `getOrders` endpoint of the Order Service and the `getCustomerInfo`, `prepare`, `validate`, `commit`, and `rollback` endpoints of the Customer Service. +- Make a payment through the `repayment` endpoint of the Customer Service. + - Reduces the amount the customer has spent. + +:::note + +The `getCustomerInfo` endpoint works as a participant service endpoint when receiving a transaction ID from the coordinator. + +::: + +## Configuration for ScalarDB Cluster + +[The configuration for ScalarDB Cluster for the Customer Service](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/scalardb-cluster-node-for-customer-service.properties) is as follows: + +```properties +scalar.db.storage=multi-storage +scalar.db.multi_storage.storages=cassandra,mysql +scalar.db.multi_storage.storages.cassandra.storage=cassandra +scalar.db.multi_storage.storages.cassandra.contact_points=cassandra-1 +scalar.db.multi_storage.storages.cassandra.username=cassandra +scalar.db.multi_storage.storages.cassandra.password=cassandra +scalar.db.multi_storage.storages.mysql.storage=jdbc +scalar.db.multi_storage.storages.mysql.contact_points=jdbc:mysql://mysql-1:3306/ +scalar.db.multi_storage.storages.mysql.username=root +scalar.db.multi_storage.storages.mysql.password=mysql +scalar.db.multi_storage.namespace_mapping=customer_service:mysql,coordinator:cassandra +scalar.db.multi_storage.default_storage=mysql +scalar.db.consensus_commit.isolation_level=SERIALIZABLE + +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.sql.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +- `scalar.db.sql.connection_mode`: This configuration decides how to connect to ScalarDB. +- `scalar.db.storage`: Specifying `multi-storage` is necessary to use Multi-storage Transactions in ScalarDB. +- `scalar.db.multi_storage.storages`: Your storage names must be defined here. +- `scalar.db.multi_storage.storages.cassandra.*`: These configurations are for the `cassandra` storage, which is one of the storage names defined in `scalar.db.multi_storage.storages`. You can configure all the `scalar.db.*` properties for the `cassandra` storage here. +- `scalar.db.multi_storage.storages.mysql.*`: These configurations are for the `mysql` storage, which is one of the storage names defined in `scalar.db.multi_storage.storages`. You can configure all the `scalar.db.*` properties for the `mysql` storage here. +- `scalar.db.multi_storage.namespace_mapping`: This configuration maps the namespaces to the storage. In this sample application, operations for `customer_service` namespace tables are mapped to the `mysql` storage and operations for `order_service` namespace tables are mapped to the `cassandra` storage. You can also define which storage is mapped for the `coordinator` namespace that is used in Consensus Commit transactions. +- `scalar.db.multi_storage.default_storage`: This configuration sets the default storage that is used for operations on unmapped namespace tables. +- `scalar.db.sql.default_transaction_mode`: Specifying `two_phase_commit_transaction` is necessary to use Two-Phase Commit Transactions mode in ScalarDB. +- `scalar.db.consensus_commit.isolation_level`: This configuration decides the isolation level used for ConsensusCommit. + +For details, see [Multi-Storage Transactions](../../multi-storage-transactions.mdx). + +[The configuration for ScalarDB Cluster for the Order Service](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/scalardb-cluster-node-for-order-service.properties) is as follows: + +```properties +scalar.db.storage=cassandra +scalar.db.contact_points=cassandra-1 +scalar.db.username=cassandra +scalar.db.password=cassandra +scalar.db.consensus_commit.isolation_level=SERIALIZABLE + +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.sql.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +- `scalar.db.storage`: `cassandra` is specified since this servcise uses only Cassandra as an underlying database. +- `scalar.db.contact_points`: This configuration specifies the contact points (e.g., host) for connecting to Cassandra. +- `scalar.db.username`: This configuration specifies the username for connecting to Cassandra. +- `scalar.db.password`: This configuration specifies the password for connecting to Cassandra. +- `scalar.db.sql.default_namespace_name`: This configuration sets the default namespace to `order_service`, eliminating the need for the application to specify namespaces. +- `scalar.db.sql.default_transaction_mode`: Specifying `two_phase_commit_transaction` is necessary to use Two-Phase Commit Transactions mode in ScalarDB. +- `scalar.db.consensus_commit.isolation_level`: This configuration decides the isolation level used for ConsensusCommit. + +In this sample application, the ScalarDB Clusters are running in standalone mode (`scalar.db.cluster.node.standalone_mode.enabled=true`). + +Also, you need to set the license key (trial license or commercial license) for the ScalarDB Clusters in the configuration file. For details, see [How to Configure a Product License Key](../../scalar-licensing/index.mdx). + +## Setup + +### Clone the ScalarDB samples repository + +Open Terminal, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory with this sample by running the following command: + +```console +cd scalardb-samples/spring-data-microservice-transaction-sample +``` + +### Set the license key + +Set the license key (trial license or commercial license) for the ScalarDB Clusters in the configuration files [`scalardb-cluster-node-for-customer-service.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/scalardb-cluster-node-for-customer-service.properties) and [`scalardb-cluster-node-for-order-service.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/scalardb-cluster-node-for-order-service.properties). For details, see [How to Configure a Product License Key](../../scalar-licensing/index.mdx). + +### Start Cassandra, MySQL, and ScalarDB Clusters + +To start Cassandra, MySQL, and ScalarDB Clusters, you need to run the following `docker-compose` command: + +```console +docker-compose up -d cassandra mysql scalardb-cluster-node-for-customer-service scalardb-cluster-node-for-order-service +``` + +:::note + +You will need to wait more than one minute for the containers to be fully started. + +::: + +### Load schema + +The database schema (the method in which the data will be organized) for the sample application has already been defined in [`schema-for-customer-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-customer-service.sql) for the Customer Service and [`schema-for-order-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-order-service.sql) for the Order Service. + +To apply the schema, go to the [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) page and download the SQL CLI tool that matches the version of ScalarDB that you want to use. + +#### MySQL + +To load the schema for [`schema-for-customer-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-customer-service.sql) into MySQL, run the following command, replacing `` with the version of the ScalarDB Schema Loader that you downloaded: + +```console +java -jar scalardb-cluster-sql-cli--all.jar --config scalardb-cluster-node-for-customer-service-client.properties --file schema-for-customer-service.sql +``` + +#### Cassandra + +To load the schema for [`schema-for-order-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-order-service.sql) into Cassandra, run the following command, replacing `` with the version of the ScalarDB Schema Loader that you downloaded: + +```console +java -jar scalardb-cluster-sql-cli--all.jar --config scalardb-cluster-node-for-order-service-client.properties --file schema-for-order-service.sql +``` + +#### Schema details + +As shown in [`schema-for-customer-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-customer-service.sql), all the tables for the Customer Service are created in the `customer_service` namespace. + +- `customer_service.customers`: a table that manages customers' information + - `credit_limit`: the maximum amount of money a lender will allow each customer to spend when using a line of credit + - `credit_total`: the amount of money that each customer has already spent by using their line of credit + +As shown in [`schema-for-order-service.sql`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/schema-for-order-service.sql), all the tables for the Order Service are created in the `order_service` namespace. + +- `order_service.orders`: a table that manages order information +- `order_service.statements`: a table that manages order statement information +- `order_service.items`: a table that manages information of items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/ERD.png) + +### Start Microservices + +First, you need to build the docker images of the sample application with the following command: + +```console +./gradlew docker +``` + +Then, you can start the microservices with the following `docker-compose` command: + +```console +docker-compose up -d customer-service order-service +``` + +### Initial data + +When the microservices start, the initial data is loaded automatically. + +After the initial data has loaded, the following records should be stored in the tables: + +- For the `customer_service.customers` table: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +- For the `order_service.items` table: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Run the sample application + +Let's start with getting information about the customer whose ID is `1`: + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000} +... +``` + +At this time, `credit_total` isn't shown, which means the current value of `credit_total` is `0`. + +Then, place an order for three apples and two oranges by using customer ID `1`. +Note that the order format is `:,:,...`: + +```console +./gradlew :client:run --args="PlaceOrder 1 1:3,2:2" +... +{"order_id": "415a453b-cfee-4c48-b8f6-d103d3e10bdb"} +... +``` + +You can see that running this command shows the order ID. + +Let's check the details of the order by using the order ID: + +```console +./gradlew :client:run --args="GetOrder 415a453b-cfee-4c48-b8f6-d103d3e10bdb" +... +{"order": {"order_id": "415a453b-cfee-4c48-b8f6-d103d3e10bdb","timestamp": 1686555272435,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": $ +,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}} +... +``` + +Then, let's place another order and get the order history of customer ID `1`: + +```console +./gradlew :client:run --args="PlaceOrder 1 5:1" +... +{"order_id": "069be075-98f7-428c-b2e0-6820693fc41b"} +... +./gradlew :client:run --args="GetOrders 1" +... +{"order": [{"order_id": "069be075-98f7-428c-b2e0-6820693fc41b","timestamp": 1686555279366,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 5,"item_name": "Melon","price": 3000,"count": 1,"total": 3000}],"total": 3000},{"order_id": "415a453b-cfee-4c48-b8f6-d103d3e10bdb","timestamp": 1686555272435,"customer_id": 1,"customer_name": "Yamada Taro","statement": [{"item_id": 1,"item_name": "Apple","price": 1000,"count": 3,"total": 3000},{"item_id": 2,"item_name": "Orange","price": 2000,"count": 2,"total": 4000}],"total": 7000}]} +... +``` + +This order history is shown in descending order by timestamp. + +The customer's current `credit_total` is `10000`. +Since the customer has now reached their `credit_limit`, which was shown when retrieving their information, they cannot place anymore orders. + +```console +./gradlew :client:run --args="GetCustomerInfo 1" +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000,"credit_total": 10000} +... +./gradlew :client:run --args="PlaceOrder 1 3:1,4:1" +... +io.grpc.StatusRuntimeException: FAILED_PRECONDITION: Credit limit exceeded. creditTotal:10000, payment:7500 + at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:271) + at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:252) + at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:165) + at sample.rpc.OrderServiceGrpc$OrderServiceBlockingStub.placeOrder(OrderServiceGrpc.java:296) + at sample.client.command.PlaceOrderCommand.call(PlaceOrderCommand.java:38) + at sample.client.command.PlaceOrderCommand.call(PlaceOrderCommand.java:12) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.client.Client.main(Client.java:39) +... +``` + +After making a payment, the customer will be able to place orders again. + +```console +./gradlew :client:run --args="Repayment 1 8000" +... +./gradlew :client:run --args="GetCustomerInfo 1" +... +{"id": 1,"name": "Yamada Taro","credit_limit": 10000,"credit_total": 2000} +... +./gradlew :client:run --args="PlaceOrder 1 3:1,4:1" +... +{"order_id": "b6adabd8-0a05-4109-9618-3420fea3161f"} +... +``` + +## Clean up + +To stop Cassandra, MySQL and the Microservices, run the following command: + +```console +docker-compose down +``` + +## Reference - How the microservice transaction is achieved + +The transactions for placing an order, getting a single order, and getting the history of orders achieve the microservice transaction. This section focuses on how the transactions that span the Customer Service and the Order Service are implemented by placing an order as an example. + +The following sequence diagram shows the transaction for placing an order: + +![Sequence Diagram](images/sequence_diagram.png) + +### 1. Transaction with a two-phase commit interface is started + +When a client sends a request to place an order to the Order Service, `OrderService.placeOrder()` is called, and the microservice transaction starts. + +At first, the Order Service starts a transaction with a two-phase commit interface with `ScalarDbTwoPcRepository.executeTwoPcTransaction()` as follows. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +// Start a two-phase commit interface transaction +TwoPcResult result = orderRepository.executeTwoPcTransaction(txId -> { + ... +}, ...); +``` + +The actions in [CRUD operations are executed](#2-crud-operations-are-executed), [Transaction is committed by using the two-phase commit protocol](#3-transaction-is-committed-by-using-the-two-phase-commit-protocol), and [Error handling](#error-handling) are automatically performed by the API. + +### 2. CRUD operations are executed + +After the transaction with a two-phase commit interface starts, CRUD operations are executed by `ScalarDbTwoPcRepository.executeTwoPcTransaction()`. The Order Service puts the order information in the `order_service.orders` table and the detailed information in the `order_service.statements` table as follows. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +// Put the order info into the `orders` table +orderRepository.insert(order); + +AtomicInteger amount = new AtomicInteger(); +for (ItemOrder itemOrder : request.getItemOrderList()) { + int itemId = itemOrder.getItemId(); + int count = itemOrder.getCount(); + // Retrieve the item info from the `items` table + Optional itemOpt = itemRepository.findById(itemId); + if (!itemOpt.isPresent()) { + String message = "Item not found: " + itemId; + responseObserver.onError( + Status.NOT_FOUND.withDescription(message).asRuntimeException()); + throw new ScalarDbNonTransientException(message); + } + Item item = itemOpt.get(); + + int cost = item.price * count; + // Put the order statement into the `statements` table + statementRepository.insert(new Statement(itemId, orderId, count)); + // Calculate the total amount + amount.addAndGet(cost); +} +``` + +Then, the Order Service calls the `payment` gRPC endpoint of the Customer Service along with the transaction ID. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +customerServiceStub.payment( + PaymentRequest.newBuilder() + .setTransactionId(transactionId) + .setCustomerId(customerId) + .setAmount(amount) + .build()); +``` + +The `payment` endpoint of the Customer Service first joins the transaction with `ScalarDbTwoPcRepository.joinTransactionOnParticipant()` as follows. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +customerRepository.joinTransactionOnParticipant(request.getTransactionId(), ...); +``` + +The endpoint then gets the customer information and checks if the customer's credit total exceeds the credit limit after the payment. If the credit total does not exceed the credit limit, the endpoint updates the customer's credit total. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +Customer customer = getCustomer(responseObserver, request.getCustomerId()); + +int updatedCreditTotal = customer.creditTotal + request.getAmount(); +// Check if the credit total exceeds the credit limit after payment +if (updatedCreditTotal > customer.creditLimit) { + String message = String.format( + "Credit limit exceeded. creditTotal:%d, payment:%d", customer.creditTotal, request.getAmount()); + responseObserver.onError( + Status.FAILED_PRECONDITION.withDescription(message).asRuntimeException()); + throw new ScalarDbNonTransientException(message); +} + +// Reduce `credit_total` for the customer +customerRepository.update(customer.withCreditTotal(updatedCreditTotal)); +``` + +### 3. Transaction is committed by using the two-phase commit protocol + +After the Order Service receives the update that the payment succeeded, the Order Service tries to commit the transaction. + +The `ScalarDbTwoPcRepository.executeTwoPcTransaction()` API, which called on the Order Service, automatically performs preparations, validations, and commits of both the local Order Service and the remote Customer Service. These steps are executed sequentially after the above CRUD operations successfully finish. The implementations to invoke `prepare`, `validate`, and `commit` gRPC endpoints of the Customer Service need to be passed as parameters to the API. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +TwoPcResult result = orderRepository.executeTwoPcTransaction(txId ->{ + ... + }, + + Collections.singletonList( + RemotePrepareCommitPhaseOperations.createSerializable( + this::callPrepareEndpoint, + this::callValidateEndpoint, + this::callCommitEndpoint, + this::callRollbackEndpoint + ) + ) +); +``` + +![Sequence Diagram of High Level 2PC API](images/seq-diagram-high-level-2pc-api.png) + +In the `prepare` endpoint of the Customer Service, the endpoint resumes and prepares the transaction by using `ScalarDbTwoPcRepository.prepareTransactionOnParticipant()`. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +customerRepository.prepareTransactionOnParticipant(request.getTransactionId()); +``` + +In the `validate` endpoint of the Customer Service, the endpoint resumes and validates the transaction by using `ScalarDbTwoPcRepository.validateTransactionOnParticipant()`. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +customerRepository.validateTransactionOnParticipant(request.getTransactionId()); +``` + +In the `commit` endpoint of the Customer Service, the endpoint resumes and commits the transaction by using `ScalarDbTwoPcRepository.commitTransactionOnParticipant()`. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +customerRepository.commitTransactionOnParticipant(request.getTransactionId()); +``` + +### Error handling + +If an error happens while executing a transaction, `ScalarDbTwoPcRepository.executeTwoPcTransaction()` will automatically roll back the transaction in both the local Order Service and the remote Customer Service. The implementation to invoke the `rollback` gRPC endpoint of the Customer Service also needs to be passed as a parameter to the API with other ones. For reference, see [`OrderService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java). + +```java +TwoPcResult result = orderRepository.executeTwoPcTransaction(txId ->{ + ... + }, + + Collections.singletonList( + RemotePrepareCommitPhaseOperations.createSerializable( + this::callPrepareEndpoint, + this::callValidateEndpoint, + this::callCommitEndpoint, + this::callRollbackEndpoint + ) + ) +); +``` + +In the `rollback` endpoint of the Customer Service, the endpoint resumes and rolls back the transaction. For reference, see [`CustomerService.java`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java). + +```java +customerRepository.rollbackTransactionOnParticipant(request.getTransactionId()); +``` + +For details about how to handle exceptions in ScalarDB, see [How to handle exceptions](../../two-phase-commit-transactions.mdx#how-to-handle-exceptions). diff --git a/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/ERD.png b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/ERD.png new file mode 100644 index 00000000..c0468efa Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/ERD.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/overview.png b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/overview.png new file mode 100644 index 00000000..223c8ad7 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/overview.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/seq-diagram-high-level-2pc-api.png b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/seq-diagram-high-level-2pc-api.png new file mode 100644 index 00000000..724e52b5 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/seq-diagram-high-level-2pc-api.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/sequence_diagram.png b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/sequence_diagram.png new file mode 100644 index 00000000..0317b5f3 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/spring-data-microservice-transaction-sample/images/sequence_diagram.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx b/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx new file mode 100644 index 00000000..f5f29cac --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx @@ -0,0 +1,333 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Sample application of Spring Data JDBC for ScalarDB with Multi-storage Transactions + +import WarningLicenseKeyContact from '/src/components/en-us/_warning-license-key-contact.mdx'; + +This tutorial describes how to create a sample Spring Boot application by using Spring Data JDBC for ScalarDB with Multi-storage Transactions. + +## Prerequisites for this sample application + +- OpenJDK LTS version (8, 11, 17, or 21) from [Eclipse Temurin](https://adoptium.net/temurin/releases/) +- [Docker](https://www.docker.com/get-started/) 20.10 or later with [Docker Compose](https://docs.docker.com/compose/install/) V2 or later + +:::note + +This sample application has been tested with OpenJDK from Eclipse Temurin. ScalarDB itself, however, has been tested with JDK distributions from various vendors. For details about the requirements for ScalarDB, including compatible JDK distributions, please see [Requirements](../../requirements.mdx). + +::: + + + +## Sample application + +### Overview + +This tutorial illustrates the process of creating a sample e-commerce application, where items can be ordered and paid for with a line of credit by using the [multi-storage transactions](../../multi-storage-transactions.mdx) feature in ScalarDB. + +:::note + +Application-specific error handling, authentication processing, etc. are omitted in the sample application since this tutorial focuses on explaining how to use Spring Data JDBC for ScalarDB with multi-storage transactions. + +For details, see [Guide of Spring Data JDBC for ScalarDB](../../scalardb-sql/spring-data-guide.mdx). + +::: + +![Overview](images/overview.png) + +The application accesses the databases through ScalarDB Cluster. + +### Schema + +[The schema](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-multi-storage-transaction-sample/schema.sql) is as follows: + +```sql +CREATE COORDINATOR TABLES IF NOT EXIST; + +CREATE NAMESPACE IF NOT EXISTS customer; + +CREATE TABLE IF NOT EXISTS customer.customers ( + customer_id INT PRIMARY KEY, + name TEXT, + credit_limit INT, + credit_total INT +); + +CREATE NAMESPACE IF NOT EXISTS "order"; + +CREATE TABLE IF NOT EXISTS "order".orders ( + customer_id INT, + timestamp BIGINT, + order_id TEXT, + PRIMARY KEY (customer_id, timestamp) +); + +CREATE INDEX IF NOT EXISTS ON "order".orders (order_id); + +CREATE TABLE IF NOT EXISTS "order".statements ( + order_id TEXT, + item_id INT, + count INT, + PRIMARY KEY (order_id, item_id) +); + +CREATE TABLE IF NOT EXISTS "order".items ( + item_id INT PRIMARY KEY, + name TEXT, + price INT +); +``` + +All the tables are created in the `customer` and `order` namespaces. + +- `customer.customers`: a table that manages customers' information + - `credit_limit`: the maximum amount of money a lender will allow each customer to spend when using a credit card + - `credit_total`: the amount of money that each customer has already spent by using the credit card +- `order.orders`: a table that manages order information +- `order.statements`: a table that manages order statement information +- `order.items`: a table that manages information of items to be ordered + +The Entity Relationship Diagram for the schema is as follows: + +![ERD](images/ERD.png) + +### Transactions + +The following five transactions are implemented in this sample application: + +1. Getting customer information +2. Placing an order by credit card (checks if the cost of the order is below the credit limit, then records order history and updates the `credit_total` if the check passes) +3. Getting order information by order ID +4. Getting order information by customer ID +5. Repayment (reduces the amount in the `credit_total`) + +## Configuration for ScalarDB Cluster + +[The configuration for ScalarDB Cluster](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-multi-storage-transaction-sample/scalardb-cluster-node.properties) are as follows: + +```properties +scalar.db.storage=multi-storage +scalar.db.multi_storage.storages=cassandra,mysql +scalar.db.multi_storage.storages.cassandra.storage=cassandra +scalar.db.multi_storage.storages.cassandra.contact_points=cassandra-1 +scalar.db.multi_storage.storages.cassandra.username=cassandra +scalar.db.multi_storage.storages.cassandra.password=cassandra +scalar.db.multi_storage.storages.mysql.storage=jdbc +scalar.db.multi_storage.storages.mysql.contact_points=jdbc:mysql://mysql-1:3306/ +scalar.db.multi_storage.storages.mysql.username=root +scalar.db.multi_storage.storages.mysql.password=mysql +scalar.db.multi_storage.namespace_mapping=customer:mysql,order:cassandra,coordinator:cassandra +scalar.db.multi_storage.default_storage=cassandra + +scalar.db.cluster.node.standalone_mode.enabled=true +scalar.db.sql.enabled=true + +# License key configurations +scalar.db.cluster.node.licensing.license_key= +scalar.db.cluster.node.licensing.license_check_cert_pem= +``` + +- `scalar.db.storage`: Specifying `multi-storage` is necessary to use Multi-storage Transactions in ScalarDB. +- `scalar.db.multi_storage.storages`: Your storage names must be defined here. +- `scalar.db.multi_storage.storages.cassandra.*`: These configurations are for the `cassandra` storage, which is one of the storage names defined in `scalar.db.multi_storage.storages`. You can configure all the `scalar.db.*` properties for the `cassandra` storage here. +- `scalar.db.multi_storage.storages.mysql.*`: These configurations are for the `mysql` storage, which is one of the storage names defined in `scalar.db.multi_storage.storages`. You can configure all the `scalar.db.*` properties for the `mysql` storage here. +- `scalar.db.multi_storage.namespace_mapping`: This configuration maps the namespaces to the storage. In this sample application, operations for `customer` namespace tables are mapped to the `mysql` storage and operations for `order` namespace tables are mapped to the `cassandra` storage. You can also define which storage is mapped for the `coordinator` namespace that is used in Consensus Commit transactions. +- `scalar.db.multi_storage.default_storage`: This configuration sets the default storage that is used for operations on unmapped namespace tables. + +For details, see [Multi-Storage Transactions](../../multi-storage-transactions.mdx). + +In this sample application, ScalarDB Cluster is running in standalone mode (`scalar.db.cluster.node.standalone_mode.enabled=true`). + +Also, you need to set the license key (trial license or commercial license) for ScalarDB Cluster in the configuration file. For details, see [How to Configure a Product License Key](../../scalar-licensing/index.mdx). + +## Client Configuration + +[The client configuration](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-multi-storage-transaction-sample/scalardb-sql.properties) is as follows: + +```properties +scalar.db.sql.connection_mode=cluster +scalar.db.sql.cluster_mode.contact_points=indirect:localhost +``` + +## Setup + +### Clone the ScalarDB samples repository + +Open Terminal, then clone the ScalarDB samples repository by running the following command: + +```console +git clone https://github.com/scalar-labs/scalardb-samples +``` + +Then, go to the directory with this sample by running the following command: + +```console +cd scalardb-samples/spring-data-multi-storage-transaction-sample +``` + +### Set the license key + +Set the license key (trial license or commercial license) for the ScalarDB Clusters in the configuration file [`scalardb-cluster-node.properties`](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-multi-storage-transaction-sample/scalardb-cluster-node.properties). For details, see [How to Configure a Product License Key](../../scalar-licensing/index.mdx). + +### Start Cassandra, MySQL, and ScalarDB Cluster + +To start Cassandra, MySQL, and ScalarDB Cluster, you need to run the following `docker-compose` command: + +```console +docker-compose up -d +``` + +Please note that starting the containers may take more than one minute. + +### Load schema + +You then need to apply the schema with the following command. +To download the SQL CLI tool, `scalardb-cluster-sql-cli--all.jar`, see the [Releases](https://github.com/scalar-labs/scalardb/releases) of ScalarDB and download the version that you want to use. + +```console +java -jar scalardb-cluster-sql-cli--all.jar --config scalardb-sql.properties --file schema.sql +``` + +### Load initial data + +After the containers have started, you need to load the initial data by running the following command: + +```console +./gradlew run --args="LoadInitialData" +``` + +After the initial data has loaded, the following records should be stored in the tables: + +- For the `customer.customers` table: + +| customer_id | name | credit_limit | credit_total | +|-------------|---------------|--------------|--------------| +| 1 | Yamada Taro | 10000 | 0 | +| 2 | Yamada Hanako | 10000 | 0 | +| 3 | Suzuki Ichiro | 10000 | 0 | + +- For the `order.items` table: + +| item_id | name | price | +|---------|--------|-------| +| 1 | Apple | 1000 | +| 2 | Orange | 2000 | +| 3 | Grape | 2500 | +| 4 | Mango | 5000 | +| 5 | Melon | 3000 | + +## Run the sample application + +Let's start with getting information about the customer whose ID is `1`: + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":0} +... +``` + +Then, place an order for three apples and two oranges by using customer ID `1`. Note that the order format is `:,:,...`: + +```console +./gradlew run --args="PlaceOrder 1 1:3,2:2" +... +{"order_id":"5d49eb62-fcb9-4dd2-9ae5-e714d989937f","customer_id":1,"timestamp":1677564659810} +... +``` + +You can see that running this command shows the order ID. + +Let's check the details of the order by using the order ID: + +```console +./gradlew run --args="GetOrder 5d49eb62-fcb9-4dd2-9ae5-e714d989937f" +... +{"order_id":"5d49eb62-fcb9-4dd2-9ae5-e714d989937f","timestamp":1677564659810,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":1,"item_name":"Apple","price":1000,"count":3,"total":3000},{"item_id":2,"item_name":"Orange","price":2000,"count":2,"total":4000}],"total":7000} +... +``` + +Then, let's place another order and get the order history of customer ID `1`: + +```console +./gradlew run --args="PlaceOrder 1 5:1" +... +{"order_id":"ccd97d75-ee57-4393-a0bb-5230c4a8c68a","customer_id":1,"timestamp":1677564776069} +... +./gradlew run --args="GetOrders 1" +... +[{"order_id":"ccd97d75-ee57-4393-a0bb-5230c4a8c68a","timestamp":1677564776069,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":5,"item_name":"Melon","price":3000,"count":1,"total":3000}],"total":3000},{"order_id":"5d49eb62-fcb9-4dd2-9ae5-e714d989937f","timestamp":1677564659810,"customer_id":1,"customer_name":"Yamada Taro","statements":[{"item_id":1,"item_name":"Apple","price":1000,"count":3,"total":3000},{"item_id":2,"item_name":"Orange","price":2000,"count":2,"total":4000}],"total":7000}] +... +``` + +This order history is shown in descending order by timestamp. + +The customer's current `credit_total` is `10000`. Since the customer has now reached their `credit_limit`, which was shown when retrieving their information, they cannot place anymore orders. + +```console +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":10000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +java.lang.RuntimeException: Credit limit exceeded. limit:10000, total:17500 + at sample.SampleService.placeOrder(SampleService.java:102) + at sample.SampleService$$FastClassBySpringCGLIB$$1123c447.invoke() + at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793) + at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) + at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) + at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) + at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) + at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) + at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) + at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708) + at sample.SampleService$$EnhancerBySpringCGLIB$$1cb0cc8c.placeOrder() + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:37) + at sample.command.PlaceOrderCommand.call(PlaceOrderCommand.java:13) + at picocli.CommandLine.executeUserObject(CommandLine.java:2041) + at picocli.CommandLine.access$1500(CommandLine.java:148) + at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2461) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2453) + at picocli.CommandLine$RunLast.handle(CommandLine.java:2415) + at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2273) + at picocli.CommandLine$RunLast.execute(CommandLine.java:2417) + at picocli.CommandLine.execute(CommandLine.java:2170) + at sample.SampleApp.run(SampleApp.java:26) + at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:768) + at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:752) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) + at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) + at sample.SampleApp.main(SampleApp.java:35) +... +``` + +After making a payment, the customer will be able to place orders again. + +```console +./gradlew run --args="Repayment 1 8000" +... +./gradlew run --args="GetCustomerInfo 1" +... +{"customer_id":1,"name":"Yamada Taro","credit_limit":10000,"credit_total":2000} +... +./gradlew run --args="PlaceOrder 1 3:1,4:1" +... +{"order_id":"3ac4a1bf-a724-4f26-b948-9f03281a971e","customer_id":1,"timestamp":1677565028204} +... +``` + +## Cleanup + +To stop Cassandra, MySQL, and ScalarDB Cluster, run the following command: + +```console +docker-compose down +``` diff --git a/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/ERD.png b/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/ERD.png new file mode 100644 index 00000000..02100437 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/ERD.png differ diff --git a/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/overview.png b/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/overview.png new file mode 100644 index 00000000..360b26c6 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-samples/spring-data-multi-storage-transaction-sample/images/overview.png differ diff --git a/versioned_docs/version-3.15/scalardb-sql/grammar.mdx b/versioned_docs/version-3.15/scalardb-sql/grammar.mdx new file mode 100644 index 00000000..c7d5045f --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-sql/grammar.mdx @@ -0,0 +1,2479 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB SQL Grammar + +- DDL + - [CREATE NAMESPACE](#create-namespace) + - [CREATE TABLE](#create-table) + - [CREATE INDEX](#create-index) + - [TRUNCATE TABLE](#truncate-table) + - [DROP INDEX](#drop-index) + - [DROP TABLE](#drop-table) + - [DROP NAMESPACE](#drop-namespace) + - [CREATE COORDINATOR TABLES](#create-coordinator-tables) + - [TRUNCATE COORDINATOR TABLES](#truncate-coordinator-tables) + - [DROP COORDINATOR TABLES](#drop-coordinator-tables) + - [ALTER TABLE](#alter-table) +- DML + - [SELECT](#select) + - [INSERT](#insert) + - [UPSERT](#upsert) + - [UPDATE](#update) + - [DELETE](#delete) +- DCL + - [CREATE USER](#create-user) + - [ALTER USER](#alter-user) + - [DROP USER](#drop-user) + - [GRANT](#grant) + - [REVOKE](#revoke) +- Others + - [USE](#use) + - [BEGIN](#begin) + - [START TRANSACTION](#start-transaction) + - [JOIN](#join) + - [PREPARE](#prepare) + - [VALIDATE](#validate) + - [COMMIT](#commit) + - [ROLLBACK](#rollback) + - [ABORT](#abort) + - [SET MODE](#set-mode) + - [SHOW NAMESPACES](#show-namespaces) + - [SHOW TABLES](#show-tables) + - [DESCRIBE](#describe) + - [SUSPEND](#suspend) + - [RESUME](#resume) + - [SHOW USERS](#show-users) + - [SHOW GRANTS](#show-grants) +- Literal + - [Text](#text) + - [Numeric](#numeric) + - [Date and time](#date-and-time) + +## DDL + +### CREATE NAMESPACE + +Before creating tables, namespaces must be created since a table belongs to one namespace. +The `CREATE NAMESPACE` command creates a namespace. + +#### Grammar + +```sql +CREATE NAMESPACE [IF NOT EXISTS] [WITH creation_options] + +creation_options:
( + data_type PRIMARY KEY, + data_type, + ... +) [WITH creation_options] + +data_type: BOOLEAN | INT | BIGINT | FLOAT | DOUBLE | TEXT | BLOB | DATE | TIME | TIMESTAMP | TIMESTAMPTZ +creation_options:
( + data_type, + data_type, + ..., + data_type [ENCRYPTED], + ..., + PRIMARY KEY (, [, ] ...) +) [WITH [clustering_order_definition [AND creation_options]] | creation_options] + +clustering_order_definition: CLUSTERING ORDER BY ( [clustering_order] [, [clustering_order]] ...) +clustering_order: ASC | DESC +``` + +- If you omit `clustering_order`, the default clustering order `ASC` will be used. + +Create a table with a primary key that is composed of multiple partition key columns and multiple clustering key columns: +```sql +CREATE TABLE [IF NOT EXISTS] [.]
( + data_type, + ..., + data_type, + ..., + data_type [ENCRYPTED], + data_type [ENCRYPTED], + ..., + PRIMARY KEY (( [, ] ...), [, ] ...) +) [WITH [clustering_order_definition [AND creation_options]] | creation_options] +``` + +#### Examples + +Examples of `CREATE TABLE` are as follows: + +```sql +-- Create a table with a primary key ("c1") and creation options +CREATE TABLE ns.tbl ( + c1 INT PRIMARY KEY, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN +) WITH 'option1' = 'value1' AND 'option2' = 'value2' AND 'option3' = 'value3'; + +-- Create a table with a partition key ("c1") and a clustering key ("c2" and "c3") with clustering order definition only if it does not already exist +CREATE TABLE IF NOT EXISTS tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY (c1, c2, c3) +) WITH CLUSTERING ORDER BY (c2 DESC, c3 ASC); + +-- Create a table with a partition key ("c1", "c2") and a clustering key ("c3" and "c4") with clustering order definition and creation options +CREATE TABLE ns.tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY ((c1, c2), c3, c4) +) WITH CLUSTERING ORDER BY (c3 DESC, c4 ASC) AND 'option1' = 'value1' AND 'option2' = 'value2' AND 'option3' = 'value3'; + +-- Create a table with a primary key ("c1") and encrypted columns ("c2", "c3", "c4", and "c5") +CREATE TABLE ns.tbl ( + c1 INT PRIMARY KEY, + c2 TEXT ENCRYPTED, + c3 FLOAT ENCRYPTED, + c4 BIGINT ENCRYPTED, + c5 BOOLEAN ENCRYPTED +); +``` + +Examples of building statement objects for `CREATE TABLE` are as follows: + +```java +// Create a table with a primary key ("c1") and creation options +CreateTableStatement statement1 = + StatementBuilder.createTable("ns", "tbl") + .withPartitionKey("c1", DataType.INT) + .withColumn("c2", DataType.TEXT) + .withColumn("c3", DataType.FLOAT) + .withColumn("c4", DataType.BIGINT) + .withColumn("c5", DataType.BOOLEAN) + .withOption("option1", "value1") + .withOption("option2", "value2") + .withOption("option3", "value3") + .build(); + +// Create a table with a partition key ("c1") and a clustering key ("c2" and "c3") with clustering order definition +CreateTableStatement statement2 = + StatementBuilder.createTable("tbl") + .ifNotExists() + .withPartitionKey("c1", DataType.INT) + .withClusteringKey("c2", DataType.TEXT) + .withClusteringKey("c3", DataType.FLOAT) + .withColumn("c4", DataType.BIGINT) + .withColumn("c5", DataType.BOOLEAN) + .withClusteringOrder("c2", ClusteringOrder.DESC) + .withClusteringOrder("c3", ClusteringOrder.ASC) + .build(); + +// Create a table with a partition key ("c1", "c2") and a clustering key ("c3" and "c4") with clustering order definition and creation options +CreateTableStatement statement3 = + StatementBuilder.createTable("ns", "tbl") + .withPartitionKey("c1", DataType.INT) + .withPartitionKey("c2", DataType.TEXT) + .withClusteringKey("c3", DataType.FLOAT) + .withClusteringKey("c4", DataType.BIGINT) + .withColumn("c5", DataType.BOOLEAN) + .withClusteringOrder("c3", ClusteringOrder.DESC) + .withClusteringOrder("c4", ClusteringOrder.ASC) + .withOption("option1", "value1") + .withOption("option2", "value2") + .withOption("option3", "value3") + .build(); + +// Create a table with a primary key ("c1") and encrypted columns ("c2", "c3", "c4", and "c5") +CreateTableStatement statement4 = + StatementBuilder.createTable("ns", "tbl") + .withPartitionKey("c1", DataType.INT) + .withColumn("c2", DataType.TEXT, true) + .withColumn("c3", DataType.FLOAT, true) + .withColumn("c4", DataType.BIGINT, true) + .withColumn("c5", DataType.BOOLEAN, true) + .build(); +``` + +### CREATE INDEX + +The `CREATE INDEX` command creates a secondary index on a table. + +:::note + +You cannot create a secondary index on encrypted columns. + +::: + +#### Grammar + +```sql +CREATE INDEX [IF NOT EXISTS] ON [.]
() +``` + +#### Examples + +Examples of `CREATE INDEX` are as follows: + +```sql +-- Create a secondary index on a column "c4" of a table "ns.tbl" +CREATE INDEX ON ns.tbl (c4); + +-- Create a secondary index only if it does not already exist +CREATE INDEX IF NOT EXISTS ON tbl (c4); + +-- Create a secondary index with options +CREATE INDEX ON ns.tbl (c4) WITH 'option1' = 'value1' AND 'option2' = 'value2' AND 'option3' = 'value3'; +``` + +Examples of building statement objects for `CREATE INDEX` are as follows: + +```java +// Create a secondary index on a column "c4" of a table "ns.tbl" +CreateIndexStatement statement1 = + StatementBuilder.createIndex().onTable("ns", "tbl").column("c4").build(); + +// Create a secondary index only if it does not already exist +CreateIndexStatement statement2 = + StatementBuilder.createIndex().ifNotExists().onTable("tbl").column("c4").build(); + +// Create a secondary index with options +CreateIndexStatement statement3 = + StatementBuilder.createIndex() + .onTable("ns", "tbl") + .column("c4") + .withOption("option1", "value1") + .withOption("option2", "value2") + .withOption("option3", "value3") + .build(); +``` + +### TRUNCATE TABLE + +The `TRUNCATE TABLE` command truncates a table. + +#### Grammar + +```sql +TRUNCATE TABLE [.]
+``` + +#### Examples + +Examples of `TRUNCATE TABLE` are as follows: + +```sql +-- Truncate a table "ns.tbl" +TRUNCATE TABLE ns.tbl; +``` + +Examples of building statement objects for `TRUNCATE TABLE` are as follows: + +```java +// Truncate a table "ns.tbl" +TruncateTableStatement statement = StatementBuilder.truncateTable("ns", "tbl").build(); +``` + +### DROP INDEX + +The `DROP INDEX` command drops a secondary index. + +#### Grammar + +```sql +DROP INDEX [IF EXISTS] ON [.]
() +``` + +#### Examples + +Examples of `DROP INDEX` are as follows: + +```sql +-- Drop a secondary index on a column "c4" of a table "ns.tbl" +DROP INDEX ON ns.tbl (c4); + +-- Drop a secondary index only if it exists +DROP INDEX IF EXISTS ON tbl (c4); +``` + +Examples of building statement objects for `DROP INDEX` are as follows: + +```java +// Drop a secondary index on a column "c4" of a table "ns.tbl" +DropIndexStatement statement1 = + StatementBuilder.dropIndex().onTable("ns", "tbl").column("c4").build(); + +// Drop a secondary index only if it exists +DropIndexStatement statement2 = + StatementBuilder.dropIndex().ifExists().onTable("ns", "tbl").column("c4").build(); +``` + +### DROP TABLE + +The `DROP TABLE` command drops a table. + +#### Grammar + +```sql +DROP TABLE [IF EXISTS] [.]
+``` + +#### Examples + +Examples of `DROP TABLE` are as follows: + +```sql +-- Drop a table "ns.tbl" +DROP TABLE ns.tbl; + +-- Drop a table only if it exists +DROP TABLE IF EXISTS tbl; +``` + +Examples of building statement objects for `DROP TABLE` are as follows: + +```java +// Drop a table "ns.tbl" +DropTableStatement statement1 = StatementBuilder.dropTable("ns", "tbl").build(); + +// Drop a table only if it exists +DropTableStatement statement2 = StatementBuilder.dropTable("ns", "tbl").ifExists().build(); +``` + +### DROP NAMESPACE + +The `DROP NAMESPACE` command drops a namespace. + +#### Grammar + +```sql +DROP NAMESPACE [IF EXISTS] [CASCADE] +``` + +#### Examples + +Examples of `DROP NAMESPACE` are as follows: + +```sql +-- Drop a namespace "ns" +DROP NAMESPACE ns; + +-- Drop a namespace only if it exists +DROP NAMESPACE IF EXISTS ns; + +-- Drop a namespace with cascade +DROP NAMESPACE ns CASCADE; +``` + +Examples of building statement objects for `DROP NAMESPACE` are as follows: + +```java +// Drop a namespace "ns" +DropNamespaceStatement statement1 = StatementBuilder.dropNamespace("ns").build(); + +// Drop a namespace only if it exists +DropNamespaceStatement statement2 = StatementBuilder.dropNamespace("ns").ifExists().build(); + +// Drop a namespace with cascade +DropNamespaceStatement statement3 = StatementBuilder.dropNamespace("ns").cascade().build(); +``` + +### CREATE COORDINATOR TABLES + +The `CREATE COORDINATOR TABLES` command creates coordinator tables. + +#### Grammar + +```sql +CREATE COORDINATOR TABLES [IF NOT {EXIST|EXISTS}] [WITH creation_options] + +creation_options:
ADD [COLUMN] data_type [ENCRYPTED] + +data_type: BOOLEAN | INT | BIGINT | FLOAT | DOUBLE | TEXT | BLOB | DATE | TIME | TIMESTAMP | TIMESTAMPTZ +``` + +- You can specify `ENCRYPTED` for the column to encrypt the data in that column. + +#### Examples + +Examples of `ALTER TABLE` are as follows: + +```sql +-- Add a new column "new_col" to "ns.tbl" +ALTER TABLE ns.tbl ADD COLUMN new_col INT; + +-- Add a new encrypted column "new_col" to "ns.tbl" +ALTER TABLE ns.tbl ADD COLUMN new_col TEXT ENCRYPTED; +``` + +Examples of building statement objects for `ALTER TABLE` are as follows: + +```java +// Add a new column "new_col" to "ns.tbl" +AlterTableAddColumnStatement statement = + StatementBuilder.alterTable("ns", "tbl").addColumn("new_col", DataType.INT).build(); + +// Add a new encrypted column "new_col" to "ns.tbl" +AlterTableAddColumnStatement statement = + StatementBuilder.alterTable("ns", "tbl").addColumn("new_col", DataType.TEXT, true).build(); +``` + +## DML + +### SELECT + +The `SELECT` command retrieves records from the database. ScalarDB SQL creates an execution plan for a `SELECT` command by using one of the `Get`, partition `Scan`, and cross-partition `Scan` operations in ScalarDB to retrieve records from the database. For the best results, specify primary key columns uniquely as much as possible in the `WHERE` clause to avoid using the cross-partition scan since it might cause performance and consistency issues, especially in non-JDBC databases. See the following rules for selecting operations. The former ones are prior to the latter ones and more efficient. [ScalarDB data model](../data-modeling.mdx) also helps in understanding the best practices for modeling and accessing data. + +1. If you fully specify the primary-key columns in the `WHERE` clause, the `SELECT` command will use a `Get` operation for a single record in a single partition. +2. If you fully specify the partition key and properly specify the clustering key and order in the `WHERE` and `ORDER BY` clauses, the `SELECT` command will use a `Scan` operation for records in a single partition. For more details, see the [Examples of partition scans and index scans](#examples-of-partition-scans-and-index-scans). +3. If you specify the indexed column value literal with the `equal to` (`=`) operator in the `WHERE` clause without the `ORDER BY` clause, the `SELECT` command will use an index `Scan` operation. +4. For other cases, the `SELECT` command will be converted to a cross-partition `Scan` operation. + +You need to enable the cross-partition scan option and the cross-partition scan with filtering and ordering options if you want to flexibly retrieve records across partitions with arbitrary conditions and orderings. Currently, the ordering option is available only for JDBC databases. For details about configurations, see [Cross-partition scan configurations](../configurations.mdx#cross-partition-scan-configurations) and [ScalarDB Cluster SQL configurations](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations). + +:::warning + +For non-JDBC databases, transactions could be executed at read-committed snapshot isolation (`SNAPSHOT`), which is a lower isolation level, even if you enable cross-partition scan with the `SERIALIZABLE` isolation level. When using non-JDBC databases, use cross-partition scan only if consistency does not matter for your transactions. + +::: + +#### Grammar + +```sql +SELECT projection [, projection] ... + FROM [.]
[AS ] [join_specification [join_specification] ...] + [WHERE and_predicates [OR and_predicates ...] | or_predicates [AND or_predicates ...]] + [ORDER BY identifier [order] [, identifier [order]] ...] + [LIMIT ] + [WITH operation_attributes] + +projection: * | identifier [AS ] +join_specification: [INNER] JOIN [.]
[AS ] ON join_predicate [AND join_predicate] ... | {LEFT|RIGHT} [OUTER] JOIN [.]
[AS ] ON join_predicate [AND join_predicate] ... +join_predicate: identifier = identifier +and_predicates: predicate | (predicate [AND predicate ...]) +or_predicates: predicate | (predicate [OR predicate ...]) +predicate: identifier operator | identifier BETWEEN AND | identifier [NOT] LIKE [ESCAPE ] | identifier IS [NOT] NULL +identifier: [[.]
.] | [alias.] +operator: = | <> | != | > | >= | < | <= +order: ASC | DESC +operation_attributes: operation_attribute [AND operation_attribute] ... +operation_attribute: = +``` + +##### Note + +`JOIN` clause: + +- For `[INNER] JOIN` and `LEFT [OUTER] JOIN`: + - The `join_predicate`s must include either all primary-key columns or a secondary-index column from the right table. + - The `WHERE` predicates and the `ORDER BY` clause can only include columns from the table specified in the `FROM` clause. +- For `RIGHT [OUTER] JOIN`: + - It must be specified as the first `join_specification`. + - The `join_predicate`s must contain all primary-key columns or a secondary-index column from the left table. + - The `WHERE` predicates and the `ORDER BY` clause can only specify columns from the table specified in the `RIGHT OUTER JOIN` clause. + +`WHERE` clauses: + +- You can use arbitrary predicates for any columns in the `WHERE` clause. +- In the `WHERE` clause, predicates must be an OR-wise of `and_predicates` (known as disjunctive normal form) or an AND-wise of `or_predicates` (known as conjunctive normal form). +- When connecting multiple `and_predicates` or `or_predicates`, which have more than one predicate, you need to put parentheses around `and_predicates` and `or_predicates`. +- You can specify `` to a bind marker (positional `?` and named `:`). See the [Literal](#literal) section for the literal syntax. +- You cannot specify encrypted columns in the `WHERE` clause. + +`LIKE` predicate: + +- `_` in `` matches any single character. +- `%` in `` matches any sequence of zero or more characters. +- `\` in `` works as the escape character by default. + - You can change the escape character by specifying the `ESCAPE` clause. + - You can disable the escape character by specifying an empty escape character, `ESCAPE ''`. + +`ORDER BY` clause: + +- You can specify `order` for any columns in the `ORDER BY` clause. +- If you omit `order`, the default order `ASC` will be used. +- You cannot specify encrypted columns in the `ORDER BY` clause. + +`LIMIT` clause: + +- You can specify `` to a bind marker (positional `?` and named `:`). + +For details about retrieving data from a database in ScalarDB, see [Get operation](../api-guide.mdx#get-operation) and [Scan operation](../api-guide.mdx#scan-operation). + +#### Examples of partition scans and index scans + +Let's say you have the following table and index: +```sql +CREATE TABLE ns.tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY (c1, c2, c3) +) WITH CLUSTERING ORDER BY (c2 DESC, c3 ASC); + +CREATE INDEX ON ns.tbl (c4); +``` + +Examples of `SELECT` are as follows: + +```sql +-- With a full primary key +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23; + +-- With a full primary key and predicates for non-primary-key columns +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 AND c4 < 100; + +-- With a partial primary key +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa'; + +-- With a partial primary key and predicates for non-primary-key columns +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND (c4 < 100 OR c4 > 500); + +-- With projections and a partition key and clustering-key boundaries +SELECT c1, c2, c3, c5 FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 >= 1.23 AND c3 < 4.56; + +-- With projections and a partition key and clustering-key boundaries and orders and limit +SELECT c1 AS a, c2 AS b, c3 AS c, c5 FROM ns.tbl WHERE c1 = 10 AND c2 > 'aaa' AND c2 <= 'ddd' ORDER BY c2 ASC, c3 DESC LIMIT 10; + +-- With an equality predicate for an indexed column +SELECT * FROM ns.tbl WHERE c4 = 100; + +-- With an equality predicate for an indexed column and predicates for non-primary-key columns +SELECT * FROM ns.tbl WHERE c4 = 100 AND c5 = false; + +-- With projections and an indexed column and limit +SELECT c1, c2, c3, c4 FROM ns.tbl WHERE c4 = 100 LIMIT 10; + +-- With positional bind markers +SELECT * FROM ns.tbl WHERE c1 = ? AND c2 > ? AND c2 <= ? ORDER BY c2 ASC, c3 DESC LIMIT ?; + +-- With operations attributes +SELECT * FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2'; +``` + +Examples of building statement objects for `SELECT` are as follows: + +```java +// With a full primary key +SelectStatement statement1 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .and(Predicate.column("c4").isLessThan(Value.of(100))) + .build(); + +// With a full primary key and predicates for non-primary-key columns +SelectStatement statement1 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c4").isEqualTo(Value.of(1.23F))) + .and(Predicate.column("c4").isLessThan(Value.of(100))) + .build(); + +// With a partial primary key +SelectStatement statement2 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .build(); + +// With a partial primary key and predicates for non-primary-key columns +SelectStatement statement2 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and( + AndPredicateList.predicate(Predicate.column("c4").isLessThan(Value.of(100))) + .and(Predicate.column("c4").isGreaterThan(Value.of(500))) + .build()) + .build(); + +// With projections and a partition key and clustering-key boundaries +SelectStatement statement3 = + StatementBuilder.select("c1", "c2", "c3", "c5") + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isGreaterThanOrEqualTo(Value.of(1.23F))) + .and(Predicate.column("c3").isLessThan(Value.of(4.56F))) + .build(); + +// With projections and a partition key and clustering key boundaries and orders and limit +SelectStatement statement4 = + StatementBuilder.select( + Projection.column("c1").as("a"), + Projection.column("c2").as("b"), + Projection.column("c3").as("c"), + Projection.column("c5").as("d")) + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isGreaterThan(Value.of("aaa"))) + .and(Predicate.column("c2").isLessThanOrEqualTo(Value.of("ddd"))) + .orderBy(Ordering.column("c2").asc(), Ordering.column("c3").desc()) + .limit(10) + .build(); + +// With an equality predicate for an indexed column +SelectStatement statement5 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c4").isEqualTo(Value.of(100))) + .build(); + +// With an equality predicate for an indexed column and predicates for non-primary-key columns +SelectStatement statement5 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c4").isEqualTo(Value.of(100))) + .and(Predicate.column("c5").isEqualTo(Value.of(false))) + .build(); + +// With projections and an indexed column and limit +SelectStatement statement6 = + StatementBuilder.select("c1", "c2", "c3", "c4") + .from("ns", "tbl") + .where(Predicate.column("c4").isEqualTo(Value.of(100))) + .limit(10) + .build(); + +// With positional bind markers +SelectStatement statement7 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c2").isGreaterThan(BindMarker.positional())) + .and(Predicate.column("c2").isLessThanOrEqualTo(BindMarker.positional())) + .orderBy(Ordering.column("c2").asc(), Ordering.column("c3").desc()) + .limit(BindMarker.positional()) + .build(); + +// With operations attributes +SelectStatement statement8 = + StatementBuilder.select() + .from("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .build(); +``` + +Examples of `SELECT` with `JOIN` are as follows: + +```sql +-- For INNER JOIN and LEFT OUTER JOIN: +SELECT * FROM tbl1 as t1 + INNER JOIN tbl2 as t2 on t1.col1=t2.id1 and t1.col2=t2.id2 -- This part must have all primary key columns or a secondary index column of `tbl2`. + WHERE t1.pkey=1 -- Only columns of `tbl1` can be specified here. + ORDER BY t1.ckey DESC; -- Only columns of `tbl1` can be specified here. + +SELECT * FROM tbl1 as t1 + INNER JOIN tbl2 as t2 on t1.col1=t2.id -- This part must have all primary key columns or a secondary index column of `tbl2`. + LEFT OUTER JOIN tbl3 as t3 on t1.col2=t3.id -- This part must have all primary key columns or a secondary index column of `tbl3`. + WHERE t1.pkey=1 -- Only columns of `tbl1` can be specified here. + ORDER BY t1.ckey DESC; -- Only columns of `tbl1` can be specified here. + +-- For RIGHT OUTER JOIN: +SELECT * FROM tbl1 as t1 + RIGHT OUTER JOIN tbl2 as t2 on t1.id=t2.col -- Acceptable as the first join. And this part must have all primary key columns or a secondary index column of `tbl1`. + LEFT OUTER JOIN tbl3 as t3 on t1.col2=t3.id + WHERE t2.pkey=1 -- Only columns of `tbl2` can be specified here. + ORDER BY t2.ckey DESC; -- Only columns of `tbl2` can be specified here. + +SELECT * FROM tbl1 as t1 + RIGHT OUTER JOIN tbl2 as t2 on t1.id1=t2.col1 and t1.id2=t2.col2 -- This part must have all primary key columns or a secondary index column of `tbl1`. + WHERE t2.pkey=1 -- Only columns of `tbl2` can be specified here. + ORDER BY t2.ckey DESC; -- Only columns of `tbl2` can be specified here. +``` + +Examples of building statement objects for `SELECT` with `JOIN` are as follows: + +```java +// For INNER JOIN and LEFT OUTER JOIN: +SelectStatement statement1 = + StatementBuilder.select() + .from("tbl1", "t1") + .innerJoin("tbl2", "t2") + .on(JoinPredicate.column("t1", "col1").isEqualTo("t2", "id1")) + .and(JoinPredicate.column("t1", "col2").isEqualTo("t2", "id2")) // This part must have all primary key columns or a secondary index column of `tbl2`. + .where(Predicate.column("t1", "pkey").isEqualTo(Value.of(1))) // Only columns of `tbl1` can be specified here. + .orderBy(Ordering.column("t1", "ckey").desc()) // Only columns of `tbl1` can be specified here. + .build(); + +SelectStatement statement2 = + StatementBuilder.select() + .from("tbl1", "t1") + .innerJoin("tbl2", "t2") + .on(JoinPredicate.column("t1", "col1").isEqualTo("t2", "id")) // This part must have all primary key columns or a secondary index column of `tbl2`. + .leftOuterJoin("tbl3", "t3") + .on(JoinPredicate.column("t1", "col2").isEqualTo("t3", "id")) // This part must have all primary key columns or a secondary index column of `tbl3`. + .where(Predicate.column("t1", "pkey").isEqualTo(Value.of(1))) // Only columns of `tbl1` can be specified here. + .orderBy(Ordering.column("t1", "ckey").desc()) // Only columns of `tbl1` can be specified here. + .build(); + +// For RIGHT OUTER JOIN: +SelectStatement statement3 = + StatementBuilder.select() + .from("tbl1", "t1") + .rightOuterJoin("tbl2", "t2") + .on(JoinPredicate.column("t1", "id").isEqualTo("t2", "col")) // Acceptable as the first join. And this part must have all primary key columns or a secondary index column of `tbl1`. + .leftOuterJoin("tbl3", "t3") + .on(JoinPredicate.column("t1", "col2").isEqualTo("t3", "id")) + .where(Predicate.column("t2", "pkey").isEqualTo(Value.of(1))) // Only columns of `tbl2` can be specified here. + .orderBy(Ordering.column("t2", "ckey").desc()) // Only columns of `tbl2` can be specified here. + .build(); + +SelectStatement statement4 = + StatementBuilder.select() + .from("tbl1", "t1") + .rightOuterJoin("tbl2", "t2") + .on(JoinPredicate.column("t1", "id1").isEqualTo("t2", "col1")) + .and(JoinPredicate.column("t1", "id2").isEqualTo("t2", "col2")) // This part must have all primary key columns or a secondary index column of `tbl1`. + .where(Predicate.column("t2", "pkey").isEqualTo(Value.of(1))) // Only columns of `tbl2` can be specified here. + .orderBy(Ordering.column("t2", "ckey").desc()) // Only columns of `tbl2` can be specified here. + .build(); +``` + +#### Examples of cross-partition scan + +If you have the following table, for example: + +```sql +CREATE TABLE ns.user ( + id INT, + name TEXT, + age INT, + height FLOAT, + PRIMARY KEY (id) +) +``` + +Examples of `SELECT` with cross-partition scan are as follows: + +```sql +-- Without the WHERE clause to retrieve all the records of a table +SELECT * FROM ns.user; + +-- Without the WHERE clause and with projections and a limit +SELECT id, name FROM ns.user LIMIT 10; + +-- With AND predicates for non-primary-key columns +SELECT * FROM ns.user WHERE age > 10 AND height > 140; + +-- With OR predicates for non-primary key columns +SELECT * FROM ns.user WHERE age > 10 OR height > 140; + +-- With OR-wise of AND predicates +SELECT * FROM ns.user WHERE (age > 10 AND height > 150) OR (age > 15 AND height > 145); + +-- With AND-wise of OR predicates +SELECT * FROM ns.user WHERE (age < 10 OR age > 65) AND (height < 145 OR height > 175); + +-- With LIKE predicates +SELECT * FROM ns.user WHERE name LIKE 'A%' OR name NOT LIKE 'B_b'; + +-- With LIKE predicates with an escape character +SELECT * FROM ns.user WHERE name LIKE '+%Alice' ESCAPE '+'; + +-- With IS NULL predicates +SELECT * FROM ns.user WHERE name IS NOT NULL AND age IS NULL; + +-- With projections +SELECT name, age, height FROM ns.user WHERE (age < 10 OR age > 65) AND age <> 0; + +-- With limit +SELECT name, age, height FROM ns.user WHERE age < 10 OR age > 65 LIMIT 10; + +-- With orderings +SELECT * FROM ns.user WHERE age < 10 ORDER BY height DESC; + +-- With orderings without the WHERE clause +SELECT * FROM ns.user ORDER BY height; + +-- With positional bind markers +SELECT * FROM ns.user WHERE age < ? ORDER BY age ASC, height DESC LIMIT ?; +``` + +For examples that use the `JOIN` clause, see [Examples of partition scans and index scans](#examples-of-partition-scans-and-index-scans). + +Examples of building statement objects for `SELECT` are as follows: + +```java +// Without the WHERE clause to retrieve all the records of a table +SelectStatement statement1 = StatementBuilder.select().from("ns", "user").build(); + +// Without the WHERE clause and with projections and a limit +SelectStatement statement2 = + StatementBuilder.select("id", "name").from("ns", "user").limit(10).build(); + +// With AND predicates for non-primary-key columns +SelectStatement statement2 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR predicates for non-primary key columns +SelectStatement statement3 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .or(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR-wise of AND predicates +SelectStatement statement4 = + StatementBuilder.select() + .from("ns", "user") + .where( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build()) + .or( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(15))) + .and(Predicate.column("height").isGreaterThan(Value.of(145.0F))) + .build()) + .build(); + +// With AND-wise of OR predicates +SelectStatement statement5 = + StatementBuilder.select() + .from("ns", "user") + .where( + OrPredicateList.predicate(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .build()) + .and( + OrPredicateList.predicate(Predicate.column("height").isLessThan(Value.of(145.0F))) + .or(Predicate.column("height").isGreaterThan(Value.of(175.0F))) + .build()) + .build(); + +// With LIKE predicates +SelectStatement statement6 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("name").isLike(Value.of("A%"))) + .or(Predicate.column("name").isNotLike(Value.of("B_b"))) + .build(); + +// With LIKE predicates with an escape character +SelectStatement statement7 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("name").isLike(Value.of("+%Alice"), Value.of("+"))) + .build(); + +// With IS NULL predicates +SelectStatement statement8 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("name").isNotNull()) + .and(Predicate.column("age").isNull()) + .build(); + +// With projections +SelectStatement statement9 = + StatementBuilder.select("name", "age", "height") + .from("ns", "user") + .where( + OrPredicateList.predicate(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .build()) + .and(Predicate.column("height").isNotEqualTo(Value.of(0))) + .build(); + +// With limit +SelectStatement statement10 = + StatementBuilder.select("name", "age", "height") + .from("ns", "user") + .where(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .limit(10) + .build(); + +// With orderings +SelectStatement statement11 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("age").isLessThan(Value.of(10))) + .orderBy(Ordering.column("height").desc()) + .build(); + +// With orderings without the WHERE clause +SelectStatement statement12 = + StatementBuilder.select() + .from("ns", "user") + .orderBy(Ordering.column("height").desc()) + .build(); + +// With positional bind markers +SelectStatement statement13 = + StatementBuilder.select() + .from("ns", "user") + .where(Predicate.column("age").isLessThan(BindMarker.positional())) + .orderBy(Ordering.column("age").asc(), Ordering.column("height").desc()) + .limit(BindMarker.positional()) + .build(); +``` + +For examples that use the `JOIN` clause, see [Examples of partition scans and index scans](#examples-of-partition-scans-and-index-scans). + +### INSERT + +The `INSERT` command inserts new records into the database. If any of the target records already exist, a transaction conflict error will be thrown. + +This command returns the following column: + +- `updateCount`: `INT` - the number of inserted records + +#### Grammar + +```sql +INSERT INTO [.]
[( [, ] ...)] + VALUES ( [, ] ...) [, ( [, ] ...)] ... + [WITH operation_attributes] + +operation_attributes: = [AND =] ... +``` + +- You must specify a full primary key in `INSERT`. +- You can specify `` to a bind marker (positional `?` and named `:`). See the [Literal](#literal) section for the literal syntax. + +#### Examples + +Examples of `INSERT` are as follows: + +```sql +-- Insert a record without specifying column names +INSERT INTO ns.tbl VALUES (10, 'aaa', 1.23, 100, true); + +-- Insert a record with column names +INSERT INTO ns.tbl (c1, c2, c3, c4) VALUES (10, 'aaa', 1.23, 100); + +-- With positional bind markers +INSERT INTO tbl VALUES (?, ?, ?, ?, ?); + +-- Insert multiple records +INSERT INTO ns.tbl (c1, c2, c3, c4) VALUES (10, 'aaa', 1.23, 100), (20, 'bbb', 4.56, 200); +``` + +Examples of building statement objects for `INSERT` are as follows: + +```java +// Insert a record without specifying column names. +InsertStatement statement1 = StatementBuilder.insertInto("ns", "tbl") + .values(Value.ofInt(10), Value.ofText("aaa"), Value.of(1.23F), Value.of(100L), Value.of(true)) + .build(); + +// Insert a record with column names. +InsertStatement statement2 = StatementBuilder.insertInto("ns", "tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values(Value.ofInt(10), Value.ofText("aaa"), Value.of(1.23F), Value.of(100L), Value.of(true)) + .build(); + +// With positional bind markers +InsertStatement statement3 = + StatementBuilder.insertInto("tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values( + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional()) + .build(); + +// Insert multiple records. +InsertStatement statement4 = StatementBuilder.insertInto("ns", "tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values(Value.ofInt(10), Value.ofText("aaa"), Value.of(1.23F), Value.of(100L), Value.of(true)) + .values(Value.ofInt(20), Value.ofText("bbb"), Value.of(2.46F), Value.of(200L), Value.of(false)) + .build(); +``` + +### UPSERT + +The `UPSERT` command inserts new records into the database if they don't exist or updates the target records if they already exist. + +This command returns the following column: + +- `updateCount`: `INT` - the number of inserted or updated records + +#### Grammar + +```sql +UPSERT INTO [.]
[( [, ] ...)] + VALUES ( [, ] ...) [, ( [, ] ...)] ... + [WITH operation_attributes] + +operation_attributes: operation_attribute [AND operation_attribute] ... +operation_attribute: = +``` + +- You must specify a full primary key in `UPSERT`. +- You can specify `` to a bind marker (positional `?` and named `:`). See the [Literal](#literal) section for the literal syntax. + +#### Examples + +Examples of `UPSERT` are as follows: + +```sql +-- Upsert a record without specifying column names. +UPSERT INTO ns.tbl VALUES (10, 'aaa', 1.23, 100, true); + +-- Upsert a record with column names. +UPSERT INTO ns.tbl (c1, c2, c3, c4) VALUES (10, 'aaa', 1.23, 100); + +-- With positional bind markers +UPSERT INTO tbl VALUES (?, ?, ?, ?, ?); + +-- Upsert multiple records. +UPSERT INTO ns.tbl (c1, c2, c3, c4) VALUES (10, 'aaa', 1.23, 100), (20, 'bbb', 4.56, 200); + +-- With operations attributes +UPSERT INTO ns.tbl VALUES (10, 'aaa', 1.23, 100, true) WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2'; +``` + +Examples of building statement objects for `UPSERT` are as follows: + +```java +// Upsert a record without specifying column names. +UpsertStatement statement1 = + StatementBuilder.upsertInto("ns", "tbl") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .build(); + +// Upsert a record with column names. +UpsertStatement statement2 = + StatementBuilder.upsertInto("ns", "tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .build(); + +// With positional bind markers +UpsertStatement statement3 = + StatementBuilder.upsertInto("tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values( + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional(), + BindMarker.positional()) + .build(); + +// Upsert multiple records. +UpsertStatement statement4 = + StatementBuilder.upsertInto("ns", "tbl") + .columns("c1", "c2", "c3", "c4", "c5") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .values( + Value.ofInt(20), + Value.ofText("bbb"), + Value.of(2.46F), + Value.of(200L), + Value.of(false)) + .build(); + +// With operations attributes +UpsertStatement statement5 = + StatementBuilder.upsertInto("ns", "tbl") + .values( + Value.ofInt(10), + Value.ofText("aaa"), + Value.of(1.23F), + Value.of(100L), + Value.of(true)) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .build(); +``` + +### UPDATE + +The `UPDATE` command updates existing records in the database. You can specify any conditions in the `WHERE` clause to filter records. However, specifying a primary key uniquely as much as possible is recommended to avoid the cross-partition operation since it might cause performance and consistency issues, especially in non-JDBC databases. Because ScalarDB SQL creates an execution plan for an `UPDATE` command that uses a `Get` or `Scan` operation to identify the target records, the same rule is applied for the selection of records. To understand what kinds of `WHERE` clauses cause cross-partition operations and to avoid such operations, see [SELECT](#select). + +You need to enable the cross-partition scan option if you want to update all records across partitions without specifying the `WHERE` clause. You also need to enable the cross-partition scan with filtering option if you want to flexibly update records across partitions with arbitrary conditions in the `WHERE` clause. For details about configurations, see [Cross-partition scan configurations](../configurations.mdx#cross-partition-scan-configurations) and [ScalarDB Cluster SQL configurations](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations). + +:::warning + +For non-JDBC databases, transactions could be executed at read-committed snapshot isolation (`SNAPSHOT`), which is a lower isolation level, even if you enable cross-partition scan with the `SERIALIZABLE` isolation level. When using non-JDBC databases, use cross-partition scan only if consistency does not matter for your transactions. + +::: + +This command returns the following column: + +- `updateCount`: `INT` - the number of updated records + +#### Grammar + +```sql +UPDATE [.]
[AS ] + SET = [, = ] ... + [WHERE and_predicates [OR and_predicates ...] | or_predicates [AND or_predicates ...]] + [WITH operation_attributes] + +identifier: [[.]
.] | [alias.] +and_predicates: predicate | (predicate [AND predicate ...]) +or_predicates: predicate | (predicate [OR predicate ...]) +predicate: operator | BETWEEN AND | [NOT] LIKE [ESCAPE ] | IS [NOT] NULL +operator: = | <> | != | > | >= | < | <= +operation_attributes: operation_attribute [AND operation_attribute] ... +operation_attribute: = +``` + +##### Note + +`WHERE` clause: + +- You can use arbitrary predicates for any columns in the `WHERE` clause. +- In the `WHERE` clause, predicates must be an OR-wise of `and_predicates` (known as disjunctive normal form) or an AND-wise of `or_predicates` (known as conjunctive normal form). +- When connecting multiple `and_predicates` or `or_predicates`, which have more than one predicate, you need to put parentheses around `and_predicates` and `or_predicates`. +- You can specify `` to a bind marker (positional `?` and named `:`). See the [Literal](#literal) section for the literal syntax. +- You cannot specify encrypted columns in the `WHERE` clause. + +`LIKE` predicate: + +- `_` in `` matches any single character. +- `%` in `` matches any sequence of zero or more characters. +- `\` in `` works as the escape character by default. + - You can change the escape character by specifying the `ESCAPE` clause. + - You can disable the escape character by specifying an empty escape character, `ESCAPE ''`. + +#### Examples with the full primary key specified + +If you have the following table, for example: + +```sql +CREATE TABLE ns.tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY (c1, c2, c3) +) WITH CLUSTERING ORDER BY (c2 DESC, c3 ASC); +``` + +Examples of `UPDATE` with the full primary key specified are as follows: + +```sql +-- Update a record +UPDATE ns.tbl SET c4 = 200, c5 = false WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23; + +-- With positional bind markers +UPDATE ns.tbl SET c4 = ?, c5 = ? WHERE c1 = ? AND c2 = ? AND c3 = ?; + +-- With operations attributes +UPDATE ns.tbl SET c4 = 200, c5 = false WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2'; +``` + +Examples of building statement objects for `UPDATE` are as follows: + +```java +// Update a record +UpdateStatement statement1 = + StatementBuilder.update("ns", "tbl") + .set( + Assignment.column("c4").value(Value.of(200L)), + Assignment.column("c5").value(Value.of(false))) + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .build(); + +// With positional bind markers +UpdateStatement statement2 = + StatementBuilder.update("tbl") + .set( + Assignment.column("c4").value(BindMarker.positional()), + Assignment.column("c5").value(BindMarker.positional())) + .where(Predicate.column("c1").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c2").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c3").isEqualTo(BindMarker.positional())) + .build(); + +// With operations attributes +UpdateStatement statement3 = + StatementBuilder.update("ns", "tbl") + .set( + Assignment.column("c4").value(Value.of(200L)), + Assignment.column("c5").value(Value.of(false))) + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .build(); +``` + +#### Examples without the full primary key specified + +If you have the following table, for example: + +```sql +CREATE TABLE ns.user ( + id INT, + name TEXT, + age INT, + height FLOAT, + PRIMARY KEY (id) +) +``` + +Examples of `UPDATE` without the full primary key specified are as follows: + +```sql +-- Without the WHERE clause to update all the records of a table +UPDATE ns.user SET age = 31; + +-- With AND predicates for non-primary key columns +UPDATE ns.user SET age = 31 WHERE age > 10 AND height > 140; + +-- With OR predicates for non-primary key columns +UPDATE ns.user SET age = 31 WHERE age > 10 OR height > 140; + +-- With OR-wise of AND predicates +UPDATE ns.user SET age = 31 WHERE (age > 10 AND height > 150) OR (age > 15 AND height > 145); + +-- With AND-wise of OR predicates +UPDATE ns.user SET age = 31 WHERE (age < 10 OR age > 65) AND (height < 145 OR height > 175); + +-- With LIKE predicates +UPDATE ns.user SET age = 31 WHERE name LIKE 'A%' OR name NOT LIKE 'B_b'; + +-- With LIKE predicates with an escape character +UPDATE ns.user SET age = 31 WHERE name LIKE '+%Alice' ESCAPE '+'; + +-- With IS NULL predicates +UPDATE ns.user SET age = 31 WHERE name IS NOT NULL AND age IS NULL; + +-- With positional bind markers +UPDATE ns.user SET age = ? WHERE age < ?; +``` + +Examples of building statement objects for `UPDATE` are as follows: + +```java +// Without the WHERE clause to update all the records of a table +UpdateStatement statement1 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .build(); + +// With AND predicates for non-primary key columns +UpdateStatement statement2 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR predicates for non-primary key columns +UpdateStatement statement3 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .or(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR-wise of AND predicates +UpdateStatement statement4 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build()) + .or( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(15))) + .and(Predicate.column("height").isGreaterThan(Value.of(145.0F))) + .build()) + .build(); + +// With AND-wise of OR predicates +UpdateStatement statement5 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where( + OrPredicateList.predicate(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .build()) + .and( + OrPredicateList.predicate(Predicate.column("height").isLessThan(Value.of(145.0F))) + .or(Predicate.column("height").isGreaterThan(Value.of(175.0F))) + .build()) + .build(); + +// With LIKE predicates +UpdateStatement statement6 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("name").isLike(Value.of("A%"))) + .or(Predicate.column("name").isNotLike(Value.of("B_b"))) + .build(); + +// With LIKE predicates with an escape character +UpdateStatement statement7 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("name").isLike(Value.of("+%Alice"), Value.of("+"))) + .build(); + +// With IS NULL predicates +UpdateStatement statement8 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(Value.of(30))) + .where(Predicate.column("name").isNotNull()) + .and(Predicate.column("age").isNull()) + .build(); + +// With positional bind markers +UpdateStatement statement9 = + StatementBuilder.update("ns", "user") + .set(Assignment.column("age").value(BindMarker.positional())) + .where(Predicate.column("age").isLessThan(BindMarker.positional())) + .build(); +``` + +### DELETE + +The `DELETE` command deletes records in the database. You can specify any conditions in the `WHERE` clause to filter records. However, specifying a primary key uniquely is recommended as much as possible to avoid the cross-partition operation since it might cause performance and consistency issues, especially in non-JDBC databases. Because ScalarDB SQL creates an execution plan for a `DELETE` command that uses a `Get` or `Scan` operation to identify the target records, the same rule is applied for the selection of records. To understand what kinds of `WHERE` clauses cause cross-partition operations and to avoid such operations, see [SELECT](#select). + +You need to enable the cross-partition scan option if you want to delete all records across partitions without specifying the `WHERE` clause. You also need to enable the cross-partition scan with filtering option if you want to flexibly delete records across partitions with arbitrary conditions in the `WHERE` clause. For details about configurations, see [Cross-partition scan configurations](../configurations.mdx#cross-partition-scan-configurations) and [ScalarDB Cluster SQL configurations](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations). + +:::warning + +For non-JDBC databases, transactions could be executed at read-committed snapshot isolation (`SNAPSHOT`), which is a lower isolation level, even if you enable cross-partition scan with the `SERIALIZABLE` isolation level. When using non-JDBC databases, use cross-partition scan only if consistency does not matter for your transactions. + +::: + +This command returns the following column: + +- `updateCount`: `INT` - the number of deleted records + +#### Grammar + +```sql +DELETE FROM [.]
[AS ] + [WHERE and_predicates [OR and_predicates ...] | or_predicates [AND or_predicates ...]] + [WITH operation_attributes] + +identifier: [[.]
.] | [alias.] +and_predicates: predicate | (predicate [AND predicate ...]) +or_predicates: predicate | (predicate [OR predicate ...]) +predicate: operator | BETWEEN AND | [NOT] LIKE [ESCAPE ] | IS [NOT] NULL +operator: = | <> | != | > | >= | < | <= +operation_attributes: operation_attribute [AND operation_attribute] ... +operation_attribute: = +``` + +##### Note + +`WHERE` clause: + +- You can use arbitrary predicates for any columns in the `WHERE` clause. +- In the `WHERE` clause, predicates must be an OR-wise of `and_predicates` (known as disjunctive normal form) or an AND-wise of `or_predicates` (known as conjunctive normal form). +- When connecting multiple `and_predicates` or `or_predicates`, which have more than one predicate, you need to put parentheses around `and_predicates` and `or_predicates`. +- You can specify `` to a bind marker (positional `?` and named `:`). See the [Literal](#literal) section for the literal syntax. +- You cannot specify encrypted columns in the `WHERE` clause. + +`LIKE` predicate: + +- `_` in `` matches any single character. +- `%` in `` matches any sequence of zero or more characters. +- `\` in `` works as the escape character by default. + - You can change the escape character by specifying the `ESCAPE` clause. + - You can disable the escape character by specifying an empty escape character, `ESCAPE ''`. + +#### Examples with the full primary key specified + +If you have the following table, for example: + +```sql +CREATE TABLE ns.tbl ( + c1 INT, + c2 TEXT, + c3 FLOAT, + c4 BIGINT, + c5 BOOLEAN, + PRIMARY KEY (c1, c2, c3) +) WITH CLUSTERING ORDER BY (c2 DESC, c3 ASC); +``` + +Examples of `DELETE` are as follows: + +```sql +-- Delete a record +DELETE FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23; + +-- With positional bind markers +DELETE FROM tbl WHERE c1 = ? AND c2 = ? AND c3 = ?; + +-- With operations attributes +DELETE FROM ns.tbl WHERE c1 = 10 AND c2 = 'aaa' AND c3 = 1.23 WITH 'attribute1' = 'value1' AND 'attribute2' = 'value2'; +``` + +Examples of building statement objects for `DELETE` are as follows: + +```java +// Delete a record +DeleteStatement statement1 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .build(); + +// With positional bind markers +DeleteStatement statement2 = + StatementBuilder.deleteFrom("tbl") + .where(Predicate.column("c1").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c2").isEqualTo(BindMarker.positional())) + .and(Predicate.column("c3").isEqualTo(BindMarker.positional())) + .build(); + +// With operations attributes +DeleteStatement statement3 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("c1").isEqualTo(Value.of(10))) + .and(Predicate.column("c2").isEqualTo(Value.of("aaa"))) + .and(Predicate.column("c3").isEqualTo(Value.of(1.23F))) + .withAttribute("attribute1", "value1") + .withAttribute("attribute2", "value2") + .build(); +``` + +#### Examples without the full primary key specified + +If you have the following table, for example: + +```sql +CREATE TABLE ns.user ( + id INT, + name TEXT, + age INT, + height FLOAT, + PRIMARY KEY (id) +) +``` + +Examples of `DELETE` with cross-partition scan filtering are as follows: + +```sql +-- Without the WHERE clause to delete all the records of a table +DELETE FROM ns.user; + +-- With AND predicates for non-primary key columns +DELETE FROM ns.user WHERE age > 10 AND height > 140; + +-- With OR predicates for non-primary key columns +DELETE FROM ns.user WHERE age > 10 OR height > 140; + +-- With OR-wise of AND predicates +DELETE FROM ns.user WHERE (age > 10 AND height > 150) OR (age > 15 AND height > 145); + +-- With AND-wise of OR predicates +DELETE FROM ns.user WHERE (age < 10 OR age > 65) AND (height < 145 OR height > 175); + +-- With LIKE predicates +DELETE FROM ns.user WHERE name LIKE 'A%' OR name NOT LIKE 'B_b'; + +-- With LIKE predicates with an escape character +DELETE FROM ns.user WHERE name LIKE '+%Alice' ESCAPE '+'; + +-- With IS NULL predicates +DELETE FROM ns.user WHERE name IS NOT NULL AND age IS NULL; + +-- With positional bind markers +DELETE FROM ns.user WHERE age < ?; +``` + +Examples of building statement objects for `DELETE` are as follows: + +```java +// Without the WHERE clause to delete all the records of a table +DeleteStatement statement1 = StatementBuilder.deleteFrom("ns", "tbl").build(); + +// With AND predicates for non-primary key columns +DeleteStatement statement2 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR predicates for non-primary key columns +DeleteStatement statement3 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("age").isGreaterThan(Value.of(10))) + .or(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build(); + +// With OR-wise of AND predicates +DeleteStatement statement4 = + StatementBuilder.deleteFrom("ns", "tbl") + .where( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(10))) + .and(Predicate.column("height").isGreaterThan(Value.of(140.0F))) + .build()) + .or( + AndPredicateList.predicate(Predicate.column("age").isGreaterThan(Value.of(15))) + .and(Predicate.column("height").isGreaterThan(Value.of(145.0F))) + .build()) + .build(); + +// With AND-wise of OR predicates +DeleteStatement statement5 = + StatementBuilder.deleteFrom("ns", "tbl") + .where( + OrPredicateList.predicate(Predicate.column("age").isLessThan(Value.of(10))) + .or(Predicate.column("age").isGreaterThan(Value.of(65))) + .build()) + .and( + OrPredicateList.predicate(Predicate.column("height").isLessThan(Value.of(145.0F))) + .or(Predicate.column("height").isGreaterThan(Value.of(175.0F))) + .build()) + .build(); + +// With LIKE predicates +DeleteStatement statement6 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("name").isLike(Value.of("A%"))) + .or(Predicate.column("name").isNotLike(Value.of("B_b"))) + .build(); + +// With LIKE predicates with an escape character +DeleteStatement statement7 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("name").isLike(Value.of("+%Alice"), Value.of("+"))) + .build(); + +// With IS NULL predicates +DeleteStatement statement8 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("name").isNotNull()) + .and(Predicate.column("age").isNull()) + .build(); + +// With positional bind markers +DeleteStatement statement9 = + StatementBuilder.deleteFrom("ns", "tbl") + .where(Predicate.column("age").isLessThan(BindMarker.positional())) + .build(); +``` + +## DCL + +### CREATE USER + +The `CREATE USER` command creates a new user with the specified username, password, and user attributes. + +#### Grammar + +```sql +CREATE USER [WITH] {PASSWORD | SUPERUSER | NO_SUPERUSER} ... +``` + +- If you don't specify a password for a user, the user is created without a password. +- If you specify the `SUPERUSER` attribute for a user, the user becomes a superuser. +- If you specify the `NO_SUPERUSER` attribute for a user, the user becomes a normal user. +- If you don't specify either `SUPERUSER` or `NO_SUPERUSER` for a user, the user becomes a normal user. + +#### Examples + +Examples of `CREATE USER` are as follows: + +```sql +-- Create a user with a password as a superuser. +CREATE USER user1 WITH PASSWORD 'password1' SUPERUSER; + +-- Create a user with a password. +CREATE USER user2 WITH PASSWORD 'password2'; + +-- Create a user without a password. +CREATE USER user3; +``` + +Examples of building statement objects for `CREATE USER` are as follows: + +```java +// Create a user with a password and the `SUPERUSER` attribute. +CreateUserStatement statement1 = + StatementBuilder.createUser("user1").with("password", UserOption.SUPERUSER).build(); + +// Create a user with a password. +CreateUserStatement statement2 = StatementBuilder.createUser("user1").with("password").build(); + +// Create a user without a password. +CreateUserStatement statement3 = StatementBuilder.createUser("user1").build(); +``` + +### ALTER USER + +The `ALTER USER` command changes the password and user attributes of the specified user. + +#### Grammar + +```sql +ALTER USER [WITH] {PASSWORD | SUPERUSER | NO_SUPERUSER} ... +``` + +- If you specify the `SUPERUSER` attribute for a user, the user becomes a superuser. +- If you specify the `NO_SUPERUSER` attribute for a user, the user becomes a normal user. + +#### Examples + +Examples of `ALTER USER` are as follows: + +```sql +-- Change the password of a user. +ALTER USER user1 WITH PASSWORD 'password1'; + +-- Change a user to a superuser. +ALTER USER user1 WITH SUPERUSER; +``` + +Examples of building statement objects for `ALTER USER` are as follows: + +```java +// Change the password of a user. +AlterUserStatement statement1 = StatementBuilder.alterUser("user1").with("password2").build(); + +// Change a user to a superuser. +AlterUserStatement statement2 = + StatementBuilder.alterUser("user1").with(UserOption.SUPERUSER).build(); +``` + +### DROP USER + +The `DROP USER` command deletes the specified user. + +#### Grammar + +```sql +DROP USER +``` + +#### Examples + +An example of `DROP USER` is as follows: + +```sql +-- Delete a user. +DROP USER user1; +``` + +An example of building statement objects for `DROP USER` is as follows: + +```java +// Delete a user. +DropUserStatement statement = StatementBuilder.dropUser("user1").build(); +``` + +### GRANT + +The `GRANT` command grants privileges to the specified user. + +#### Grammar + +```sql +GRANT {privilege [, privilege] ... | ALL [PRIVILEGES]} ON [TABLE]
[,
] ... TO [USER] [, ] ... [WITH GRANT OPTION] +GRANT {privilege [, privilege] ... | ALL [PRIVILEGES]} ON NAMESPACE [, ] ... TO [USER] [, ] ... [WITH GRANT OPTION] + +privilege: SELECT | INSERT | UPDATE | DELETE | CREATE | DROP | TRUNCATE | ALTER +``` + +- You must grant `INSERT` and `UPDATE` privileges together. +- To grant a user the `UPDATE` or `DELETE` privilege, the target user must have the `SELECT` privilege. +- If you specify the `WITH GRANT OPTION` option, the user can grant privileges to other users. + +#### Examples + +Examples of `GRANT` are as follows: + +```sql +-- Grant the SELECT privilege on a table to a user. +GRANT SELECT ON ns.tbl TO user1; + +-- Grant the SELECT privilege on tables to users. +GRANT SELECT ON ns.tbl1, ns.tbl2 TO user1, user2; + +-- Grant the SELECT privilege on all tables in a namespace to a user. +GRANT SELECT ON NAMESPACE ns TO user1; + +-- Grant all privileges and GRANT OPTION on a table to a user. +GRANT ALL ON ns.tbl TO user1 WITH GRANT OPTION; + +-- Grant all privileges and GRANT OPTION on all tables in a namespace to a user. +GRANT ALL ON NAMESPACE ns TO user1 WITH GRANT OPTION; +``` + +Examples of building statement objects for `GRANT` are as follows: + +```java +// Grant the SELECT privilege on a table to a user. +GrantStatement statement1 = + StatementBuilder.grant(Privilege.SELECT).onTable("ns", "tbl").toUser("user1").build(); + +// Grant the SELECT privilege on tables to users. +GrantStatement statement2 = + StatementBuilder.grant(Privilege.SELECT) + .onTable("ns", "tbl1", "ns", "tbl2") + .toUser("user1", "user2") + .build(); + +// Grant the SELECT privilege on all tables in a namespace to a user. +GrantStatement statement3 = + StatementBuilder.grant(Privilege.SELECT).onNamespace("ns").toUser("user1").build(); + +// Grant all privileges and GRANT OPTION on a table to a user. +GrantStatement statement4 = + StatementBuilder.grant(Privilege.values()) + .onTable("ns", "tbl") + .toUser("user1") + .withGrantOption() + .build(); + +// Grant all privileges and GRANT OPTION on all tables in a namespace to a user. +GrantStatement statement5 = + StatementBuilder.grant(Privilege.values()) + .onNamespace("ns") + .toUser("user1") + .withGrantOption() + .build(); +``` + +### REVOKE + +The `REVOKE` command revokes privileges from the specified user. + +#### Grammar + +```sql +REVOKE {privilege [, privilege] ... | ALL [PRIVILEGES]} [, GRANT OPTION] ON [TABLE]
[,
] ... FROM [USER] [, ] ... +REVOKE GRANT OPTION ON [TABLE]
[,
] ... FROM [USER] [, ] ... +REVOKE {privilege [, privilege] ... | ALL [PRIVILEGES]} [, GRANT OPTION] ON NAMESPACE [, ] ... FROM [USER] [, ] ... +REVOKE GRANT OPTION ON NAMESPACE [, ] ... FROM [USER] [, ] ... + +privilege: SELECT | INSERT | UPDATE | DELETE | CREATE | DROP | TRUNCATE | ALTER +``` + +- You must revoke `INSERT` and `UPDATE` privileges together. +- If the target user has the `INSERT` or `UPDATE` privilege, you cannot revoke the `SELECT` privilege from them. + +#### Examples + +Examples of `REVOKE` are as follows: + +```sql +-- Revoke the SELECT privilege on a table from a user. +REVOKE SELECT ON ns.tbl FROM user1; + +-- Revoke the SELECT privilege on tables from users. +REVOKE SELECT ON ns.tbl1, ns.tbl2 FROM user1, user2; + +-- Revoke the SELECT privilege on all tables in a namespace from a user. +REVOKE SELECT ON NAMESPACE ns FROM user1; + +-- Revoke all privileges and GRANT OPTION on a table from a user. +REVOKE ALL, GRANT OPTION ON ns.tbl FROM user1; + +-- Revoke all privileges and GRANT OPTION on all tables in a namespace from a user. +REVOKE ALL, GRANT OPTION ON NAMESPACE ns FROM user1; +``` + +Examples of building statement objects for `REVOKE` are as follows: + +```java +// Revoke the SELECT privilege on a table from a user. +RevokeStatement statement1 = + StatementBuilder.revoke(Privilege.SELECT).onTable("ns", "tbl").fromUser("user1").build(); + +// Revoke the SELECT privilege on tables from users. +RevokeStatement statement2 = + StatementBuilder.revoke(Privilege.SELECT) + .onTable("ns", "tbl1", "ns", "tbl2") + .fromUser("user1", "user2") + .build(); + +// Revoke the SELECT privilege on all tables in a namespace from a user. +RevokeStatement statement3 = + StatementBuilder.revoke(Privilege.SELECT).onNamespace("ns").fromUser("user1").build(); + +// Revoke all privileges and GRANT OPTION on a table from a user. +RevokeStatement statement4 = + StatementBuilder.revoke(Privilege.values()) + .onTable("ns", "tbl") + .fromUser("user1") + .build(); + +// Revoke all privileges and GRANT OPTION on all tables in a namespace from a user. +RevokeStatement statement5 = + StatementBuilder.revoke(Privilege.values()) + .onNamespace("ns") + .fromUser("user1") + .build(); +``` + +## Others + +### USE + +The `USE` command specifies a default namespace. If a namespace name is omitted in a SQL statement, the default namespace will be used. + +#### Grammar + +```sql +USE +``` + +#### Examples + +An example of `USE` is as follows: + +```sql +-- Specify a default namespace name "ns" +USE ns; +``` + +An example of building statement objects for `USE` is as follows: + +```java +// Specify a default namespace name "ns" +UseStatement statement = StatementBuilder.use("ns").build(); +``` + +### BEGIN + +The `BEGIN` command begins a transaction. + +This command returns the following column: + +- `transactionId`: `TEXT` - a transaction ID associated with the transaction you have begun + +#### Grammar + +```sql +BEGIN +``` + +#### Examples + +An example of building statement objects for `BEGIN` is as follows: + +```java +// Begin a transaction +BeginStatement statement = StatementBuilder.begin().build(); +``` + +### START TRANSACTION + +The `START TRANSACTION` command starts a transaction. This command is an alias of `BEGIN`. + +This command returns the following column: + +- `transactionId`: `TEXT` - the transaction ID associated with the transaction you have started + +#### Grammar + +```sql +START TRANSACTION +``` + +#### Examples + +An example of building statement objects for `START TRANSACTION` is as follows: + +```java +// Start a transaction. +StartTransactionStatement statement = StatementBuilder.startTransaction().build(); +``` + +### JOIN + +The `JOIN` command joins a transaction associated with the specified transaction ID. + +#### Grammar + +```sql +JOIN +``` + +#### Examples + +An example of `JOIN` is as follows: + +```sql +-- Join a transaction +JOIN 'id'; +``` + +An example of building statement objects for `JOIN` is as follows: + +```java +// Join a transaction +JoinStatement statement = StatementBuilder.join("id").build(); +``` + +### PREPARE + +The `PREPARE` command prepares the current transaction. + +#### Grammar + +```sql +PREPARE +``` + +#### Examples + +An example of building statement objects for `PREPARE` is as follows: + +```java +// Prepare the current transaction +PrepareStatement statement = StatementBuilder.prepare().build(); +``` + +### VALIDATE + +The `VALIDATE` command validates the current transaction. + +#### Grammar + +```sql +VALIDATE +``` + +#### Examples + +An example of building statement objects for `VALIDATE` is as follows: + +```java +// Validate the current transaction +ValidateStatement statement = StatementBuilder.validate().build(); +``` + +### COMMIT + +The `COMMIT` command commits the current transaction. + +#### Grammar + +```sql +COMMIT +``` + +#### Examples + +An example of building statement objects for `COMMIT` is as follows: + +```java +// Commit the current transaction +CommitStatement statement = StatementBuilder.commit().build(); +``` + +### ROLLBACK + +The `ROLLBACK` command rolls back the current transaction. + +#### Grammar + +```sql +ROLLBACK +``` + +#### Examples + +An example of building statement objects for `ROLLBACK` is as follows: + +```java +// Rollback the current transaction +RollbackStatement statement = StatementBuilder.rollback().build(); +``` + +### ABORT + +The `ABORT` command rolls back the current transaction. This command is an alias of `ROLLBACK`. + +#### Grammar + +```sql +ABORT +``` + +#### Examples + +An example of building statement objects for `ABORT` is as follows: + +```java +// Abort the current transaction. +AbortStatement statement = StatementBuilder.abort().build(); +``` + +### SET MODE + +The `SET MODE` command switches the current transaction mode. + +#### Grammar + +```sql +SET MODE transaction_mode + +transaction_mode: TRANSACTION | TWO_PHASE_COMMIT_TRANSACTION +``` + +#### Examples + +An example of `SET MODE` is as follows: + +```sql +-- Switch the current transaction mode to Two-phase Commit Transaction +SET MODE TWO_PHASE_COMMIT_TRANSACTION; +``` + +An example of building statement objects for `SET MODE` is as follows: + +```java +// Switch the current transaction mode to Two-phase Commit Transaction +SetModeStatement statement = + StatementBuilder.setMode(TransactionMode.TWO_PHASE_COMMIT_TRANSACTION).build(); +``` + +### SHOW NAMESPACES + +The `SHOW NAMESPACES` command shows namespace names. + +:::note + +This command extracts the namespace names of user tables dynamically. As a result, only namespaces that contain tables are returned. Starting from ScalarDB 4.0, we plan to improve the design to remove this limitation. + +::: + +This command returns the following column: + +- `namespaceName`: `TEXT` - the namespace name + +#### Grammar + +```sql +SHOW NAMESPACES +``` + +#### Examples + +An example of building statement objects for `SHOW NAMESPACES` is as follows: + +```java +// Show namespace names. +ShowNamespacesStatement statement = StatementBuilder.showNamespaces().build(); +``` + +### SHOW TABLES + +The `SHOW TABLES` command shows table names in a namespace. If a namespace name is omitted, the default namespace will be used. + +This command returns the following column: + +- `tableName`: `TEXT` - a table name + +#### Grammar + +```sql +SHOW TABLES [FROM ] +``` + +#### Examples + +Examples of `SHOW TABLES` is as follows: + +```sql +-- Show table names in the default namespace +SHOW TABLES; + +-- Show table names in a namespace "ns" +SHOW TABLES FROM ns; +``` + +Examples of building statement objects for `SHOW TABLES` is as follows: + +```java +// Show table names in the default namespace +ShowTablesStatement statement1 = StatementBuilder.showTables().build(); + +// Show table names in a namespace "ns" +ShowTablesStatement statement2 = StatementBuilder.showTables().from("ns").build(); +``` + +### DESCRIBE + +The `DESCRIBE` command returns column metadata for the specified table. + +This command returns the following columns: + +- `columnName`: `TEXT` - a table name +- `type`: `TEXT` - a type name +- `isPrimaryKey`: `BOOLEAN` - whether it's a column part of primary key +- `isPartitionKey`: `BOOLEAN` - whether it's a column part of partition key +- `isClusteringKey`: `BOOLEAN` - whether it's a column part of clustering key +- `clusteringOrder`: `TEXT` - a clustering order +- `isIndexed`: `BOOLEAN` - whether it's an indexed column + +#### Grammar + +```sql +DESCRIBE [.]
+ +DESC [.]
+``` + +#### Examples + +Examples of `DESCRIBE` is as follows: + +```sql +-- Returns column metadata for "ns.tbl" +DESCRIBE ns.tbl; + +-- Returns column metadata for "tbl" +DESC tbl; +``` + +Examples of building statement objects for `DESCRIBE` is as follows: + +```java +// Returns column metadata for "ns.tbl" +DescribeStatement statement1 = StatementBuilder.describe("ns", "tbl").build(); + +// Returns column metadata for "tbl" +DescribeStatement statement2 = StatementBuilder.describe("tbl").build(); +``` + +### SUSPEND + +The `SUSPEND` command suspends the ongoing transaction in the current session. + +#### Grammar + +```sql +SUSPEND +``` + +#### Examples + +Examples of building statement objects for `SUSPEND` is as follows: + +```java +// Suspend the ongonig transaction in the current session +SuspendStatement statement = StatementBuilder.suspend().build(); +``` + +### RESUME + +The `RESUME` command resumes the transaction associated with the specified transaction ID in the current session. + +#### Grammar + +```sql +RESUME +``` + +#### Examples + +An example of `RESUME` is as follows: + +```sql +-- Resume a transaction +RESUME 'id'; +``` + +An example of building statement objects for `RESUME` is as follows: + +```java +// Resume a transaction +ResumeStatement statement = StatementBuilder.resume("id").build(); +``` + +### SHOW USERS + +The `SHOW USERS` command shows usernames and user attributes. If you are a superuser, you can see all users. If you are a normal user, you can see only your own username and attributes. + +This command returns the following columns: + +- `username`: `TEXT` - a username +- `isSuperuser`: `BOOLEAN` - whether the user is a superuser + +#### Grammar + +```sql +SHOW USERS +``` + +#### Examples + +An example of `SHOW USERS` is as follows: + +```sql +-- Show usernames and user attributes +SHOW USERS; +``` + +An example of building statement objects for `SHOW USERS` is as follows: + +```java +// Show usernames and user attributes +ShowUsersStatement statement = StatementBuilder.showUsers().build(); +``` + +### SHOW GRANTS + +The `SHOW GRANTS` command shows the privileges granted to the current user or the specified user. + +This command returns the following columns: + +- `name`: `TEXT` - a namespace name or a table name, depending on the type +- `type`: `TEXT` - the type of the object (either `NAMESPACE` or `TABLE`) +- `privilege`: `TEXT` - a privilege + +#### Grammar + +```sql +-- Show privileges granted to the current user +SHOW GRANTS + +-- Show privileges granted to the specified user +SHOW GRANTS FOR [USER] +``` + +#### Examples + +Examples of `SHOW GRANTS` are as follows: + +```sql +-- Show privileges granted to the current user +SHOW GRANTS; + +-- Show privileges granted to user1 +SHOW GRANTS FOR user1; +``` + +Examples of building statement objects for `SHOW GRANTS` are as follows: + +```java +// Show privileges granted to the current user +ShowGrantsStatement statement1 = StatementBuilder.showGrants().build(); + +// Show privileges granted to user1 +ShowGrantsStatement statement2 = StatementBuilder.showGrants().forUser("user1").build(); +``` + +## Literal + +Literal and column values are synonymous and refer to a fixed data value used when writing SQL statements. For example, `1`, `'abc'`, `1.23`, and `'2024-05-19'` are literals. + +### Text + +A text literal is a sequence of characters enclosed in single quotes `'`, such as `'abc'` and `'abc def'`. + +### Numeric + +Numeric literals include exact-value (INTEGER and BIGINT) and approximate-value (FLOAT and DOUBLE) literals. + +An exact-value literal is a sequence of digits, such as `123` and `-5`. + +An approximate-value literal is a sequence of digits with a decimal point, such as `4.754` and `-1.2`. + +### Date and time + +Date and time literals are text literals that follow a specific format to represents DATE, TIME, TIMESTAMP, and TIMESTAMPTZ values. + +| ScalarDB type | Format | Note | Example | +|---------------|-------------------------------------|------------------------------------------------------------------|----------------------------------------------------------------------------------| +| DATE | **'YYYY-MM-DD'** | | `'2024-05-19'` | +| TIME | **'HH:MM:[SS[.FFFFFF]]'** | Second and fractional second (up to 1 microsecond) are optional. | `'12:34'`, `'12:34:56'`, `'12:34:56.789123'` | +| TIMESTAMP | **'YYYY-MM-DD HH:MM:[SS[.FFF]]'** | Second and fractional second (up to 1 millisecond) are optional. | `'2024-05-19 12:34'`, `'2024-05-19 12:34:56'`, `'2024-05-19 12:34:56.789'` | +| TIMESTAMPTZ | **'YYYY-MM-DD HH:MM:[SS[.FFF]] Z'** | Second and fractional second (up to 1 millisecond) are optional. | '`2024-05-19 12:34 Z'`, `'2024-05-19 12:34:56 Z'`, `'2024-05-19 12:34:56.789 Z'` | diff --git a/versioned_docs/version-3.15/scalardb-sql/images/spring_data_ingegration_overall_arch.png b/versioned_docs/version-3.15/scalardb-sql/images/spring_data_ingegration_overall_arch.png new file mode 100644 index 00000000..67b52a44 Binary files /dev/null and b/versioned_docs/version-3.15/scalardb-sql/images/spring_data_ingegration_overall_arch.png differ diff --git a/versioned_docs/version-3.15/scalardb-sql/index.mdx b/versioned_docs/version-3.15/scalardb-sql/index.mdx new file mode 100644 index 00000000..4de31391 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-sql/index.mdx @@ -0,0 +1,37 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB SQL Overview + +ScalarDB SQL is an interface layer that allows client applications to communicate with ScalarDB Cluster by using SQL. + +:::note + +ScalarDB SQL is not fully compatible with standard SQL, but it offers a large subset of the SQL language. + +::: + +## Types of SQL interfaces + +ScalarDB SQL has three types of SQL interfaces. + +### JDBC + +The JDBC interface lets you connect to ScalarDB Cluster by using the standard JDBC API. This is useful for applications that already use JDBC. + +For details on how to set up and use the JDBC interface, see the [ScalarDB JDBC Guide](./jdbc-guide.mdx). + +### SQL API + +The SQL API lets you connect to ScalarDB Cluster by using the proprietary and modern Java SQL API. This is useful for applications that do not need to rely on the JDBC interface. + +For details on how to set up and use the SQL API, see the [ScalarDB SQL API Guide](./sql-api-guide.mdx). + +### Spring Data JDBC + +The Spring Data JDBC interface lets you interact with ScalarDB Cluster via Spring Data JDBC repositories and entities. This is useful for applications that already use Spring Data or when you want to integrate ScalarDB Cluster into Spring applications. + +For details on how to set up and use the Sprign Data JDBC interface, see the [Guide of Spring Data JDBC for ScalarDB](./spring-data-guide.mdx). diff --git a/versioned_docs/version-3.15/scalardb-sql/jdbc-guide.mdx b/versioned_docs/version-3.15/scalardb-sql/jdbc-guide.mdx new file mode 100644 index 00000000..ef8180e2 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-sql/jdbc-guide.mdx @@ -0,0 +1,223 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB JDBC Guide + +The usage of ScalarDB JDBC basically follows [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/). +This guide describes several important topics that are specific to ScalarDB JDBC. + +## Add ScalarDB JDBC driver to your project + +To add the dependencies for the ScalarDB JDBC driver by using Gradle, use the following, replacing `` with the versions of the ScalarDB JDBC driver and the related library, respectively, that you are using: + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql-jdbc:' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:' +} +``` + +To add the dependencies by using Maven, use the following, replacing `...` with the version of the ScalarDB JDBC driver that you are using: + +```xml + + + com.scalar-labs + scalardb-sql-jdbc + ... + + + com.scalar-labs + scalardb-cluster-java-client-sdk + ... + + +``` + +## JDBC connection URL + +The JDBC connection URL format of ScalarDB JDBC is as follows: + +```console +jdbc:scalardb:?=&=&... +``` + +For example: + +Only specify configuration file path: + +```console +jdbc:scalardb:/path/to/database.properties +``` + +Only specify properties: + +```console +jdbc:scalardb:?scalar.db.contact_points=localhost&scalar.db.username=cassandra&scalar.db.password=cassandra&scalar.db.storage=cassandra +``` + +Specify configuration file path and properties: + +```console +jdbc:scalardb:/path/to/database.properties?scalar.db.metadata.cache_expiration_time_secs=0 +``` + +## Configurations for ScalarDB JDBC + +Please see [ScalarDB Cluster SQL client configurations](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations) for details on the configurations. + +In addition, the ScalarDB JDBC specific configurations are as follows: + +| name | description | default | +|---------------------------------------------------------------------|------------------------------------------------------------------------------|---------| +| scalar.db.sql.jdbc.default_auto_commit | The default connection's auto-commit mode. | true | +| scalar.db.sql.jdbc.sql_session_factory_cache.expiration_time_millis | The expiration time in milliseconds for the cache of SQL session factories. | 10000 | + +## Data type mapping between ScalarDB and JDBC + +Since ScalarDB doesn't support all the data types defined in JDBC, the following explains the data type mapping between ScalarDB and JDBC. + +The data type mapping between ScalarDB and JDBC is as follows: + +| ScalarDB Type | JDBC (Java) Type | +|---------------|-------------------------| +| BOOLEAN | boolean or Boolean | +| INT | int or Integer | +| BIGINT | long or Long | +| FLOAT | float or Float | +| DOUBLE | double or Double | +| TEXT | String | +| BLOB | byte[] | +| DATE | java.time.LocalDate | +| TIME | java.time.LocalTime | +| TIMESTAMP | java.time.LocalDateTime | +| TIMESTAMPTZ | java.time.Instant | + +How to get the data from a `java.sql.ResultSet` object for each data type is as follows: + +```java +try (ResultSet resultSet = ...) { + resultSet.next(); + + // Get a BOOLEAN value of a column + boolean booleanValue = resultSet.getBoolean(""); + + // Get an INT value of a column + int intValue = resultSet.getInt(""); + + // Get a BIGINT value of a column + long bigIntValue = resultSet.getLong(""); + + // Get a FLOAT value of a column + float floatValue = resultSet.getFloat(""); + + // Get a DOUBLE value of a column + double doubleValue = resultSet.getDouble(""); + + // Get a TEXT value of a column + String textValue = resultSet.getString(""); + + // Get a BLOB value of a column + byte[] blobValue = resultSet.getBytes(""); + + // Get a DATE value of a column + LocalDate dateValue = resultSet.getObject("", LocalDate.class); + + // Get a TIME value of a column + LocalTime timeValue = resultSet.getObject("", LocalTime.class); + + // Get a TIMESTAMP value of a column + LocalDateTime timestampValue = resultSet.getObject("", LocalDateTime.class); + + // Get a TIMESTAMPTZ value of a column + Instant timestampTZValue = resultSet.getObject("", Instant.class); +} +``` + +How to set the data as a parameter for each data type for a `java.sql.PreparedStatement` object is as follows: + +```java +try (PreparedStatement preparedStatement = ...) { + // Set a BOOLEAN value as parameter + preparedStatement.setBoolean(1, ); + + // Set an INT value as parameter + preparedStatement.setInt(2, ); + + // Set a BIGINT value as parameter + preparedStatement.setLong(3, ); + + // Set a FLOAT value as parameter + preparedStatement.setFloat(4, ); + + // Set a DOUBLE value as parameter + preparedStatement.setDouble(5, ); + + // Set a TEXT value as parameter + preparedStatement.setString(7, ""); + + // Set a BLOB value as parameter + preparedStatement.setBytes(8, ); + + //Set a DATE value as parameter + preparedStatement.setObject(9, ); + + //Set a TIME value as parameter + preparedStatement.setObject(10, ); + + //Set a TIMESTAMP value as parameter + preparedStatement.setObject(11, ); + + //Set a TIMESTAMPTZ value as parameter + preparedStatement.setObject(12, ); + + preparedStatement.execute(); +} +``` + +## Handle SQLException + +The exception handling is basically the same as ScalarDB SQL API as follows: + +```java +// If you execute multiple statements in a transaction, you need to set auto-commit to false. +connection.setAutoCommit(false); + +try { + // Execute statements (SELECT/INSERT/UPDATE/DELETE) in the transaction + ... + + // Commit the transaction + connection.commit(); +} catch (SQLException e) { + if (e.getErrorCode() == 301) { + // The error code 301 indicates that you catch `UnknownTransactionStatusException`. + // If you catch `UnknownTransactionStatusException`, it indicates that the status of the + // transaction, whether it has succeeded or not, is unknown. In such a case, you need to check + // if the transaction is committed successfully or not and retry it if it failed. How to + // identify a transaction status is delegated to users + } else { + // For other cases, you can try retrying the transaction + + // Rollback the transaction + connection.rollback(); + + // The cause of the exception can be `TransactionRetryableException` or the other + // exceptions. For `TransactionRetryableException`, you can basically retry the transaction. + // However, for the other exceptions, the transaction may still fail if the cause of the + // exception is nontransient. For such a case, you need to limit the number of retries and + // give up retrying + } +} +``` + +Please see also [ScalarDB SQL API Guide](sql-api-guide.mdx) for more details on exception handling. + +## References + +- [Java JDBC API](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) +- [ScalarDB SQL API Guide](sql-api-guide.mdx) +- [Javadoc for ScalarDB JDBC](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-jdbc/3.15.4/index.html) diff --git a/versioned_docs/version-3.15/scalardb-sql/migration-guide.mdx b/versioned_docs/version-3.15/scalardb-sql/migration-guide.mdx new file mode 100644 index 00000000..b16ebe4b --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-sql/migration-guide.mdx @@ -0,0 +1,115 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# How to Migrate Your Applications and Databases into a ScalarDB-Based Environment + +This guide describes how to migrate your existing applications and relational databases into ScalarDB-based applications and ScalarDB-managed databases, respectively. + +## Target audience + +The target audiences for this guide are application developers and database administrators. The purpose of this guide is to help you understand how to migrate your existing applications and databases and in what conditions. + +## What you will learn + +- Requirements for the migration +- Steps to migrate your application +- Changes to make in your application for the migration + +## Steps to migrate your application + +```mermaid +flowchart LR +subgraph AM[After migration] + direction TB + C[Application - updated] -->|ScalarDB SQL| D[ScalarDB] --> E[Relational/JDBC databases - schema updated] +end +subgraph BM[Before migration] + direction TB + A[Application] ---->|SQL| B[Relational/JDBC databases] +end +BM===>AM +``` + +1. Verify the items in the checklist. + - See [Migration checklist](#migration-checklist) to confirm your database is migratable. +2. Migrate your application (if necessary). + - ScalarDB provides selection, projection, and join operations with dedicated SQL grammar. Thus, some SQL statements in your application might have to be changed for ScalarDB SQL, for example, at a grammar level or a logic level like aggregation processing. + - For details, see [How to migrate your application](#how-to-migrate-your-application). +3. Back up your database. + - Although ScalarDB Schema Loader, which you will use to import your database, only changes the metadata of your database when importing it to ScalarDB, you must back it up to avoid unexpected accidents. + - Follow the administration guide of your database. +4. Set up a ScalarDB environment. + - Prepare a configuration file so that ScalarDB can access target databases. + - For details about ScalarDB configurations, see [ScalarDB Configurations](../configurations.mdx). +5. Import your database to ScalarDB. + - Prepare an import schema file that defines target schemas and tables. The schemas and tables will be mapped to ScalarDB namespaces and tables, respectively. Note that "schema" is a synonym for "database" in some database systems. + - Run the ScalarDB Schema Loader with the import option, the ScalarDB configuration file that you created, and the schema file that you prepared. + - For details on how to use Schema Loader, see [Run Schema Loader for importing existing tables](../schema-loader-import.mdx#run-schema-loader-for-importing-existing-tables). +6. Switch your application and check the behavior. + - Now, you can switch your application to the ScalarDB-based application. + +## Migration checklist + +Before starting the migration, check the following questions. If the answer to any of these questions is "No", you must address them before proceeding with the migration. + +- Are your target database and version one of the [supported relational databases (called JDBC databases in ScalarDB) and versions](../requirements.mdx#relational-databases)? +- Do you have a fully privileged account that can manage the target database? For details, see [the general requirements](../database-configurations.mdx#general-requirements). +- Do all target tables have primary keys? +- Is the data type of each column supported in ScalarDB? For supported data types and how they are mapped to ScalarDB data types, see [Data-type mapping from JDBC databases to ScalarDB](../schema-loader-import.mdx#data-type-mapping-from-jdbc-databases-to-scalardb). +- Do the functionality and grammar of the queries in your application comply with the [ScalarDB SQL specifications](./grammar.mdx)? Or, for non-compliant queries, can you re-write them for ScalarDB? For examples of re-writes, see [How to migrate your application](#how-to-migrate-your-application). +- After migrating your applications and databases into ScalarDB applications and ScalarDB-managed databases, respectively, can you stop accessing the databases directly? In other words, is it acceptable for you to always access the databases through ScalarDB? + +## How to migrate your application + +Depending on your application environment, you may need to migrate your application in the following three aspects: + +- Change connection settings. +- Modify SQL statements based on the ScalarDB SQL grammar. +- Modify application logic if there is no available SQL modification workaround. + +### Change connection settings + +If your application is based on Java, you can use the ScalarDB JDBC driver when migrating. For details on how to add dependencies for the ScalarDB JDBC driver and rewrite the connection URL, see the [ScalarDB JDBC Guide](./jdbc-guide.mdx). + +If your application is not based on Java, you can connect ScalarDB and issue SQL via gRPC. For details, see [ScalarDB Cluster SQL gRPC API Guide](../scalardb-cluster/scalardb-cluster-sql-grpc-api-guide.mdx). + +### Modify SQL statements + +You may need to change the SQL statements in your application due to the differences in SQL grammar. Typical examples are as follows. For more details, see [ScalarDB SQL Grammar](./grammar.mdx). + +- `JOIN` queries + - ScalarDB supports only `JOIN` queries in the style of writing the table to be joined and the condition in the `FROM` clause. + - The `JOIN` condition and filtering also have a few limitations. + - You may need to rewrite the queries based on the above. You can choose application-level modification if your SQL queries are not compliant with the ScalarDB specifications. +- `WHERE` clause + - In ScalarDB, predicates must be an OR-wise of `AND` predicate lists (known as disjunctive normal form or DNF) or an AND-wise of `OR` predicate lists (known as conjunctive normal form or CNF). Thus, you may have to change the `WHERE` clause, but note that an arbitrary form of predicates can be changed to either DNF or CNF. + - Similarly, if you use `IN` clauses, you will need to change them to either DNF or CNF. For `IN` clauses with sub-queries, see [Modify application logic](#modify-application-logic). + - ScalarDB adopts a specification similar to that of the `LIKE` operator and the escape sequence of PostgreSQL and MySQL. If your database is neither PostgreSQL nor MySQL, you may need to change predicates with the `LIKE` operator. + +### Modify application logic + +Although ScalarDB SQL does not provide some functionalities, such as aggregate queries and sub-queries, those queries can be modified to application-level implementations. Typical modification techniques are as follows: + +- Aggregate queries + - For simple aggregate queries such as `count()` and `sum()` without the `GROUP BY` clause, you can use `SELECT` for the target records and then count the number of records or calculate the sum by using the results. + - For `GROUP BY` aggregate queries, first use `SELECT` for all target records without the `GROUP BY` clause. Then, put result records into a multi-map data structure while categorizing them based on the columns specified in the `GROUP BY` clause, which should be used as keys of the multi-map. Finally, aggregate records for each key in the multi-map. For the multi-map, you can use libraries such as [Guava](https://github.com/google/guava). +- Sub-queries + - For sub-queries in the `IN` clause, first use `SELECT` for the records specified in the sub-queries, then add result values as `OR` predicates in the `WHERE` clause. + - For other sub-queries, basically, you need to use `SELECT` for the records for each query, then join or filter results records in your application. +- Read-modify-write by using a single update query + - `UPDATE` queries may often have an expression like an increment or a decrement, for example, `UPDATE table SET a = a + 1 WHERE ...`. In ScalarDB, you need to use `SELECT` for a target record and then set the incremented value as a constant in a single transaction, just like `UPDATE table SET a = 5 WHERE ...`. + +## Limitations + +Due to the difference in data types, ScalarDB will throw an error when writing data larger than the maximum size of the column in the underlying database, even if the size is acceptable for the ScalarDB data type. Conversely, in a few types, the data in the underlying database may be larger than the maximum size in ScalarDB. For details, see [Data-type mapping from JDBC databases to ScalarDB](../schema-loader-import.mdx#data-type-mapping-from-jdbc-databases-to-scalardb). + +## References + +- [Supported Databases](../requirements.mdx#databases) +- [ScalarDB SQL API Guide](./sql-api-guide.mdx) +- [ScalarDB JDBC Guide](./jdbc-guide.mdx) +- [ScalarDB SQL Grammar](./grammar.mdx) +- [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](../schema-loader-import.mdx) diff --git a/versioned_docs/version-3.15/scalardb-sql/scalardb-sql-status-codes.mdx b/versioned_docs/version-3.15/scalardb-sql/scalardb-sql-status-codes.mdx new file mode 100644 index 00000000..8dbe6bf5 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-sql/scalardb-sql-status-codes.mdx @@ -0,0 +1,643 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB SQL Error Codes + +This page provides a list of error codes in ScalarDB SQL. + +## Error code classes and descriptions + +| Class | Description | +|:---------------|:-----------------------------------| +| `DB-SQL-1xxxx` | Errors for the user error category | + +## `DB-SQL-1xxxx` status codes + +The following are status codes and messages for the user error category. + +### `DB-SQL-10000` + +**Message** + +```markdown +The namespace does not exist. Namespace: %s +``` + +### `DB-SQL-10001` + +**Message** + +```markdown +The table does not exist. Table: %s +``` + +### `DB-SQL-10002` + +**Message** + +```markdown +The column %s does not exist +``` + +### `DB-SQL-10003` + +**Message** + +```markdown +The column does not exist. Table: %s; Column: %s +``` + +### `DB-SQL-10004` + +**Message** + +```markdown +The column index is out of bounds. Index: %d; Size: %d +``` + +### `DB-SQL-10005` + +**Message** + +```markdown +A positional bind marker is not allowed when binding named values +``` + +### `DB-SQL-10006` + +**Message** + +```markdown +A named bind marker is not allowed when binding positional values +``` + +### `DB-SQL-10007` + +**Message** + +```markdown +Cannot convert BLOB values to SQL. Please use a bind marker for a BLOB value and bind it separately +``` + +### `DB-SQL-10008` + +**Message** + +```markdown +No namespace name has been specified. Set a default namespace name, or explicitly specify a namespace name +``` + +### `DB-SQL-10009` + +**Message** + +```markdown +Zero bytes may not occur in string parameters +``` + +### `DB-SQL-10010` + +**Message** + +```markdown +Mixing positional values and named values is not allowed +``` + +### `DB-SQL-10011` + +**Message** + +```markdown +Preparing a transaction is supported only in two-phase commit transaction mode +``` + +### `DB-SQL-10012` + +**Message** + +```markdown +Validating a transaction is supported only in two-phase commit transaction mode +``` + +### `DB-SQL-10013` + +**Message** + +```markdown +The previous transaction is still in progress. Commit, roll back, or suspend the previous transaction first +``` + +### `DB-SQL-10014` + +**Message** + +```markdown +This SQL session has already been closed +``` + +### `DB-SQL-10015` + +**Message** + +```markdown +A transaction has not begun +``` + +### `DB-SQL-10016` + +**Message** + +```markdown +The type %s is not supported +``` + +### `DB-SQL-10017` + +**Message** + +```markdown +No connection mode implementations are found. Please add a connection mode implementation to the classpath +``` + +### `DB-SQL-10018` + +**Message** + +```markdown +The connection mode is not specified, but multiple connection mode implementations are found. Specify one of the following connection modes: %s +``` + +### `DB-SQL-10019` + +**Message** + +```markdown +The connection mode '%s' is not found. Specify one of the following connection modes: %s +``` + +### `DB-SQL-10020` + +**Message** + +```markdown +Access denied: You need the %s privilege on the namespace %s to execute this operation +``` + +### `DB-SQL-10021` + +**Message** + +```markdown +Access denied: You need the %s privilege on the table %s to execute this operation +``` + +### `DB-SQL-10022` + +**Message** + +```markdown +Access denied: You can't grant the %s privilege because you don't have the same privilege on the table %s +``` + +### `DB-SQL-10023` + +**Message** + +```markdown +Access denied: You can't grant the %s privilege because you don't have the same privilege on the namespace %s +``` + +### `DB-SQL-10024` + +**Message** + +```markdown +Access denied: You can't revoke the %s privilege because you don't have the same privilege on the table %s +``` + +### `DB-SQL-10025` + +**Message** + +```markdown +Access denied: You can't revoke the %s privilege because you don't have the same privilege on the namespace %s +``` + +### `DB-SQL-10026` + +**Message** + +```markdown +Syntax error. Line %d:%d %s +``` + +### `DB-SQL-10027` + +**Message** + +```markdown +Syntax error. Multiple PRIMARY KEYs specified (exactly one required) +``` + +### `DB-SQL-10028` + +**Message** + +```markdown +Cannot grant the INSERT privilege if the user doesn't have the UPDATE privilege +``` + +### `DB-SQL-10029` + +**Message** + +```markdown +Cannot grant the UPDATE privilege if the user doesn't have the INSERT privilege +``` + +### `DB-SQL-10030` + +**Message** + +```markdown +Cannot grant the UPDATE privilege if the user doesn't have the SELECT privilege +``` + +### `DB-SQL-10031` + +**Message** + +```markdown +Cannot grant the DELETE privilege if the user doesn't have the SELECT privilege +``` + +### `DB-SQL-10032` + +**Message** + +```markdown +Cannot revoke the SELECT privilege if the user has the UPDATE privilege +``` + +### `DB-SQL-10033` + +**Message** + +```markdown +Cannot revoke the SELECT privilege if the user has the DELETE privilege +``` + +### `DB-SQL-10034` + +**Message** + +```markdown +Cannot revoke the INSERT privilege if the user has the UPDATE privilege +``` + +### `DB-SQL-10035` + +**Message** + +```markdown +Cannot revoke the UPDATE privilege if the user has the INSERT privilege +``` + +### `DB-SQL-10036` + +**Message** + +```markdown +A non-clustering-key column is specified in the CLUSTERING ORDER directive. Column: %s +``` + +### `DB-SQL-10037` + +**Message** + +```markdown +The order of the columns in the CLUSTERING ORDER directive must match the order for the clustering key (%s must appear before %s) +``` + +### `DB-SQL-10038` + +**Message** + +```markdown +The CLUSTERING ORDER is missing for the column %s +``` + +### `DB-SQL-10039` + +**Message** + +```markdown +Empty SQL is specified +``` + +### `DB-SQL-10040` + +**Message** + +```markdown +Multiple SQLs are not allowed +``` + +### `DB-SQL-10041` + +**Message** + +```markdown +The column %s is ambiguous +``` + +### `DB-SQL-10042` + +**Message** + +```markdown +The column %s cannot be specified in the %s clause. Only the columns in the table %s can be specified in the %s clause +``` + +### `DB-SQL-10043` + +**Message** + +```markdown +An unbound bind marker is still in the escape character of the LIKE predicate for the column %s +``` + +### `DB-SQL-10044` + +**Message** + +```markdown +The escape character must be a TEXT value for the LIKE predicate for the column %s +``` + +### `DB-SQL-10045` + +**Message** + +```markdown +The value of the predicate must not be null unless the operator is 'IS NULL' or 'IS NOT NULL'. Predicate: %s +``` + +### `DB-SQL-10046` + +**Message** + +```markdown +An unbound bind marker is still in the LIMIT clause +``` + +### `DB-SQL-10047` + +**Message** + +```markdown +The LIMIT must be an INT value +``` + +### `DB-SQL-10048` + +**Message** + +```markdown +Unmatched column names or values +``` + +### `DB-SQL-10049` + +**Message** + +```markdown +The column %s is specified twice +``` + +### `DB-SQL-10050` + +**Message** + +```markdown +All primary key columns must be specified in the INSERT or UPSERT statement +``` + +### `DB-SQL-10051` + +**Message** + +```markdown +An unbound bind marker is still in the value of the column %s +``` + +### `DB-SQL-10052` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a boolean value (BOOLEAN) is specified +``` + +### `DB-SQL-10053` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a decimal number (INT or BIGINT) is specified +``` + +### `DB-SQL-10054` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a floating point number (FLOAT or DOUBLE) is specified +``` + +### `DB-SQL-10055` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a string (TEXT, DATE, TIME, TIMESTAMP, or TIMESTAMPTZ) is specified +``` + +### `DB-SQL-10056` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a BOOLEAN value is specified +``` + +### `DB-SQL-10057` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but an INT value is specified +``` + +### `DB-SQL-10058` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a BIGINT value is specified +``` + +### `DB-SQL-10059` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a FLOAT value is specified +``` + +### `DB-SQL-10060` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a DOUBLE value is specified +``` + +### `DB-SQL-10061` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a TEXT value is specified +``` + +### `DB-SQL-10062` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a BLOB value is specified +``` + +### `DB-SQL-10063` + +**Message** + +```markdown +RIGHT OUTER JOIN can only be specified as the first join +``` + +### `DB-SQL-10064` + +**Message** + +```markdown +The JOIN predicate is not specified properly. Predicate: %s +``` + +### `DB-SQL-10065` + +**Message** + +```markdown +The data types of the columns in the JOIN predicate do not match. Predicate: %s +``` + +### `DB-SQL-10066` + +**Message** + +```markdown +The column %s is specified twice in the JOIN predicates. Predicates: %s +``` + +### `DB-SQL-10067` + +**Message** + +```markdown +Either all primary key columns or an indexed column for the table %s must be specified in the JOIN predicates. Predicates: %s +``` + +### `DB-SQL-10068` + +**Message** + +```markdown +Cannot issue mutation DML SQLs such as INSERT, UPDATE or DELETE with executeQuery() +``` + +### `DB-SQL-10069` + +**Message** + +```markdown +Cannot issue SELECT SQLs with executeUpdate() +``` + +### `DB-SQL-10070` + +**Message** + +```markdown +The TWO_PHASE_COMMIT_TRANSACTION mode is not supported in the current transaction manager +``` + +### `DB-SQL-10071` + +**Message** + +```markdown +The encrypted column %s is not allowed in the %s clause +``` + +### `DB-SQL-10072` + +**Message** + +```markdown +The user %s does not exist +``` + +### `DB-SQL-10073` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a DATE value is specified +``` + +### `DB-SQL-10074` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a TIME value is specified +``` + +### `DB-SQL-10075` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a TIMESTAMP value is specified +``` + +### `DB-SQL-10076` + +**Message** + +```markdown +Unmatched column type. The type of the column %s should be %s, but a TIMESTAMPTZ value is specified +``` + +### `DB-SQL-10077` + +**Message** + +```markdown +The policy %s does not exist +``` diff --git a/versioned_docs/version-3.15/scalardb-sql/spring-data-guide.mdx b/versioned_docs/version-3.15/scalardb-sql/spring-data-guide.mdx new file mode 100644 index 00000000..970251c8 --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-sql/spring-data-guide.mdx @@ -0,0 +1,823 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Guide of Spring Data JDBC for ScalarDB + +Directly using the ScalarDB API may be difficult because you need to write a lot of code and consider how and when to call the APIs (e.g., `rollback()` and `commit()`) for transactions. Since we assume most ScalarDB users develop their applications in Java, you can take advantage of the Spring Framework, which is one of the most popular application frameworks for developing in Java. By using Spring Data JDBC for ScalarDB, you can streamline development by using a familiar framework. + +![Rough overall architecture of Spring Data JDBC for ScalarDB](images/spring_data_ingegration_overall_arch.png) + +The usage of Spring Data JDBC for ScalarDB basically follows [Spring Data JDBC - Reference Documentation](https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/). +This guide describes several important topics to use Spring Data JDBC for ScalarDB and its limitations. + +:::warning + +Spring Data JDBC for ScalarDB extends Spring Data JDBC, but full compatibility is not guaranteed. Only the features listed on this page are officially tested and supported. + +::: + +## Add Spring Data JDBC for ScalarDB to your project + +To add the dependencies on Spring Data JDBC for ScalarDB by using Gradle, use the following, replacing `` with the versions of Spring Data JDBC for ScalarDB and the related library, respectively, that you are using: + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql-spring-data:' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:' +} +``` + +To add the dependencies by using Maven, use the following, replacing `...` with the version of Spring Data JDBC for ScalarDB that you are using: + +```xml + + + com.scalar-labs + scalardb-sql-spring-data + ... + + + com.scalar-labs + scalardb-cluster-java-client-sdk + ... + + +``` + +## Configurations + +Spring Data JDBC for ScalarDB is supposed to be used as a part of Spring application. The following properties are needed at least. + +### spring.datasource.driver-class-name + +This needs to be set to fixed value `com.scalar.db.sql.jdbc.SqlJdbcDriver`. + +```console +spring.datasource.driver-class-name=com.scalar.db.sql.jdbc.SqlJdbcDriver +``` + +### spring.datasource.url + +This value follows the ScalarDB JDBC connection URL configuration. For more information, see [ScalarDB JDBC Guide](jdbc-guide.mdx) and [ScalarDB Cluster SQL client configurations](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations). + +```console +spring.datasource.url=jdbc:scalardb:\ +?scalar.db.sql.connection_mode=direct\ +&scalar.db.contact_points=jdbc:mysql://localhost:3306/my_app_ns\ +&scalar.db.username=root\ +&scalar.db.password=mysql\ +&scalar.db.storage=jdbc\ +&scalar.db.consensus_commit.isolation_level=SERIALIZABLE +``` + +## Annotations + +`@EnableScalarDbRepositories` annotation is needed on the JVM application to use Spring Data JDBC for ScalarDB as follows. + +```java +@SpringBootApplication +@EnableScalarDbRepositories +public class MyApplication { + // These repositories are described in the next section in details + @Autowired private GroupRepository groupRepository; + @Autowired private UserRepository userRepository; +``` + +## Persistent entity model + +The users of Spring Data JDBC for ScalarDB needs to write classes for object mapping to ScalarDB tables. How to write those classes are written in [Persisting Entities](https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/#jdbc.entity-persistence), so this section describes some limitations on the integration. + +These are example model classes: + +### domain/model/User + +```java +// This model class corresponds to the following table schema: +// +// create table my_app_ns.user (id bigint, group_id bigint, name text, primary key (id)); +// +// -- UserRepository can use `name` column as a condition in SELECT statement +// -- as the column is a ScalarDB secondary index. +// create index on my_app_ns.user (name); + +// Set `schema` parameter in @Table annotation if you don't use `scalar.db.sql.default_namespace_name` property. +// +// Spring Data automatically decides the target table name based on a model class name. +// You can also specify a table name by setting `value` parameter. +// +// @Table(schema = "my_app_ns", value = "user") +@Table +public class User { + @Id + public final Long id; + + public final Long groupId; + + // Spring Data automatically decides the target column name based on an instance variable name. + // You can also specify a column name by setting `value` parameter in @Column annotation. + // @Column("name") + public final String name; + + public User(Long id, Long groupId, String name) { + this.id = id; + this.groupId = groupId; + this.name = name; + } +} +``` + +### domain/model/Group + +```java +// This model class corresponds to the following table schema: +// +// create table my_app_ns.group (account_id int, group_type int, balance int, primary key (account_id, group_type)); + +@Table +public class Group { + // This column `account_id` is a part of PRIMARY KEY in ScalarDB SQL + // + // Spring Data JDBC always requires a single @Id annotation while it doesn't allow multiple @Id annotations. + // The corresponding ScalarDB SQL table `group` has a primary key consisting of multiple columns. + // So, Spring Data @Id annotation can't be used in this case, but @Id annotation must be put on any instance variable + // (@Id annotation can be put on `balance` as well.) + @Id + public final Integer accountId; + + // This column `group_type` is also a part of PRIMARY KEY in ScalarDB SQL + public final Integer groupType; + + public final Integer balance; + + public Group(Integer accountId, Integer groupType, Integer balance) { + this.accountId = accountId; + this.groupType = groupType; + this.balance = balance; + } +} +``` + +[This sample implementation](https://github.com/scalar-labs/scalardb-samples/tree/main/spring-data-sample/src/main/java/sample/domain/model) can be used as a reference as well. + +### domain/repository/UserRepository + +```java +@Transactional +@Repository +public interface UserRepository extends ScalarDbRepository { + + // `insert()` and `update()` are automatically enabled with `ScalarDbRepository` (or `ScalarDbTwoPcRepository`). + + // Many APIs of `CrudRepository` and `PagingAndSortingRepository` are automatically enabled. + // https://docs.spring.io/spring-data/commons/docs/3.0.x/api/org/springframework/data/repository/CrudRepository.html + // https://docs.spring.io/spring-data/commons/docs/3.0.x/api/org/springframework/data/repository/PagingAndSortingRepository.html + + // Also, you can prepare complicated APIs with the combination of the method naming conventions. + // https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/#repositories.definition-tuning + + // These APIs use the ScalarDB secondary index + List findByName(String name); + List findTop2ByName(String name); + // Current ScalarDB SQL doesn't support range scan or order using secondary indexes + // List findByNameBetween(String name); + // List findByGroupIdOrderByName(long groupId); + + default void reverseName(long id) { + Optional model = findById(id); + if (model.isPresent()) { + User existing = model.get(); + User updated = + new User( + existing.id, + existing.groupId, + existing.name.reverse()); + update(updated); + } + } + + default void deleteAfterSelect(long id) { + Optional existing = findById(id); + existing.ifPresent(this::delete); + } +} +``` + +### domain/repository/GroupRepository + +```java +@Transactional +@Repository +public interface GroupRepository extends ScalarDbRepository { + + // @Id annotation is put only on Group.accountId, but ScalarDB SQL expects the combination of + // `account_id` and `group_type` columns as the table uses them as a primary key. So `findById()` can't be used. + Optional findFirstByAccountIdAndGroupType(int accountId, int groupType); + + List findByAccountIdAndGroupTypeBetweenOrderByGroupTypeDesc( + int accountId, int groupTypeFrom, int groupTypeTo); + + List findTop2ByAccountIdAndGroupTypeBetween( + int accountId, int groupTypeFrom, int groupTypeTo); + + // `update()` method also depends on @Id annotation as well as `findById()`, + // so users need to write ScalarDB SQL in @Query annotation. + @Modifying + @Query( + "UPDATE \"my_app_ns\".\"group\" SET \"balance\" = :balance \n" + + " WHERE \"my_app_ns\".\"group\".\"account_id\" = :accountId \n" + + " AND \"my_app_ns\".\"group\".\"group_type\" = :groupType \n") + int updateWithAttributes( + @Param("accountId") int accountId, + @Param("groupType") int groupType, + @Param("balance") int balance); + + default void incrementBalance(int accountId, int groupType, int value) { + Optional model = findFirstByAccountIdAndGroupType(accountId, groupType); + model.ifPresent( + found -> + updateWithAttributes( + found.accountId, found.groupType, found.balance + value)); + } + + default void transfer( + int accountIdFrom, int groupTypeFrom, int accountIdTo, int groupTypeTo, int value) { + incrementBalance(accountIdFrom, groupTypeFrom, -value); + incrementBalance(accountIdTo, groupTypeTo, value); + } + + // This method name and signature results in issuing an unexpected SELECT statement and + // results in query failure. It looks a bug of Spring Data... + // + // void deleteByAccountIdAndGroupType(int accountId, int groupType); + + @Modifying + @Query( + "DELETE FROM \"my_app_ns\".\"group\" \n" + + " WHERE \"my_app_ns\".\"group\".\"account_id\" = :accountId \n" + + " AND \"my_app_ns\".\"group\".\"group_type\" = :groupType \n") + int deleteByAccountIdAndGroupType( + @Param("accountId") int accountId, @Param("groupType") int groupType); + + default void deleteByAccountIdAndGroupTypeAfterSelect(int accountId, int groupType) { + Optional entity = findFirstByAccountIdAndGroupType(accountId, groupType); + entity.ifPresent(found -> deleteByAccountIdAndGroupType(accountId, groupType)); + } +} +``` + +[This sample implementation](https://github.com/scalar-labs/scalardb-samples/tree/main/spring-data-sample/src/main/java/sample/domain/repository) can be used as a reference as well. + +## Error handling + +Spring Data JDBC for ScalarDB can throw the following exceptions. + +- com.scalar.db.sql.springdata.exception.ScalarDbTransientException + - This is thrown when a transaction fails due to a transient error + - The transaction should be retried + - This is a subclass of `org.springframework.dao.TransientDataAccessException` and catching the superclass is safer to handle other type of transient errors thrown from Spring Data +- com.scalar.db.sql.springdata.exception.ScalarDbNonTransientException + - This is thrown when a transaction fails due to a non-transient error + - The transaction should not be retried + - This is a subclass of `org.springframework.dao.NonTransientDataAccessException` and catching the superclass is safer to handle other type of non-transient errors thrown from Spring Data +- com.scalar.db.sql.springdata.exception.ScalarDbUnknownTransactionStateException + - This is a subclass of `ScalarDbNonTransientException` and the transaction should not be retried as well + - This is thrown when a transaction commit fails and the final state is unknown + - Whether the transaction is actually committed or not needs to be decided by the application side (e.g. check if the target record is expectedly updated) + +These exceptions include the transaction ID, which can be useful for troubleshooting purposes. + +## Limitations + +### Multiple column PRIMARY KEY + +As you see in the above example, Spring Data JDBC's `@Id` annotation doesn't support multiple columns. So, if a table has a primary key consisting of multiple columns, users can't use the following APIs and may need to write Scalar SQL DB query in `@Query` annotation. + +- `findById()` +- `existsById()` +- `update(T entity)` +- `delete(T entity)` +- `deleteById(ID id)` +- `deleteAllById(Iterable ids)` + +### One-to-many relationships between two entities + +Spring Data JDBC supports one-to-many relationships. But it implicitly deletes and re-creates all the associated child records even if only parent's attributes are changed. This behavior would result in a performance penalty. Additionally, certain use cases of the one-to-many relationship in Spring Data JDBC for ScalarDB fail because of the combination with some limitations of ScalarDB SQL. Considering those concerns and limitations, it's not recommended to use the feature in Spring Data JDBC for ScalarDB. + +For instance, assuming a Bank record contains many Account records, the following implementation fails when calling `BankRepository#update()` + +```java +@Autowired BankRepository bankRepository; + +... + +bankRepository.insert(new Bank(42, "My bank", ImmutableSet.of( + new Account(1, "Alice"), + new Account(2, "Bob"), + new Account(3, "Carol") +))); + +Bank bank = bankRepository.findById(42).get(); +System.out.printf("Bank: " + bank); + +// Fails here as `DELETE FROM "account" WHERE "account"."bank_id" = ?` is implicitly issued by Spring Data JDBC +// while ScalarDB SQL doesn't support DELETE with a secondary index +// (Spring Data JDBC's custom query might avoid these limitations) +bankRepository.update(new Bank(bank.bankId, bank.name + " 2", bank.accounts)); +``` + +## Advanced features + +### Multi-storage transaction + +ScalarDB supports [Multi-storage Transaction](../multi-storage-transactions.mdx), and users can use the feature via Spring Data JDBC for ScalarDB. The following needs to be configured to use the feature. + +#### spring.datasource.url +Here is a sample datasource URL assuming there are two namespaces "north" and "south" that manage data with MySQL and PostgreSQL respectively. +``` +spring.datasource.url=jdbc:scalardb:\ +?scalar.db.sql.connection_mode=direct\ +&scalar.db.storage=multi-storage\ +&scalar.db.multi_storage.storages=mysql,postgresql\ +&scalar.db.multi_storage.namespace_mapping=north:mysql,south:postgresql\ +&scalar.db.multi_storage.default_storage=postgresql\ +&scalar.db.multi_storage.storages.mysql.storage=jdbc\ +&... +``` + +#### @Table annotation on model classes + +- `schema` parameter: multi-storage mapping key name (`scalar.db.multi_storage.namespace_mapping`) +- `value` parameter: actual table name + +```java + @Table(schema = "north", value = "account") + public class NorthAccount { +``` + +### Retry + +#### Retry with Spring Retry + +Spring Data JDBC for ScalarDB could throw exceptions when concurrent transactions conflict. Users need to take care of those exceptions by retrying the operations. [Spring Retry](https://github.com/spring-projects/spring-retry) provides some functionalities for retry. Also in Spring Data JDBC for ScalarDB, Spring Retry would be helpful to make retry handling simpler and easier. This section introduces how to use Spring Retry. + +##### Dependencies + +The following dependencies need to be added to your project. + +```gradle +dependencies { + implementation "org.springframework.boot:spring-boot-starter:${springBootVersion}" + implementation "org.springframework.boot:spring-boot-starter-aop:${springBootVersion}" + implementation "org.springframework.retry:spring-retry:${springRetryVersion}" +} +``` + +##### Annotation + +`@EnableRetry` annotation needs to be added in the JVM application. +```java +@SpringBootApplication +@EnableScalarDbRepositories +@EnableRetry +public class MyApp { +``` + +`@Retryable` annotation makes Spring Data repository class or method automatically retry a failed operation. Spring Data JDBC for ScalarDB can throw a transient error exception, so it's highly recommended to specify `org.springframework.dao.TransientDataAccessException` as a target class in the annotation. Also, backoff and max attempts can be configured in the annotation like this: + +```java + @Transactional + @Retryable( + include = TransientDataAccessException.class, + maxAttempts = 4, + backoff = @Backoff(delay = 500, maxDelay = 2000, multiplier = 2)) + default void insertWithRetry(Player player) { + insert(player); + } +``` + +With `@Recover` annotation, retry-exhausted failure will be automatically recovered by a specified method. + +```java + @Transactional + @Retryable(include = TransientDataAccessException.class, + recover = "recoverInsert") + default void insertWithRetryAndRecover(Player player) { + insert(player); + } + + @Transactional + @Recover + default void recoverInsert(Throwable throwable, Player player) throws Throwable { + Optional existing = findById(player.id); + if (!existing.isPresent()) { + throw throwable; + } + logger.info( + "Found an existing record {}. Updating it with a new record {}", existing.get(), player); + + update(player); + } +``` + +#### Retry with other retry library + +There are other options available for retrying transactions, such as Spring Retry's RetryTemplate or Resilience4j. Feel free to choose and use your preferred retry library. + +### Two-phase commit transaction + +ScalarDB supports [Two-phase commit transaction](../two-phase-commit-transactions.mdx), and users can use the feature via Spring Data JDBC for ScalarDB. The following configurations are needed. + +#### spring.datasource.url + +- `scalar.db.sql.default_transaction_mode` property: `two_phase_commit_transaction` + +```console +spring.datasource.url=jdbc:scalardb:\ +?scalar.db.sql.connection_mode=direct\ +&scalar.db.contact_points=jdbc:mysql://localhost:3306/my_app_ns\ +&...\ +&scalar.db.sql.default_transaction_mode=two_phase_commit_transaction +``` + +#### Configuration of Spring Data transaction manager + +Spring Data JDBC for ScalarDB provides a custom Spring Data transaction manager to achieve 2PC transactions. You need to configure either of the following annotations to enable the custom transaction manager. + +- Set `transactionManager` parameter of all the `@Transactional` to `scalarDbSuspendableTransactionManager` +- Set `transactionManagerRef` parameter of the `@EnableScalarDbRepositories` to `scalarDbSuspendableTransactionManager` + +#### Repository classes + +##### APIs + +Spring Data JDBC for ScalarDB supports 2 types of APIs for 2PC transaction. One is primitive APIs and the other is high level API. + +###### Primitive 2PC APIs + +`ScalarDbTwoPcRepository` is an extension of `ScalarDbRepository` and it has the following APIs that correspond to the same name methods in ScalarDB and users can use them to build custom repository methods for 2PC transaction. + +- begin() + - returns an auto-generated transaction ID +- prepare() +- validate() +- suspend() +- commit() +- join(`transactionId`) +- resume(`transactionId`) + +All in-flight operations are rolled back when any exception is thrown from Spring Data repository method. + +See [How to execute Two-phase Commit Transactions](../two-phase-commit-transactions.mdx#how-to-execute-two-phase-commit-transactions) for details. + +```java +@Transactional(transactionManager = "scalarDbSuspendableTransactionManager") +@Repository +public interface TwoPcPlayerRepository extends ScalarDbTwoPcRepository { + + Logger logger = LoggerFactory.getLogger(TwoPcPlayerRepository.class); + + // Either of twoPcJoinAndInsert() or twoPcBeginAndInsert() can be used to start a transaction + default void twoPcJoinAndInsert(String txId, Player player) throws SQLException { + join(txId); + insert(player); + suspend(); + } + + default String twoPcBeginAndInsert(String id, Player player) throws SQLException { + String txId = begin(); + insert(player); + suspend(); + return txId; + } + + default void twoPcPrepare(String txId) throws SQLException { + resume(txId); + prepare(); + suspend(); + } + + default void twoPcValidate(String txId) throws SQLException { + resume(txId); + validate(); + suspend(); + } + + default void twoPcCommit(String txId) throws SQLException { + resume(txId); + commit(); + } +``` + +###### High level 2PC API + +The above primitive APIs are powerful and make it possible to explicitly control 2PC transaction operations in flexible and fine-grained ways. On the other hand, users need to consider which APIs to call in a proper order when using the APIs. Especially coordinator side operations for local state and remote service calls would be easily complicated. + +`ScalarDbTwoPcRepository` also provides some user-friendly APIs called high-level APIs to cover common use cases. With these APIs, you can develop your microservice applications more easily and securely. + +For the development of coordinator service in a microservice, `ScalarDbTwoPcRepository` provides `executeTwoPcTransaction` API that implicitly executes 2PC related operations in the following order. By using the API, you don’t need to think about how and when to execute transactional operations. + +- Start a local transaction with a global transaction ID +- Execution phase: Local and remote CRUD operations (*) +- Prepare phase: Local and remote prepare operations (**) in parallel +- Validation phase: Local and remote validation operations (**) in parallel + - This is needed only if `scalar.db.consensus_commit.isolation_level` is `SERIALIZABLE` and `scalar.db.consensus_commit.serializable_strategy` is `EXTRA_READ` +- Commit phase: Local commit operation is first executed. Remote commit operations are executed (**) in parallel after the local commit operation succeeded +- (If any operation except for remote commit operation fails) rollback phase: Local and remote rollback operations (**) in parallel + +(* This implementation of local and remote operation callbacks is injected by users)\ +(** This implementation of remote operation callbacks is injected by users) + +Rollback operations for local and remote participants will be executed when an exception is thrown from any operation. + +As for the error handling of `executeTwoPcTransaction()`, + +- The following exceptions can be thrown from the API + - `ScalarDbTransientException` + - Users should retry the 2PC transaction operations from the beginning when this exception is thrown + - `ScalarDbNonTransientException` + - `ScalarDbUnknownTransactionStateException` + - Whether the 2PC transaction is actually committed or not needs to be decided by the application side +- The exceptions contain the 2PC global transaction ID. It should be useful for trouble shootings + +As for the implementations of Execution phase operations (in local and remote participants) and remote operations of Prepare/Validation/Commit/Rollback phases that are passed by users, those callbacks need to throw either of the exceptions when it fails: + +- `ScalarDbTransientException` when any transient issue happens including network disconnection and database transaction conflict +- `ScalarDbNonTransientException` when any non-transient issue happens including authentication error and permission error +- `ScalarDbUnknownTransactionStateException` when any exception that contains `UnknownTransactionStatusException` as a cause +- Other exceptions thrown from the callbacks are treated as `ScalarDbTransientException` + +For the development of participant service in a microservice, `ScalarDbTwoPcRepository` provides the following APIs. By using the API, you don’t need to think about how and when to join, resume and suspend a transaction in details. + +- `joinTransactionOnParticipant` + - Join the transaction, execute the CRUD operations and suspend the transaction on the participant service. This API should be called first, and then `prepareTransactionOnParticipant` and following APIs are supposed to be called. +- `resumeTransactionOnParticipant` + - Resume the transaction, execute the CRUD operations and suspend the transaction on the participant service. This API can be called after `joinTransactionOnParticipant` before `prepareTransactionOnParticipant` if needed. +- `prepareTransactionOnParticipant` + - Prepare the transaction and suspend the transaction on the participant service. This API should be called after `joinTransactionOnParticipant`, and then `validateTransactionOnParticipant` and following APIs are supposed to be called. +- `validateTransactionOnParticipant` + - Validate the transaction and suspend the transaction on the participant service. This API should be called after `prepareTransactionOnParticipant`, and then `commitTransactionOnParticipant` or `rollbackTransactionOnParticipant` is supposed to be called. + - This is needed only if `scalar.db.consensus_commit.isolation_level` is `SERIALIZABLE` and `scalar.db.consensus_commit.serializable_strategy` is `EXTRA_READ` +- `commitTransactionOnParticipant` + - Commit the transaction on the participant service. This API should be called after `prepareTransactionOnParticipant` or `validateTransactionOnParticipant, depending on the transaction manager configurations. +- `rollbackTransactionOnParticipant` + - Rollback the transaction on the participant service. This API should be called after `prepareTransactionOnParticipant` or `validateTransactionOnParticipant, depending on the transaction manager configurations. + +With the high-level 2PC APIs of Spring Data JDBC for ScalarDB, you can focus on the business logic by hiding complicated transaction operations inside the APIs as follows: + +**Coordinator service** + +```java + @Autowired private AccountRepository accountRepository; + private final StockService stockService = ...; + private final NotificationService notificationService = ...; + private final List remotePrepareCommitOpsList = + Arrays.asList( + RemotePrepareCommitPhaseOperations.createSerializable( + stockService::prepareTransaction, + stockService::validateTransaction, + stockService::commitTransaction, + stockService::rollbackTransaction), + RemotePrepareCommitPhaseOperations.createSerializable( + notificationService::prepareTxn, + notificationService::validateTxn, + notificationService::commitTxn, + notificationService::rollbackTxn)); +``` + +```java + private Result> executeTwoPcTransactionUsingHighLevelApi( + Account account, String itemName, int itemPrice, String notificationEventName) { + return accountRepository.executeTwoPcTransaction( + // CRUD operations for local and remote participants in execution phase. + txId -> { + // [local] Read the account's balance + Optional stored = accountRepository.findById(account.id); + if (!stored.isPresent()) { + // Cancel the transaction if the account doesn't exist. + // No need to retry. + throw new ScalarDbNonTransientException( + "The local state doesn't meet the condition. Aborting this transaction"); + } + // [remote] Start a transaction with the transaction ID, + // read the item information and decrement the count + Optional price = stockService.purchaseItem(txId, account.id, itemName); + // [remote] Start a transaction with the transaction ID, + // read the notification and remove it + Optional notification = + notificationService.getNotification(txId, account.id, notificationEventName); + if (price.isPresent() && notification.isPresent()) { + int currentBalance = stored.get().balance - price.get(); + if (currentBalance < 0) { + // Cancel the transaction if the global state doesn't meet the condition. + // No need to retry. + throw new ScalarDbNonTransientException( + "The state of local and remote participants doesn't meet the condition. Aborting this transaction"); + } + // [local] Decrease the account's balance for the item + accountRepository.update(new Account(account.id, currentBalance)); + return Pair.of(currentBalance, notification.get()); + } + // Cancel the transaction if the global state doesn't meet the condition. + // No need to retry. + throw new ScalarDbNonTransientException( + "The remote state doesn't meet the condition. Aborting this transaction"); + }, + // Remote operations for Prepare/Validate/Commit/Rollback + remotePrepareCommitOpsList); + } +``` + +```java + RetryTemplate retryTemplate = + new RetryTemplateBuilder() + .retryOn(TransientDataAccessException.class) + .exponentialBackoff(500, 2.0, 8000) + .maxAttempts(8) + .withListener( + new RetryListenerSupport() { + @Override + public void onError(RetryContext context, RetryCallback callback, Throwable throwable) { + if (throwable instanceof ScalarDbUnknownTransactionStateException) { + // Report an exception occurred that requires special treatments + reportToDevelopers( + String.format("Failed to process a 2PC transaction (%s). The final transaction status is unknown. Please check current application status", + ((ScalarDbUnknownTransactionStateException) throwable).getTransactionId()), throwable); + } + }}) + .build(); + + Result> result = + retryTemplate.execute(context -> + executeTwoPcTransactionUsingHighLevelApi(account, itemName, itemPrice, notificationEventName)); +``` + +[This sample implementation](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/order-service/src/main/java/sample/order/OrderService.java) can be used as a reference as well. + +**Participant service** + +```java +@RestController +public class StockController { + @Autowired private StockRepository stockRepository; + + @PostMapping("/purchaseItem") + public Optional purchaseItem( + @RequestParam("transactionId") String transactionId, + @RequestParam("accountId") int accountId, + @RequestParam("itemName") String itemName) { + return stockRepository.joinTransactionOnParticipant(txId, () -> { + Optional item = stockRepository.findById(itemName); + + ... + + return Optional.of(item.price); + }); + } + + @PostMapping("/prepareTransaction") + public void prepareTransaction(@RequestParam("transactionId") String transactionId) { + return stockRepository.prepareTransactionOnParticipant(txId); + } + + @PostMapping("/validateTransaction") + public void validateTransaction(@RequestParam("transactionId") String transactionId) { + return stockRepository.validateTransactionOnParticipant(txId); + } + + @PostMapping("/commitTransaction") + public void commitTransaction(@RequestParam("transactionId") String transactionId) { + return stockRepository.commitTransactionOnParticipant(txId); + } + + @PostMapping("/rollbackTransaction") + public void rollbackTransaction(@RequestParam("transactionId") String transactionId) { + return stockRepository.rollbackTransactionOnParticipant(txId); + } +} +``` + +[This sample implementation](https://github.com/scalar-labs/scalardb-samples/blob/main/spring-data-microservice-transaction-sample/customer-service/src/main/java/sample/customer/CustomerService.java) uses gRPC not REST API, but it can be used as a reference as well. + +#### How to use both 2PC and normal transaction modes in a JVM application + +In most cases, only one of the 2PC and normal transaction modes is supposed to be used in an application. But there might be some use cases for using both transaction modes. For instance, assuming a service that is used as a participant in 2PC also has some APIs that are directly called by other services or clients without 2PC protocol. In this case, developers would want to simply use normal transaction mode for the APIs not used in 2PC. + +To achieve this use case, different `scalar.db.sql.default_transaction_mode` parameters for 2PC and normal transaction modes need to be passed to Spring Data JDBC framework via `spring.datasource.url` property. Spring Data JDBC doesn't provide a simple way to use multiple datasource configurations, though. But with some custom configuration classes, users can use both 2PC and normal transaction modes in a JVM application using multiple datasource configurations. + +#### Limitations + +##### `@Transactional` methods don't implicitly call `commit()` + +In microservice applications with ScalarDB, commits must be explicitly invoked by a coordinator service, not be locally triggered by the Spring Data transaction framework when exiting `@Transactional` methods. The `@Transactional(transactionManager = "scalarDbSuspendableTransactionManager")` annotation prevents such local commits. + +This extended behavior may confuse developers who expect `@Transactional` methods to implicitly commit transactions. + +For instance, assuming you want to use the `@Transactional` annotation on methods of a service class, the following code works in the **normal** transaction mode. + +```java +@Service +public class SampleService { + + ... + + // For the normal transaction mode + @Transactional + // For the 2PC transaction mode + // @Transactional(transactionManager = "scalarDbSuspendableTransactionManager") + public void repayment(int customerId, int amount) { + Customer customer = customerRepository.getById(customerId); + + int updatedCreditTotal = customer.creditTotal - amount; + + // Check if over repayment or not + if (updatedCreditTotal < 0) { + throw new RuntimeException( + String.format( + "Over repayment. creditTotal:%d, payment:%d", customer.creditTotal, amount)); + } + + // Reduce credit_total for the customer + customerRepository.update(customer.withCreditTotal(updatedCreditTotal)); + } +} +``` + +However, that code doesn't work in the 2PC transaction mode even with `transactionManager = "scalarDbSuspendableTransactionManager"`. Instead, use `ScalarDbTwoPcRepository.executeOneshotOperations()` as follows. + +```java +@Service +public class SampleService { + + ... + + public void repayment(int customerId, int amount) { + customerRepository.executeOneshotOperations(() -> { + Customer customer = customerRepository.getById(customerId); + + int updatedCreditTotal = customer.creditTotal - amount; + + // Check if over repayment or not + if (updatedCreditTotal < 0) { + throw new RuntimeException( + String.format( + "Over repayment. creditTotal:%d, payment:%d", customer.creditTotal, amount)); + } + + // Reduce credit_total for the customer + customerRepository.update(customer.withCreditTotal(updatedCreditTotal)); + + return null; + }); + } +} +``` + +## Troubleshooting + +This section describes methods to troubleshoot errors that may occur when using Spring Data JDBC. + +### `A constructor parameter name must not be null to be used with Spring Data JDBC` runtime error + +The runtime error `A constructor parameter name must not be null to be used with Spring Data JDBC` may occur when using Spring Boot 3. To work around this issue, you can pass the `-parameters` option to `javac` as follows: + +```gradle + compileJava { + options.compilerArgs << '-parameters' + } +``` + +## Sample application + +You can see the following sample applications that use Spring Data JDBC for ScalarDB. It only serves as a reference and does not necessarily meet production code standards. + +- [Getting Started with ScalarDB Cluster SQL via Spring Data JDBC for ScalarDB](../scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc.mdx) +- [Sample application of Spring Data JDBC for ScalarDB with Multi-storage Transactions](../scalardb-samples/spring-data-multi-storage-transaction-sample/README.mdx) +- [Sample application of Spring Data JDBC for ScalarDB with Microservice Transactions](../scalardb-samples/spring-data-microservice-transaction-sample/README.mdx) + +## How it works + +In order to use Spring Data JDBC for ScalarDB, the following features are implemented in the integration + +- Map `jdbc:scalardb` protocol in JDBC Connection URL to a Spring Data JDBC dialect class for ScalarDB SQL + - This feature is handled by ScalarDbDialect and ScalarDbDialectProvider +- Prevent users from using some APIs of Spring Data Repository classes (CrudRepository and PagingAndSortingRepository) unsupported in ScalarDB SQL + - This feature is handled by ScalarDbJdbcAggregateTemplate which is a bit lower layer Spring Data JDBC component used by Repository classes +- Make Spring Data Repository classes implicitly use the custom JdbcAggregateTemplate (ScalarDbJdbcAggregateTemplate) + - This feature is handled by ScalarDbJdbcRepositoryFactory and ScalarDbJdbcRepositoryFactoryBean +- Add explicit `insert()` and `update()` APIs to Spring Data Repository classes instead of bundled `save()` which depends on autoincrement ID feature in underlying databases while ScalarDB SQL doesn't support it + - This feature is handled by ScalarDbRepository (or ScalarDbTwoPcRepository) and ScalarDbRepositoryImpl +- Enable all the above features in Spring framework manner + - This configuration is handled by + - some Java classes in `com.scalar.db.sql.springdata` + - `@EnableScalarDbRepositories` annotation + - `resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports` + - `resources/META-INF/spring.factories` + +## References + +- [Spring Data JDBC - Reference Documentation](https://docs.spring.io/spring-data/jdbc/docs/3.0.x/reference/html/) +- [ScalarDB JDBC Guide](jdbc-guide.mdx) +- [Javadoc for Spring Data JDBC for ScalarDB](https://javadoc.io/doc/com.scalar-labs/scalardb-sql-spring-data/3.15.4/index.html) diff --git a/versioned_docs/version-3.15/scalardb-sql/sql-api-guide.mdx b/versioned_docs/version-3.15/scalardb-sql/sql-api-guide.mdx new file mode 100644 index 00000000..d2203aad --- /dev/null +++ b/versioned_docs/version-3.15/scalardb-sql/sql-api-guide.mdx @@ -0,0 +1,377 @@ +--- +tags: + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB SQL API Guide + +import JavadocLink from '/src/theme/JavadocLink.js'; + +This guide describes how to use ScalarDB SQL API. + +## Add ScalarDB SQL API to your project + +To add the dependencies on ScalarDB SQL API by using Gradle, use the following, replacing `` with the versions of ScalarDB SQL API and the related library, respectively, that you are using: + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-sql:' + implementation 'com.scalar-labs:scalardb-cluster-java-client-sdk:' +} +``` + +To add the dependencies by using Maven, use the following, replacing `...` with the version of ScalarDB SQL API that you are using: + +```xml + + + com.scalar-labs + scalardb-sql + ... + + + com.scalar-labs + scalardb-cluster-java-client-sdk + ... + + +``` + +## SqlSessionFactory + +In ScalarDB SQL API, you execute all operations through a `SqlSession` instance, which is instantiated with `SqlSessionFactory`. +This section explains how to use them. + +Before explaining `SqlSessionFactory`, we start with the explanation for Connection mode and Transaction mode. + +### Transaction mode + +Also, ScalarDB SQL offers two transaction modes: *Transaction* mode and *Two-phase Commit Transaction* mode. +Transaction mode exposes only `commit` interface to users and runs two-phase commit behind the scene, while Two-phase Commit Transaction mode exposes two-phase commit style interfaces (`prepare` and `commit`) to users. + +You can specify the default transaction mode in your configuration file or when you build `SqlSessionFactory`. +And you also can change it with the `setTransactionMode()` method of `SqlSession`. + +### Build SqlSessionFactory + +You can build `SqlSessionFactory` with a properties file as follows: + +```java +SqlSessionFactory sqlSessionFactory = SqlSessionFactory.builder() + .withPropertiesFile("") + // If you need to set custom properties, you can specify them with withProperty() or withProperties() + .withProperty("", "") + .build(); +``` + +Please see [ScalarDB Cluster SQL client configurations](../scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api.mdx#scalardb-cluster-sql-client-configurations) for the details of the configurations. + +### Get a SqlSession instance + +You can get a `SqlSession` instance with `SqlSessionFactory` as follows: + +```java +SqlSession sqlSession = sqlSessionFactory.createSqlSession(); +``` + +Note that `SqlSession` is not thread-safe. +Please don't use it from multiple threads at the same time. + +#### Close a SqlSession instance + +Once all operations are done with a `SqlSession` instance, you should close the SqlSession instance: + +```java +sqlSession.close(); +``` + +### Close a SqlSessionFactory instance + +`sqlSessionFactory` should also be closed once it's no longer needed: + +```java +sqlSessionFactory.close(); +``` + +## Execute SQLs + +You can execute a SQL with `SqlSession` as follows: + +```java +ResultSet resultSet = sqlSession.execute(""); +``` + +You can also execute a `Statement` object with `SqlSession` as follows: + +```java +// Build a statement +Statement statement = StatementBuilder....; + +// Execute the statement +ResultSet resultSet = sqlSession.execute(statement); +``` + +`Statement` objects can be built by `StatementBuilder` that has factory methods for corresponding SQLs. For more details, see the page in the Javadoc and [ScalarDB SQL Grammar](grammar.mdx). + +### Handle ResultSet objects + +As the result of the SQL execution, `SqlSession` returns a `ResultSet` object. +Here, we describe how to handle `ResultSet` objects. + +If you want to get results one by one from the `ResultSet` object, you can use the `one()` method as follows: +```java +Optional record = resultSet.one(); +``` + +Or, if you want to get results all at once as a `List`, you can use the `all()` method as follows: +```java +List records = resultSet.all(); +``` + +Also, as `ResultSet` implements `Iterable`, you can use it in a for-each loop as follows: + +```java +for (Record record : resultSet) { + ... +} +``` + +If you want to get the metadata of the `ResultSet` object, you can use the `getColumnDefinitions()` method as follows: + +```java +ColumnDefinitions columnDefinitions = resultSet.getColumnDefinitions(); +``` + +For more details, see the page in the Javadoc. + +### Handle Record objects + +As mentioned, a `ResultSet` object returns `Record` objects that represent records of the database. + +You can get a column value of a result with `getXXX("")` or `getXXX()` methods (XXX is a type name) as follows: + +```java +// Get a BOOLEAN value of a column +boolean booleanValueGottenByName = record.getBoolean(""); +boolean booleanValueGottenByIndex = record.getBoolean(); + +// Get an INT value of a column +int intValueGottenByName = record.getInt(""); +int intValueGottenByIndex = record.getInt(); + +// Get a BIGINT value of a column +long bigIntValueGottenByName = record.getBigInt(""); +long bigIntValueGottenByIndex = record.getBigInt(); + +// Get a FLOAT value of a column +float floatValueGottenByName = record.getFloat(""); +float floatValueGottenByIndex = record.getFloat(); + +// Get a DOUBLE value of a column +double doubleValueGottenByName = record.getDouble(""); +double doubleValueGottenByIndex = record.getDouble(); + +// Get a TEXT value of a column +String textValueGottenByName = record.getText(""); +String textValueGottenByIndex = record.getText(); + +// Get a BLOB value of a column (as a ByteBuffer) +ByteBuffer blobValueGottenByName = record.getBlob(""); +ByteBuffer blobValueGottenByIndex = record.getBlob(); + +// Get a BLOB value of a column as a byte array +byte[] blobValueAsBytesGottenByName = record.getBlobAsBytes(""); +byte[] blobValueAsBytesGottenByIndex = record.getBlobAsBytes(); + +// Get a DATE value of a column as a LocalDate +LocalDate dateValueGottenByName = record.getDate(""); +LocalDate dateValueGottenByName = record.getDate(); + +// Get a TIME value of a column as a LocalTime +LocalTime timeValueGottenByName = record.getTime(""); +LocalTime timeValueGottenByName = record.getTime(); + +// Get a TIMESTAMP value of a column as a LocalDateTime +LocalDateTime timestampValueGottenByName = record.getTimestamp(""); +LocalDateTime timestampValueGottenByName = record.getTimestamp(); + +// Get a TIMESTAMPTZ value of a column as an Instant +Instant timestampTZValueGottenByName = record.getTimestampTZ(""); +Instant timestampTZValueGottenByName = record.getTimestampTZ(); +``` + +And if you need to check if a value of a column is null, you can use the `isNull("")` or `isNull()` method. + +``` java +// Check if a value of a column is null +boolean isNullGottenByName = record.isNull(""); +boolean isNullGottenByIndex = record.isNull(); +``` + +For more details, see the page of the Javadoc. + +### Prepared Statements + +You can use `PreparedStatement` for queries that are executed multiple times in your application: + +```java +PreparedStatement preparedStatement = sqlSession.prepareStatement(""); +ResultSet result = preparedStatement.execute(); +``` + +If you execute the same query a second time or later, the cached pre-parsed statement object is used. +Thus, you can gain a performance advantage with `PreparedStatement` when you execute the query multiple times. +If you execute a query only once, a prepared statement is inefficient because it requires extra processing. +Consider using the `sqlSession.execute()` method instead in that case. + +Also, you can use `PreparedStatement` with bind parameters. +Parameters can be either positional or named: + +```java +// Positional parameters +PreparedStatement preparedStatement1 = + sqlSession.prepareStatement("INSERT INTO tbl (c1, c2) VALUES (?, ?)"); + +// Named parameters +PreparedStatement preparedStatement2 = + sqlSession.prepareStatement("INSERT INTO tbl (c1, c2) VALUES (:a, :b)"); +``` + +You can set parameters first and execute it: + +```java +// Positional setters +preparedStatement1 + .setInt(0, 10) + .setText(1, "value") + .execute(); + +// Named setters +preparedStatement2 + .setInt("a", 10) + .setText("b", "value") + .execute(); +``` + +For more details, see the page of the Javadoc. + +## Execute transactions + +In ScalarDB SQL, you can execute DML statements (SELECT/INSERT/UPDATE/DELETE) only in transactions. +So before executing DML statements, you must begin a transaction. + +Note that you cannot execute statements other than DML statements transactionally. +So even if you execute a non-DML statement after beginning a transaction, it is executed immediately, and it doesn't affect the transaction you have begun. + +This section describes how to execute a transaction for each transaction mode: Transaction mode and Two-phase Commit Transaction mode. + +### Transaction Mode + +An example code for Transaction mode is as follows: + +```java +try { + // Begin a transaction + sqlSession.begin(); + + // Execute statements (SELECT/INSERT/UPDATE/DELETE) in the transaction + ... + + // Commit the transaction + sqlSession.commit(); +} catch (UnknownTransactionStatusException e) { + // If you catch `UnknownTransactionStatusException`, it indicates that the status of the + // transaction, whether it has succeeded or not, is unknown. In such a case, you need to check if + // the transaction is committed successfully or not and retry it if it failed. How to identify a + // transaction status is delegated to users +} catch (SqlException e) { + // For other exceptions, you can try retrying the transaction + + // Rollback the transaction + sqlSession.rollback(); + + // For `TransactionRetryableException`, you can basically retry the transaction. However, for + // the other exceptions, the transaction may still fail if the cause of the exception is + // nontransient. For such a case, you need to limit the number of retries and give up retrying +} +``` + +If you catch `UnknownTransactionStatusException`, it indicates that the status of the transaction, whether it has succeeded or not, is unknown. +In such a case, you need to check if the transaction is committed successfully or not and retry it if it fails. +How to identify a transaction status is delegated to users. +You may want to create a transaction status table and update it transactionally with other application data so that you can get the status of a transaction from the status table. + +If you catch another exception, you can try retrying the transaction. +For `TransactionRetryableException`, you can basically retry the transaction. +However, for the other exceptions, the transaction may still fail if the cause of the exception is nontransient. +For such a case, you need to limit the number of retries and give up retrying. + +### Two-phase Commit Transaction Mode + +Before reading this, please read [this document](../two-phase-commit-transactions.mdx) to learn the concept of Two-phase commit transactions. + +To begin a transaction for a coordinator, you can do as follows: + +```java +String transactionId = sqlSession.begin(); +``` + +And to join a transaction for participants, you can do as follows: + +```java +sqlSession.join(transactionId); +``` + +An example code of Two-phase Commit Transaction mode is as follows: + +```java +try { + // Begin a transaction + sqlSession.begin(); + + // Execute statements (SELECT/INSERT/UPDATE/DELETE) in the transaction + ... + + // Prepare the transaction + sqlSession.prepare(); + + // Validate the transaction + sqlSession.validate(); + + // Commit the transaction + sqlSession.commit(); +} catch (UnknownTransactionStatusException e) { + // If you catch `UnknownTransactionStatusException` when committing the transaction, it + // indicates that the status of the transaction, whether it has succeeded or not, is unknown. + // In such a case, you need to check if the transaction is committed successfully or not and + // retry it if it failed. How to identify a transaction status is delegated to users +} catch (SqlException e) { + // For other exceptions, you can try retrying the transaction + + // Rollback the transaction + sqlSession.rollback(); + + // For `TransactionRetryableException`, you can basically retry the transaction. However, for + // the other exceptions, the transaction may still fail if the cause of the exception is + // nontransient. For that case, you need to limit the number of retries and give up retrying +} +``` + +The exception handling is the same as Transaction mode. + +## Get Metadata + +You can get metadata with the `SqlSession.getMetadata()` method as follows: + +```java +Metadata metadata = sqlSession.getMetadata(); +``` + +For more details, see the page of the Javadoc. + +## References + +- [ScalarDB SQL Grammar](grammar.mdx) +- [Two-phase Commit Transactions](../two-phase-commit-transactions.mdx) +- [Javadoc for ScalarDB SQL](https://javadoc.io/doc/com.scalar-labs/scalardb-sql/3.15.4/index.html) diff --git a/versioned_docs/version-3.15/schema-loader-import.mdx b/versioned_docs/version-3.15/schema-loader-import.mdx new file mode 100644 index 00000000..90c8ee85 --- /dev/null +++ b/versioned_docs/version-3.15/schema-loader-import.mdx @@ -0,0 +1,289 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +You might want to use ScalarDB (e.g., for database-spanning transactions) with your existing databases. In that case, you can import those databases under the ScalarDB control using ScalarDB Schema Loader. ScalarDB Schema Loader automatically adds ScalarDB-internal metadata columns in each existing table and metadata tables to enable various ScalarDB functionalities including transaction management across multiple databases. + +## Before you begin + +:::warning + +You should carefully plan to import a table to ScalarDB in production because it will add transaction metadata columns to your database tables and the ScalarDB metadata tables. In this case, there would also be several differences between your database and ScalarDB, as well as some limitations. + +::: + +### What will be added to your databases + +- **ScalarDB metadata tables:** ScalarDB manages namespace names and table metadata in a namespace (schema or database in underlying databases) called 'scalardb'. +- **Transaction metadata columns:** The Consensus Commit transaction manager requires metadata (for example, transaction ID, record version, and transaction status) stored along with the actual records to handle transactions properly. Thus, this tool adds the metadata columns if you use the Consensus Commit transaction manager. + +:::note + +This tool only changes database metadata. Thus, the processing time does not increase in proportion to the database size and usually takes only several seconds. + +::: + +### Requirements + +- [JDBC databases](./requirements.mdx#relational-databases), except for SQLite, can be imported. +- Each table must have primary key columns. (Composite primary keys can be available.) +- Target tables must only have columns with supported data types. For details, see [Data-type mapping from JDBC databases to ScalarDB](#data-type-mapping-from-jdbc-databases-to-scalardb)). + +### Set up Schema Loader + +To set up Schema Loader for importing existing tables, see [Set up Schema Loader](./schema-loader.mdx#set-up-schema-loader). + +## Run Schema Loader for importing existing tables + +You can import an existing table in JDBC databases to ScalarDB by using the `--import` option and an import-specific schema file. To import tables, run the following command, replacing the contents in the angle brackets as described: + +```console +java -jar scalardb-schema-loader-.jar --config -f --import +``` + +- ``: Version of ScalarDB Schema Loader that you set up. +- ``: Path to a properties file for ScalarDB. For a sample properties file, see [`database.properties`](https://github.com/scalar-labs/scalardb/blob/master/conf/database.properties). +- ``: Path to an import schema file. For a sample, see [Sample import schema file](#sample-import-schema-file). + +If you use the Consensus Commit transaction manager after importing existing tables, run the following command separately, replacing the contents in the angle brackets as described: + +```console +java -jar scalardb-schema-loader-.jar --config --coordinator +``` + +## Sample import schema file + +The following is a sample schema for importing tables. For the sample schema file, see [`import_schema_sample.json`](https://github.com/scalar-labs/scalardb/blob/master/schema-loader/sample/import_schema_sample.json). + +```json +{ + "sample_namespace1.sample_table1": { + "transaction": true, + "override-columns-type": { + "c3": "TIME", + "c5": "TIMESTAMP" + } + }, + "sample_namespace1.sample_table2": { + "transaction": true + }, + "sample_namespace2.sample_table3": { + "transaction": false + } +} +``` + +The import table schema consists of a namespace name, a table name, a `transaction` field, and an optional `override-columns-type` field: +- The `transaction` field indicates whether or not the table will be imported for transactions. If you set the `transaction` field to `true` or don't specify the `transaction` field, this tool will create a table with transaction metadata, if needed. If you set the `transaction` field to `false`, this tool will import a table without adding transaction metadata (that is, for a table using the [Storage API](run-non-transactional-storage-operations-through-primitive-crud-interface.mdx)). +- The `override-columns-type` field indicates the columns for which you wish to override the default data-type mapping. This field is optional and only needs to be set with the columns requiring a type override. + +## Data-type mapping from JDBC databases to ScalarDB + +The following table shows the supported data types in each JDBC database and their mapping to the ScalarDB data types. Select your database and check if your existing tables can be imported. + + + + | MySQL | ScalarDB | Notes | + |--------------|-------------------------------------|---------------------------------------------------------------------------------------------------------------------| + | bigint | BIGINT | See warning [1](#1) below. | + | binary | BLOB | | + | bit | BOOLEAN | | + | blob | BLOB | See warning [2](#2) below. | + | char | TEXT | See warning [2](#2) below. | + | date | DATE | | + | datetime | TIMESTAMP (default) and TIMESTAMPTZ | When importing as TIMESTAMPTZ, ScalarDB will assume the data to be on the UTC time zone. See warning [6](#6) below. | + | double | DOUBLE | | + | float | FLOAT | | + | int | INT | | + | int unsigned | BIGINT | See warning [2](#2) below. | + | integer | INT | | + | longblob | BLOB | | + | longtext | TEXT | | + | mediumblob | BLOB | See warning [2](#2) below. | + | mediumint | INT | See warning [2](#2) below. | + | mediumtext | TEXT | See warning [2](#2) below. | + | smallint | INT | See warning [2](#2) below. | + | text | TEXT | See warning [2](#2) below. | + | time | TIME | | + | timestamp | TIMESTAMPTZ | | + | tinyblob | BLOB | See warning [2](#2) below. | + | tinyint | INT | See warning [2](#2) below. | + | tinyint(1) | BOOLEAN | | + | tinytext | TEXT | See warning [2](#2) below. | + | varbinary | BLOB | See warning [2](#2) below. | + | varchar | TEXT | See warning [2](#2) below. | + + Data types not listed above are not supported. The following are some common data types that are not supported: + + - bigint unsigned + - bit(n) (n > 1) + - decimal + - enum + - geometry + - json + - numeric + - set + - year + + + | PostgreSQL/YugabyteDB | ScalarDB | Notes | + |--------------------------|-------------|----------------------------| + | bigint | BIGINT | See warning [1](#1) below. | + | boolean | BOOLEAN | | + | bytea | BLOB | | + | character | TEXT | See warning [2](#2) below. | + | character varying | TEXT | See warning [2](#2) below. | + | date | DATE | | + | double precision | DOUBLE | | + | integer | INT | | + | real | FLOAT | | + | smallint | INT | See warning [2](#2) below. | + | text | TEXT | | + | time | TIME | | + | timestamp | TIMESTAMP | | + | timestamp with time zone | TIMESTAMPTZ | | + + Data types not listed above are not supported. The following are some common data types that are not supported: + + - bigserial + - bit + - box + - cidr + - circle + - inet + - interval + - json + - jsonb + - line + - lseg + - macaddr + - macaddr8 + - money + - numeric + - path + - pg_lsn + - pg_snapshot + - point + - polygon + - serial + - smallserial + - time with time zone + - tsquery + - tsvector + - txid_snapshot + - uuid + - xml + + + | Oracle | ScalarDB | Notes | + |--------------------------------|-------------------------------------|----------------------------| + | binary_double | DOUBLE | | + | binary_float | FLOAT | | + | blob | BLOB | See warning [3](#3) below. | + | char | TEXT | See warning [2](#2) below. | + | clob | TEXT | | + | date | DATE (default), TIME, and TIMESTAMP | See warning [6](#6) below. | + | float | DOUBLE | See warning [4](#4) below. | + | long | TEXT | | + | long raw | BLOB | | + | nchar | TEXT | See warning [2](#2) below. | + | nclob | TEXT | | + | number | BIGINT / DOUBLE | See warning [5](#5) below. | + | nvarchar2 | TEXT | See warning [2](#2) below. | + | raw | BLOB | See warning [2](#2) below. | + | timestamp | TIMESTAMP (default) and TIME | See warning [6](#6) below. | + | timestamp with time zone | TIMESTAMPTZ | | + | timestamp with local time zone | TIMESTAMPTZ | | + | varchar2 | TEXT | See warning [2](#2) below. | + + Data types not listed above are not supported. The following are some common data types that are not supported: + + - interval + - rowid + - urowid + - bfile + - json + + + | SQL Server | ScalarDB | Notes | + |----------------|-------------|----------------------------| + | bigint | BIGINT | See warning [1](#1) below. | + | binary | BLOB | See warning [2](#2) below. | + | bit | BOOLEAN | | + | char | TEXT | See warning [2](#2) below. | + | date | DATE | | + | datetime | TIMESTAMP | + | datetime2 | TIMESTAMP | | + | float | DOUBLE | | + | image | BLOB | | + | int | INT | | + | nchar | TEXT | See warning [2](#2) below. | + | ntext | TEXT | | + | nvarchar | TEXT | See warning [2](#2) below. | + | offsetdatetime | TIMESTAMPTZ | | + | real | FLOAT | | + | smalldatetime | TIMESTAMP | | + | smallint | INT | See warning [2](#2) below. | + | text | TEXT | | + | time | TIME | | + | tinyint | INT | See warning [2](#2) below. | + | varbinary | BLOB | See warning [2](#2) below. | + | varchar | TEXT | See warning [2](#2) below. | + + Data types not listed above are not supported. The following are some common data types that are not supported: + + - cursor + - decimal + - geography + - geometry + - hierarchyid + - money + - numeric + - rowversion + - smallmoney + - sql_variant + - uniqueidentifier + - xml + + + +:::warning + +
    +
  1. + The value range of `BIGINT` in ScalarDB is from -2^53 to 2^53, regardless of the size of `bigint` in the underlying database. Thus, if the data out of this range exists in the imported table, ScalarDB cannot read it. +
  2. +
  3. + For certain data types noted above, ScalarDB may map a data type larger than that of the underlying database. In that case, You will see errors when putting a value with a size larger than the size specified in the underlying database. +
  4. +
  5. + The maximum size of `BLOB` in ScalarDB is about 2GB (precisely 2^31-1 bytes). In contrast, Oracle `blob` can have (4GB-1)*(number of blocks). Thus, if data larger than 2GB exists in the imported table, ScalarDB cannot read it. +
  6. +
  7. + ScalarDB does not support Oracle `float` columns that have a higher precision than `DOUBLE` in ScalarDB. +
  8. +
  9. + ScalarDB does not support Oracle `numeric(p, s)` columns (`p` is precision and `s` is scale) when `p` is larger than 15 due to the maximum size of the data type in ScalarDB. Note that ScalarDB maps the column to `BIGINT` if `s` is zero; otherwise ScalarDB will map the column to `DOUBLE`. For the latter case, be aware that round-up or round-off can happen in the underlying database since the floating-point value will be cast to a fixed-point value. +
  10. +
  11. + The underlying storage type can be mapped to several ScalarDB data types. To override the default mapping, use the `override-columns-type` field in the import schema file. For an example, see [Sample import schema file](#sample-import-schema-file). +
  12. +
+ +::: + +## Use import function in your application + +You can use the import function in your application by using the following interfaces: + +- [ScalarDB Admin API](./api-guide.mdx#import-a-table) +- [ScalarDB Schema Loader API](./schema-loader.mdx#use-schema-loader-in-your-application) diff --git a/versioned_docs/version-3.15/schema-loader.mdx b/versioned_docs/version-3.15/schema-loader.mdx new file mode 100644 index 00000000..6cf21a18 --- /dev/null +++ b/versioned_docs/version-3.15/schema-loader.mdx @@ -0,0 +1,705 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# ScalarDB Schema Loader + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +ScalarDB has its own data model and schema that maps to the implementation-specific data model and schema. In addition, ScalarDB stores internal metadata, such as transaction IDs, record versions, and transaction statuses, to manage transaction logs and statuses when you use the Consensus Commit transaction manager. + +Since managing the schema mapping and metadata for transactions can be difficult, you can use ScalarDB Schema Loader, which is a tool to create schemas that doesn't require you to need in-depth knowledge about schema mapping or metadata. + +You have two options to specify general CLI options in Schema Loader: + +- Pass the ScalarDB properties file and database-specific or storage-specific options. +- Pass database-specific or storage-specific options without the ScalarDB properties file. (Deprecated) + +:::note + +This tool supports only basic options to create, delete, repair, or alter a table. If you want to use the advanced features of a database, you must alter your tables with a database-specific tool after creating the tables with this tool. + +::: + +## Set up Schema Loader + +Select your preferred method to set up Schema Loader, and follow the instructions. + + + + You can download the release versions of Schema Loader from the [ScalarDB Releases](https://github.com/scalar-labs/scalardb/releases) page. + + + You can pull the Docker image from the [Scalar container registry](https://github.com/orgs/scalar-labs/packages/container/package/scalardb-schema-loader) by running the following command, replacing the contents in the angle brackets as described: + + ```console + docker run --rm -v :/scalardb.properties -v :/schema.json ghcr.io/scalar-labs/scalardb-schema-loader: --config /scalardb.properties --schema-file /schema.json + ``` + +:::note + +You can specify the same command arguments even if you use the fat JAR or the container. In the [Available commands](#available-commands) section, the JAR is used, but you can run the commands by using the container in the same way by replacing `java -jar scalardb-schema-loader-.jar` with `docker run --rm -v : [-v :] ghcr.io/scalar-labs/scalardb-schema-loader:`. + +::: + + + +## Run Schema Loader + +This section explains how to run Schema Loader. + +### Available commands + +Select how you would like to configure Schema Loader for your database. The preferred method is to use the properties file since other, database-specific methods are deprecated. + +The following commands are available when using the properties file: + +```console +Usage: java -jar scalardb-schema-loader-.jar [-D] [--coordinator] + [--no-backup] [--no-scaling] -c= + [--compaction-strategy=] [-f=] + [--replication-factor=] + [--replication-strategy=] [--ru=] +Create/Delete schemas in the storage defined in the config file + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -c, --config= + Path to the config file of ScalarDB + --compaction-strategy= + The compaction strategy, must be LCS, STCS or TWCS + (supported in Cassandra) + --coordinator Create/delete/repair Coordinator tables + -D, --delete-all Delete tables + -f, --schema-file= + -I, --import Import tables : it will import existing non-ScalarDB + tables to ScalarDB. + Path to the schema json file + --no-backup Disable continuous backup (supported in DynamoDB) + --no-scaling Disable auto-scaling (supported in DynamoDB, Cosmos DB) + --repair-all Repair tables : it repairs the table metadata of + existing tables. When using Cosmos DB, it + additionally repairs stored procedure attached + to each table + --replication-factor= + The replication factor (supported in Cassandra) + --replication-strategy= + The replication strategy, must be SimpleStrategy or + NetworkTopologyStrategy (supported in Cassandra) + --ru= Base resource unit (supported in DynamoDB, Cosmos DB) +``` + +For a sample properties file, see [`database.properties`](https://github.com/scalar-labs/scalardb/blob/master/conf/database.properties). + +:::note + +The following database-specific methods have been deprecated. Please use the [commands for configuring the properties file](#available-commands) instead. + + + + ```console + Usage: java -jar scalardb-schema-loader-.jar --jdbc [-D] + -f= -j= -p= -u= + Create/Delete JDBC schemas + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -D, --delete-all Delete tables + -f, --schema-file= + Path to the schema json file + -j, --jdbc-url= JDBC URL + -p, --password= + JDBC password + --repair-all Repair tables : it repairs the table metadata of + existing tables + -u, --user= JDBC user + ``` + + + ```console + Usage: java -jar scalardb-schema-loader-.jar --dynamo [-D] + [--no-backup] [--no-scaling] [--endpoint-override=] + -f= -p= [-r=] --region= + -u= + Create/Delete DynamoDB schemas + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -D, --delete-all Delete tables + --endpoint-override= + Endpoint with which the DynamoDB SDK should + communicate + -f, --schema-file= + Path to the schema json file + --no-backup Disable continuous backup for DynamoDB + --no-scaling Disable auto-scaling for DynamoDB + -p, --password= AWS access secret key + -r, --ru= Base resource unit + --region= AWS region + --repair-all Repair tables : it repairs the table metadata of + existing tables + -u, --user= AWS access key ID + ``` + + + ```console + Usage: java -jar scalardb-schema-loader-.jar --cosmos [-D] + [--no-scaling] -f= -h= -p= [-r=] + Create/Delete Cosmos DB schemas + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -D, --delete-all Delete tables + -f, --schema-file= + Path to the schema json file + -h, --host= Cosmos DB account URI + --no-scaling Disable auto-scaling for Cosmos DB + -p, --password= Cosmos DB key + -r, --ru= Base resource unit + --repair-all Repair tables : it repairs the table metadata of + existing tables and repairs stored procedure + attached to each table + ``` + + + ```console + Usage: java -jar scalardb-schema-loader-.jar --cassandra [-D] + [-c=] -f= -h= + [-n=] [-p=] [-P=] + [-R=] [-u=] + Create/Delete Cassandra schemas + -A, --alter Alter tables : it will add new columns and create/delete + secondary index for existing tables. It compares the + provided table schema to the existing schema to decide + which columns need to be added and which indexes need + to be created or deleted + -c, --compaction-strategy= + Cassandra compaction strategy, must be LCS, STCS or TWCS + -D, --delete-all Delete tables + -f, --schema-file= + Path to the schema json file + -h, --host= Cassandra host IP + -n, --network-strategy= + Cassandra network strategy, must be SimpleStrategy or + NetworkTopologyStrategy + -p, --password= + Cassandra password + -P, --port= Cassandra Port + -R, --replication-factor= + Cassandra replication factor + --repair-all Repair tables : it repairs the table metadata of + existing tables + -u, --user= Cassandra user + ``` + + + +::: + +### Create namespaces and tables + +To create namespaces and tables by using a properties file, run the following command, replacing the contents in the angle brackets as described: + +```console +java -jar scalardb-schema-loader-.jar --config -f [--coordinator] +``` + +If `--coordinator` is specified, a [Coordinator table](api-guide.mdx#specify-operations-for-the-coordinator-table) will be created. When the [group commit feature for the Coordinator table](api-guide.mdx#group-commit-for-coordinator-table) is enabled, this command creates a Coordinator table with additional columns for the group commit feature. + +:::note + +The following database-specific CLI arguments have been deprecated. Please use the CLI arguments for configuring the properties file instead. + + + + ```console + java -jar scalardb-schema-loader-.jar --jdbc -j -u -p -f + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --dynamo -u -p --region -f [-r BASE_RESOURCE_UNIT] + ``` + + - `` should be a string to specify an AWS region like `ap-northeast-1`. + - `-r` option is almost the same as Cosmos DB for NoSQL option. However, the unit means DynamoDB capacity unit. The read and write capacity units are set the same value. + + + ```console + java -jar scalardb-schema-loader-.jar --cosmos -h -p -f [-r BASE_RESOURCE_UNIT] + ``` + + - `` you can use a primary key or a secondary key. + - `-r BASE_RESOURCE_UNIT` is an option. You can specify the RU of each database. The maximum RU in tables in the database will be set. If you don't specify RU of tables, the database RU will be set with this option. By default, it's 400. + + + ```console + java -jar scalardb-schema-loader-.jar --cassandra -h [-P ] [-u ] [-p ] -f [-n ] [-R ] + ``` + + - If `-P ` is not supplied, it defaults to `9042`. + - If `-u ` is not supplied, it defaults to `cassandra`. + - If `-p ` is not supplied, it defaults to `cassandra`. + - `` should be `SimpleStrategy` or `NetworkTopologyStrategy`. + + + +::: + +### Alter tables + +You can use a command to add new columns to and create or delete a secondary index for existing tables. This command compares the provided table schema to the existing schema to decide which columns need to be added and which indexes need to be created or deleted. + +To add new columns to and create or delete a secondary index for existing tables, run the following command, replacing the contents in the angle brackets as described: + +```console +java -jar scalardb-schema-loader-.jar --config -f --alter +``` + +:::note + +The following database-specific CLI arguments have been deprecated. Please use the CLI arguments for configuring the properties file instead. + + + + ```console + java -jar scalardb-schema-loader-.jar --jdbc -j -u -p -f --alter + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --dynamo -u -p --region -f --alter + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cosmos -h -p -f --alter + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cassandra -h [-P ] [-u ] [-p ] -f --alter + ``` + + + +::: + +### Delete tables + +You can delete tables by using the properties file. To delete tables, run the following command, replacing the contents in the angle brackets as described: + +```console +java -jar scalardb-schema-loader-.jar --config -f [--coordinator] -D +``` + +If `--coordinator` is specified, the Coordinator table will be deleted as well. + +:::note + +The following database-specific CLI arguments have been deprecated. Please use the CLI arguments for configuring the properties file instead. + + + + ```console + java -jar scalardb-schema-loader-.jar --jdbc -j -u -p -f -D + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --dynamo -u -p --region -f -D + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cosmos -h -p -f -D + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cassandra -h [-P ] [-u ] [-p ] -f -D + ``` + + + +::: + +### Repair tables + +You can repair the table metadata of existing tables by using the properties file. To repair table metadata of existing tables, run the following command, replacing the contents in the angle brackets as described: + +```console +java -jar scalardb-schema-loader-.jar --config -f [--coordinator] --repair-all +``` + +:::warning + +Before executing this command, you should confirm the following configurations are the same as those that were last applied: + +- The schema configuration +- Whether the [group commit feature for the Coordinator table](api-guide.mdx#group-commit-for-coordinator-table) is enabled or not, if the `--coordinator` option described below is specified + +::: + +If `--coordinator` is specified, the Coordinator table will be repaired as well. In addition, if you're using Cosmos DB for NoSQL, running this command will also repair stored procedures attached to each table. + +:::note + +The following database-specific CLI arguments have been deprecated. Please use the CLI arguments for configuring the properties file instead. + + + + ```console + java -jar scalardb-schema-loader-.jar --jdbc -j -u -p -f --repair-all + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --dynamo -u -p --region [--no-backup] -f --repair-all + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cosmos -h -p -f --repair-all + ``` + + + ```console + java -jar scalardb-schema-loader-.jar --cassandra -h [-P ] [-u ] [-p ] -f --repair-all + ``` + + + +::: + +### Import tables + +You can import an existing table in JDBC databases to ScalarDB by using the `--import` option and an import-specific schema file. For details, see [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](./schema-loader-import.mdx). + +### Sample schema file + +The following is a sample schema. For a sample schema file, see [`schema_sample.json`](https://github.com/scalar-labs/scalardb/blob/master/schema-loader/sample/schema_sample.json). + +```json +{ + "sample_db.sample_table": { + "transaction": false, + "partition-key": [ + "c1" + ], + "clustering-key": [ + "c4 ASC", + "c6 DESC" + ], + "columns": { + "c1": "INT", + "c2": "TEXT", + "c3": "BLOB", + "c4": "INT", + "c5": "BOOLEAN", + "c6": "INT" + }, + "secondary-index": [ + "c2", + "c4" + ] + }, + + "sample_db.sample_table1": { + "transaction": true, + "partition-key": [ + "c1" + ], + "clustering-key": [ + "c4" + ], + "columns": { + "c1": "INT", + "c2": "TEXT", + "c3": "INT", + "c4": "INT", + "c5": "BOOLEAN" + } + }, + + "sample_db.sample_table2": { + "transaction": false, + "partition-key": [ + "c1" + ], + "clustering-key": [ + "c4", + "c3" + ], + "columns": { + "c1": "INT", + "c2": "TEXT", + "c3": "INT", + "c4": "INT", + "c5": "BOOLEAN" + } + } +} +``` + +The schema has table definitions that include `columns`, `partition-key`, `clustering-key`, `secondary-index`, and `transaction` fields. + +- The `columns` field defines columns of the table and their data types. +- The `partition-key` field defines which columns the partition key is composed of. +- The `clustering-key` field defines which columns the clustering key is composed of. +- The `secondary-index` field defines which columns are indexed. +- The `transaction` field indicates whether the table is for transactions or not. + - If you set the `transaction` field to `true` or don't specify the `transaction` field, this tool creates a table with transaction metadata if needed. + - If you set the `transaction` field to `false`, this tool creates a table without any transaction metadata (that is, for a table with [Storage API](run-non-transactional-storage-operations-through-primitive-crud-interface.mdx)). + +You can also specify database or storage-specific options in the table definition as follows: + +```json +{ + "sample_db.sample_table3": { + "partition-key": [ + "c1" + ], + "columns": { + "c1": "INT", + "c2": "TEXT", + "c3": "BLOB" + }, + "compaction-strategy": "LCS", + "ru": 5000 + } +} +``` + +The database or storage-specific options you can specify are as follows: + + + + No options are available for JDBC databases. + + + The `ru` option stands for Request Units. For details, see [RUs](#rus). + + + The `ru` option stands for Request Units. For details, see [RUs](#rus). + + + The `compaction-strategy` option is the compaction strategy used. This option should be `STCS` (SizeTieredCompaction), `LCS` (LeveledCompactionStrategy), or `TWCS` (TimeWindowCompactionStrategy). + + + +## Scale for performance when using Cosmos DB for NoSQL or DynamoDB + +When using Cosmos DB for NoSQL or DynamoDB, you can scale by using Request Units (RUs) or auto-scaling. + +### RUs + +You can scale the throughput of Cosmos DB for NoSQL and DynamoDB by specifying the `--ru` option. When specifying this option, scaling applies to all tables or the `ru` parameter for each table. + +If the `--ru` option is not set, the default values will be `400` for Cosmos DB for NoSQL and `10` for DynamoDB. + +:::note + +- Schema Loader abstracts [Request Units](https://docs.microsoft.com/azure/cosmos-db/request-units) for Cosmos DB for NoSQL and [Capacity Units](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html#HowItWorks.ProvisionedThroughput.Manual) for DynamoDB with `RU`. Therefore, be sure to set an appropriate value depending on the database implementation. +- Be aware that Schema Loader sets the same value to both read capacity unit and write capacity unit for DynamoDB. + +::: + +### Auto-scaling + +By default, Schema Loader enables auto-scaling of RUs for all tables: RUs scale between 10 percent and 100 percent of a specified RU depending on the workload. For example, if you specify `-r 10000`, the RUs of each table auto-scales between `1000` and `10000`. + +:::note + +Auto-scaling for Cosmos DB for NoSQL is enabled only when this option is set to `4000` or more. + +::: + +## Data-type mapping between ScalarDB and other databases + +The following table shows the supported data types in ScalarDB and their mapping to the data types of other databases. + +| ScalarDB | Cassandra | Cosmos DB for NoSQL | DynamoDB | MySQL/MariaDB | PostgreSQL/YugabyteDB | Oracle | SQL Server | SQLite | +|-------------|----------------------|---------------------|----------|---------------|--------------------------|--------------------------|-----------------|---------| +| BOOLEAN | boolean | boolean (JSON) | BOOL | boolean | boolean | number(1) | bit | boolean | +| INT | int | number (JSON) | N | int | int | number(10) | int | int | +| BIGINT | bigint | number (JSON) | N | bigint | bigint | number(16) | bigint | bigint | +| FLOAT | float | number (JSON) | N | real | real | binary_float | float(24) | float | +| DOUBLE | double | number (JSON) | N | double | double precision | binary_double | float | double | +| TEXT | text | string (JSON) | S | longtext | text | varchar2(4000) | varchar(8000) | text | +| BLOB | blob | string (JSON) | B | longblob | bytea | RAW(2000) | varbinary(8000) | blob | +| DATE | date | number (JSON) | N | date | date | date | date | int | +| TIME | time | number (JSON) | N | time | time | timestamp | time | bigint | +| TIMESTAMP | Unsupported | number (JSON) | N | datetime | timestamp | timestamp | datetime2 | bigint | +| TIMESTAMPTZ | timestamp | number (JSON) | N | datetime | timestamp with time zone | timestamp with time zone | datetimeoffset | bigint | + +:::note + +TIMESTAMP represents a date-time without time zone information, while TIMESTAMPTZ represents a date-time on the UTC time zone. + +::: + +However, the following data types in JDBC databases are converted differently when they are used as a primary key or a secondary index key. This is due to the limitations of RDB data types. For MySQL and Oracle, you can change the column size (minimum 64 bytes) as long as it meets the limitation of the total size of key columns. For details, see [Underlying storage or database configurations](configurations.mdx#underlying-storage-or-database-configurations). + +| ScalarDB | MySQL/MariaDB | PostgreSQL/YugabyteDB | Oracle | +|----------|----------------|-----------------------|---------------| +| TEXT | VARCHAR(128) | VARCHAR(10485760) | VARCHAR2(128) | +| BLOB | VARBINARY(128) | | RAW(128) | + +The following data types have a value range and precision regardless of the underlying database. + +| Type | Minimum | Maximum | Precision | +|-------------|---------------------------|---------------------------|---------------| +| BIGINT | -2^53 | 2^53 | - | +| DATE | 1000-01-01 | 9999-12-31 | 1 day | +| TIME | 00:00:00.000000 | 23:59:59.999999 | 1 microsecond | +| TIMESTAMP | 1000-01-01 00:00:00.000 | 9999-12-31 23:59:59.999 | 1 millisecond | +| TIMESTAMPTZ | 1000-01-01 00:00:00.000 Z | 9999-12-31 23:59:59.999 Z | 1 millisecond | + +:::note + +YugabyteDB has limitations that prevent floating point types (FLOAT and DOUBLE) from functioning correctly as a primary key, clustering keys, or secondary index keys. + +::: + +If this data-type mapping doesn't match your application, please alter the tables to change the data types after creating them by using this tool. + +## Internal metadata for Consensus Commit + +The Consensus Commit transaction manager manages metadata (for example, transaction ID, record version, and transaction status) stored along with the actual records to handle transactions properly. + +Thus, along with any columns that the application requires, additional columns for the metadata need to be defined in the schema. Additionally, this tool creates a table with the metadata if you use the Consensus Commit transaction manager. + +## Use Schema Loader in your application + +You can check the version of Schema Loader from the [Maven Central Repository](https://mvnrepository.com/artifact/com.scalar-labs/scalardb-schema-loader). For example in Gradle, you can add the following dependency to your `build.gradle` file, replacing `` with the version of Schema Loader that you want to use: + +```gradle +dependencies { + implementation 'com.scalar-labs:scalardb-schema-loader:' +} +``` + +### Create, alter, repair, or delete tables + +You can create, alter, delete, or repair tables that are defined in the schema by using Schema Loader. To do this, you can pass a ScalarDB properties file, schema, and additional options, if needed, as shown below: + +```java +public class SchemaLoaderSample { + public static int main(String... args) throws SchemaLoaderException { + Path configFilePath = Paths.get("database.properties"); + // "sample_schema.json" and "altered_sample_schema.json" can be found in the "/sample" directory. + Path schemaFilePath = Paths.get("sample_schema.json"); + Path alteredSchemaFilePath = Paths.get("altered_sample_schema.json"); + boolean createCoordinatorTables = true; // whether to create the Coordinator table or not + boolean deleteCoordinatorTables = true; // whether to delete the Coordinator table or not + boolean repairCoordinatorTables = true; // whether to repair the Coordinator table or not + + Map tableCreationOptions = new HashMap<>(); + + tableCreationOptions.put( + CassandraAdmin.REPLICATION_STRATEGY, ReplicationStrategy.SIMPLE_STRATEGY.toString()); + tableCreationOptions.put(CassandraAdmin.COMPACTION_STRATEGY, CompactionStrategy.LCS.toString()); + tableCreationOptions.put(CassandraAdmin.REPLICATION_FACTOR, "1"); + + tableCreationOptions.put(DynamoAdmin.REQUEST_UNIT, "1"); + tableCreationOptions.put(DynamoAdmin.NO_SCALING, "true"); + tableCreationOptions.put(DynamoAdmin.NO_BACKUP, "true"); + + Map indexCreationOptions = new HashMap<>(); + indexCreationOptions.put(DynamoAdmin.NO_SCALING, "true"); + + Map tableReparationOptions = new HashMap<>(); + indexCreationOptions.put(DynamoAdmin.NO_BACKUP, "true"); + + // Create tables. + SchemaLoader.load(configFilePath, schemaFilePath, tableCreationOptions, createCoordinatorTables); + + // Alter tables. + SchemaLoader.alterTables(configFilePath, alteredSchemaFilePath, indexCreationOptions); + + // Repair tables. + SchemaLoader.repairTables(configFilePath, schemaFilePath, tableReparationOptions, repairCoordinatorTables); + + // Delete tables. + SchemaLoader.unload(configFilePath, schemaFilePath, deleteCoordinatorTables); + + return 0; + } +} +``` + +You can also create, delete, or repair a schema by passing a serialized-schema JSON string (the raw text of a schema file) as shown below: + +```java +// Create tables. +SchemaLoader.load(configFilePath, serializedSchemaJson, tableCreationOptions, createCoordinatorTables); + +// Alter tables. +SchemaLoader.alterTables(configFilePath, serializedAlteredSchemaFilePath, indexCreationOptions); + +// Repair tables. +SchemaLoader.repairTables(configFilePath, serializedSchemaJson, tableReparationOptions, repairCoordinatorTables); + +// Delete tables. +SchemaLoader.unload(configFilePath, serializedSchemaJson, deleteCoordinatorTables); +``` + +When configuring ScalarDB, you can use a `Properties` object as well, as shown below: + +```java +// Create tables. +SchemaLoader.load(properties, serializedSchemaJson, tableCreationOptions, createCoordinatorTables); + +// Alter tables. +SchemaLoader.alterTables(properties, serializedAlteredSchemaFilePath, indexCreationOptions); + +// Repair tables. +SchemaLoader.repairTables(properties, serializedSchemaJson, tableReparationOptions, repairCoordinatorTables); + +// Delete tables. +SchemaLoader.unload(properties, serializedSchemaJson, deleteCoordinatorTables); +``` + +### Import tables + +You can import an existing JDBC database table to ScalarDB by using the `--import` option and an import-specific schema file, in a similar manner as shown in [Sample schema file](#sample-schema-file). For details, see [Importing Existing Tables to ScalarDB by Using ScalarDB Schema Loader](./schema-loader-import.mdx). + +:::warning + +You should carefully plan to import a table to ScalarDB in production because it will add transaction metadata columns to your database tables and the ScalarDB metadata tables. In this case, there would also be several differences between your database and ScalarDB, as well as some limitations. + +::: + +The following is an import sample: + +```java +public class SchemaLoaderImportSample { + public static int main(String... args) throws SchemaLoaderException { + Path configFilePath = Paths.get("database.properties"); + // "import_sample_schema.json" can be found in the "/sample" directory. + Path schemaFilePath = Paths.get("import_sample_schema.json"); + Map tableImportOptions = new HashMap<>(); + + // Import tables. + // You can also use a Properties object instead of configFilePath and a serialized-schema JSON + // string instead of schemaFilePath. + SchemaLoader.importTables(configFilePath, schemaFilePath, tableImportOptions); + + return 0; + } +} +``` diff --git a/versioned_docs/version-3.15/slides/TransactionManagementOnCassandra.pdf b/versioned_docs/version-3.15/slides/TransactionManagementOnCassandra.pdf new file mode 100644 index 00000000..40e855bd Binary files /dev/null and b/versioned_docs/version-3.15/slides/TransactionManagementOnCassandra.pdf differ diff --git a/versioned_docs/version-3.15/two-phase-commit-transactions.mdx b/versioned_docs/version-3.15/two-phase-commit-transactions.mdx new file mode 100644 index 00000000..0f251d60 --- /dev/null +++ b/versioned_docs/version-3.15/two-phase-commit-transactions.mdx @@ -0,0 +1,745 @@ +--- +tags: + - Community + - Enterprise Standard + - Enterprise Premium +displayed_sidebar: docsEnglish +--- + +# Transactions with a Two-Phase Commit Interface + +ScalarDB supports executing transactions with a two-phase commit interface. With the two-phase commit interface, you can execute a transaction that spans multiple processes or applications, like in a microservice architecture. + +This page explains how transactions with a two-phase commit interface work in ScalarDB and how to configure and execute them in ScalarDB. + +## How transactions with a two-phase commit interface work in ScalarDB + +ScalarDB normally executes transactions in a single transaction manager instance with a one-phase commit interface. In transactions with a one-phase commit interface, you begin a transaction, execute CRUD operations, and commit the transaction in the same transaction manager instance. + +In ScalarDB, you can execute transactions with a two-phase commit interface that span multiple transaction manager instances. The transaction manager instances can be in the same process or application, or the instances can be in different processes or applications. For example, if you have transaction manager instances in multiple microservices, you can execute a transaction that spans multiple microservices. + +In transactions with a two-phase commit interface, there are two roles—Coordinator and a participant—that collaboratively execute a single transaction. + +The Coordinator process and the participant processes all have different transaction manager instances. The Coordinator process first begins or starts a transaction, and the participant processes join the transaction. After executing CRUD operations, the Coordinator process and the participant processes commit the transaction by using the two-phase interface. + +## How to execute transactions with a two-phase commit interface + +To execute a two-phase commit transaction, you must get the transaction manager instance. Then, the Coordinator process can begin or start the transaction, and the participant can process the transaction. + +### Get a `TwoPhaseCommitTransactionManager` instance + +You first need to get a `TwoPhaseCommitTransactionManager` instance to execute transactions with a two-phase commit interface. + +To get a `TwoPhaseCommitTransactionManager` instance, you can use `TransactionFactory` as follows: + +```java +TransactionFactory factory = TransactionFactory.create(""); +TwoPhaseCommitTransactionManager transactionManager = factory.getTwoPhaseCommitTransactionManager(); +``` + +### Begin or start a transaction (for Coordinator) + +For the process or application that begins the transaction to act as Coordinator, you should use the following `begin` method: + +```java +// Begin a transaction. +TwoPhaseCommitTransaction tx = transactionManager.begin(); +``` + +Or, for the process or application that begins the transaction to act as Coordinator, you should use the following `start` method: + +```java +// Start a transaction. +TwoPhaseCommitTransaction tx = transactionManager.start(); +``` + +Alternatively, you can use the `begin` method for a transaction by specifying a transaction ID as follows: + +```java +// Begin a transaction by specifying a transaction ID. +TwoPhaseCommitTransaction tx = transactionManager.begin(""); +``` + +Or, you can use the `start` method for a transaction by specifying a transaction ID as follows: + +```java +// Start a transaction by specifying a transaction ID. +TwoPhaseCommitTransaction tx = transactionManager.start(""); +``` + +### Join a transaction (for participants) + +For participants, you can join a transaction by specifying the transaction ID associated with the transaction that Coordinator has started or begun as follows: + +```java +TwoPhaseCommitTransaction tx = transactionManager.join(""); +``` + +:::note + +To get the transaction ID with `getId()`, you can specify the following: + +```java +tx.getId(); +``` + +::: + +### CRUD operations for the transaction + +The CRUD operations for `TwoPhaseCommitTransacton` are the same as the operations for `DistributedTransaction`. For details, see [CRUD operations](api-guide.mdx#crud-operations). + +The following is example code for CRUD operations in transactions with a two-phase commit interface: + +```java +TwoPhaseCommitTransaction tx = ... + +// Retrieve the current balances by ID. +Get fromGet = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLE) + .partitionKey(new Key(ID, fromId)) + .build(); + +Get toGet = + Get.newBuilder() + .namespace(NAMESPACE) + .table(TABLE) + .partitionKey(new Key(ID, toId)) + .build(); + +Optional fromResult = tx.get(fromGet); +Optional toResult = tx.get(toGet); + +// Calculate the balances (assuming that both accounts exist). +int newFromBalance = fromResult.get().getInt(BALANCE) - amount; +int newToBalance = toResult.get().getInt(BALANCE) + amount; + +// Update the balances. +Put fromPut = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLE) + .partitionKey(new Key(ID, fromId)) + .intValue(BALANCE, newFromBalance) + .build(); + +Put toPut = + Put.newBuilder() + .namespace(NAMESPACE) + .table(TABLE) + .partitionKey(new Key(ID, toId)) + .intValue(BALANCE, newToBalance) + .build(); + +tx.put(fromPut); +tx.put(toPut); +``` + +### Prepare, commit, or roll back a transaction + +After finishing CRUD operations, you need to commit the transaction. As with the standard two-phase commit protocol, there are two phases: prepare and commit. + +In all the Coordinator and participant processes, you need to prepare and then commit the transaction as follows: + +```java +TwoPhaseCommitTransaction tx = ... + +try { + // Execute CRUD operations in the Coordinator and participant processes. + ... + + // Prepare phase: Prepare the transaction in all the Coordinator and participant processes. + tx.prepare(); + ... + + // Commit phase: Commit the transaction in all the Coordinator and participant processes. + tx.commit(); + ... +} catch (TransactionException e) { + // If an error happens, you will need to roll back the transaction in all the Coordinator and participant processes. + tx.rollback(); + ... +} +``` + +For `prepare()`, if any of the Coordinator or participant processes fail to prepare the transaction, you will need to call `rollback()` (or `abort()`) in all the Coordinator and participant processes. + +For `commit()`, if any of the Coordinator or participant processes successfully commit the transaction, you can consider the transaction as committed. When a transaction has been committed, you can ignore any errors in the other Coordinator and participant processes. If all the Coordinator and participant processes fail to commit the transaction, you will need to call `rollback()` (or `abort()`) in all the Coordinator and participant processes. + +For better performance, you can call `prepare()`, `commit()`, and `rollback()` in the Coordinator and participant processes in parallel, respectively. + +#### Validate the transaction + +Depending on the concurrency control protocol, you need to call `validate()` in all the Coordinator and participant processes after `prepare()` and before `commit()`, as shown below: + +```java +// Prepare phase 1: Prepare the transaction in all the Coordinator and participant processes. +tx.prepare(); +... + +// Prepare phase 2: Validate the transaction in all the Coordinator and participant processes. +tx.validate(); +... + +// Commit phase: Commit the transaction in all the Coordinator and participant processes. +tx.commit(); +... +``` + +Similar to `prepare()`, if any of the Coordinator or participant processes fail to validate the transaction, you will need to call `rollback()` (or `abort()`) in all the Coordinator and participant processes. In addition, you can call `validate()` in the Coordinator and participant processes in parallel for better performance. + +:::note + +When using the [Consensus Commit](configurations.mdx#use-consensus-commit-directly) transaction manager with `EXTRA_READ` set as the value for `scalar.db.consensus_commit.serializable_strategy` and `SERIALIZABLE` set as the value for `scalar.db.consensus_commit.isolation_level`, you need to call `validate()`. However, if you are not using Consensus Commit, specifying `validate()` will not have any effect. + +::: + +### Execute a transaction by using multiple transaction manager instances + +By using the APIs described above, you can execute a transaction by using multiple transaction manager instances. The following is an example of how that works. + +:::warning + +The following sample code is a simplified version that solely illustrates how to use the two-phase commit interface and doesn't represent a real-world use case. In actual applications, it is assumed that a transaction manager instance is created per process or service. + +For a real-world example, see the [microservice transactions sample tutorial](scalardb-samples/microservice-transaction-sample/README.mdx). + +::: + +```java +TransactionFactory factory1 = + TransactionFactory.create(""); +TwoPhaseCommitTransactionManager transactionManager1 = + factory1.getTwoPhaseCommitTransactionManager(); + +TransactionFactory factory2 = + TransactionFactory.create(""); +TwoPhaseCommitTransactionManager transactionManager2 = + factory2.getTwoPhaseCommitTransactionManager(); + +TwoPhaseCommitTransaction transaction1 = null; +TwoPhaseCommitTransaction transaction2 = null; +try { + // Begin a transaction. + transaction1 = transactionManager1.begin(); + + // Join the transaction begun by `transactionManager1` by getting the transaction ID. + transaction2 = transactionManager2.join(transaction1.getId()); + + // Execute CRUD operations in the transaction. + Optional result = transaction1.get(...); + List results = transaction2.scan(...); + transaction1.put(...); + transaction2.delete(...); + + // Prepare the transaction. + transaction1.prepare(); + transaction2.prepare(); + + // Validate the transaction. + transaction1.validate(); + transaction2.validate(); + + // Commit the transaction. If any of the transactions successfully commit, + // you can regard the transaction as committed. + AtomicReference exception = new AtomicReference<>(); + boolean anyMatch = + Stream.of(transaction1, transaction2) + .anyMatch( + t -> { + try { + t.commit(); + return true; + } catch (TransactionException e) { + exception.set(e); + return false; + } + }); + + // If all the transactions fail to commit, throw the exception and roll back the transaction. + if (!anyMatch) { + throw exception.get(); + } +} catch (TransactionException e) { + // Roll back the transaction. + if (transaction1 != null) { + try { + transaction1.rollback(); + } catch (RollbackException e1) { + // Handle the exception. + } + } + if (transaction2 != null) { + try { + transaction2.rollback(); + } catch (RollbackException e1) { + // Handle the exception. + } + } +} +``` + +For simplicity, the above example code doesn't handle the exceptions that the APIs may throw. For details about handling exceptions, see [How to handle exceptions](#how-to-handle-exceptions). + +As previously mentioned, for `commit()`, if any of the Coordinator or participant processes succeed in committing the transaction, you can consider the transaction as committed. Also, for better performance, you can execute `prepare()`, `validate()`, and `commit()` in parallel, respectively. + +### Resume or re-join a transaction + +Given that processes or applications that use transactions with a two-phase commit interface usually involve multiple request and response exchanges, you might need to execute a transaction across various endpoints or APIs. For such scenarios, you can use `resume()` or `join()` to get a transaction object (an instance of `TwoPhaseCommitTransaction`) for the transaction that you previously joined. + +The following shows how `resume()` and `join()` work: + +```java +// Join (or begin) the transaction. +TwoPhaseCommitTransaction tx = transactionManager.join(""); + +... + +// Resume the transaction by using the transaction ID. +TwoPhaseCommitTransaction tx1 = transactionManager.resume(""); + +// Or you can re-join the transaction by using the transaction ID. +TwoPhaseCommitTransaction tx2 = transactionManager.join(""); +``` + +:::note + +To get the transaction ID with `getId()`, you can specify the following: + +```java +tx.getId(); +``` + +In addition, when using `join()` to re-join a transaction, if you have not joined the transaction before, a new transaction object will be returned. On the other hand, when using `resume()` to resume a transaction, if you have not joined the transaction before, `TransactionNotFoundException` will be thrown. + + +::: + +The following is an example of two services that have multiple endpoints: + +```java +interface ServiceA { + void facadeEndpoint() throws Exception; +} + +interface ServiceB { + void endpoint1(String txId) throws Exception; + + void endpoint2(String txId) throws Exception; + + void prepare(String txId) throws Exception; + + void commit(String txId) throws Exception; + + void rollback(String txId) throws Exception; +} +``` + +The following is an example of a client calling `ServiceA.facadeEndpoint()` that begins a transaction that spans the two services (`ServiceA` and `ServiceB`): + +```java +public class ServiceAImpl implements ServiceA { + + private TwoPhaseCommitTransactionManager transactionManager = ...; + private ServiceB serviceB = ...; + + ... + + @Override + public void facadeEndpoint() throws Exception { + TwoPhaseCommitTransaction tx = transactionManager.begin(); + + try { + ... + + // Call `ServiceB` `endpoint1`. + serviceB.endpoint1(tx.getId()); + + ... + + // Call `ServiceB` `endpoint2`. + serviceB.endpoint2(tx.getId()); + + ... + + // Prepare. + tx.prepare(); + serviceB.prepare(tx.getId()); + + // Commit. + tx.commit(); + serviceB.commit(tx.getId()); + } catch (Exception e) { + // Roll back. + tx.rollback(); + serviceB.rollback(tx.getId()); + } + } +} +``` + +As shown above, the facade endpoint in `ServiceA` calls multiple endpoints (`endpoint1()`, `endpoint2()`, `prepare()`, `commit()`, and `rollback()`) of `ServiceB`. In addition, in transactions with a two-phase commit interface, you need to use the same transaction object across the endpoints. + +In this situation, you can resume the transaction. The implementation of `ServiceB` is as follows: + +```java +public class ServiceBImpl implements ServiceB { + + private TwoPhaseCommitTransactionManager transactionManager = ...; + + ... + + @Override + public void endpoint1(String txId) throws Exception { + // Join the transaction. + TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + } + + @Override + public void endpoint2(String txId) throws Exception { + // Resume the transaction that you joined in `endpoint1()`. + TwoPhaseCommitTransaction tx = transactionManager.resume(txId); + + // Or re-join the transaction that you joined in `endpoint1()`. + // TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + } + + @Override + public void prepare(String txId) throws Exception { + // Resume the transaction. + TwoPhaseCommitTransaction tx = transactionManager.resume(txId); + + // Or re-join the transaction. + // TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + + // Prepare. + tx.prepare(); + } + + @Override + public void commit(String txId) throws Exception { + // Resume the transaction. + TwoPhaseCommitTransaction tx = transactionManager.resume(txId); + + // Or re-join the transaction. + // TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + + // Commit. + tx.commit(); + } + + @Override + public void rollback(String txId) throws Exception { + // Resume the transaction. + TwoPhaseCommitTransaction tx = transactionManager.resume(txId); + + // Or re-join the transaction. + // TwoPhaseCommitTransaction tx = transactionManager.join(txId); + + ... + + // Roll back. + tx.rollback(); + } +} +``` + +As shown above, by resuming or re-joining the transaction, you can share the same transaction object across multiple endpoints in `ServiceB`. + +## How to handle exceptions + +When executing a transaction by using multiple transaction manager instances, you will also need to handle exceptions properly. + +:::warning + +If you don't handle exceptions properly, you may face anomalies or data inconsistency. + +::: + +For instance, in the example code in [Execute a transaction by using multiple transaction manager instances](#execute-a-transaction-by-using-multiple-transaction-manager-instances), multiple transaction managers (`transactionManager1` and `transactionManager2`) are used in a single process for ease of explanation. However, that example code doesn't include a way to handle exceptions. + +The following example code shows how to handle exceptions in transactions with a two-phase commit interface: + +```java +public class Sample { + public static void main(String[] args) throws Exception { + TransactionFactory factory1 = + TransactionFactory.create(""); + TwoPhaseCommitTransactionManager transactionManager1 = + factory1.getTwoPhaseCommitTransactionManager(); + + TransactionFactory factory2 = + TransactionFactory.create(""); + TwoPhaseCommitTransactionManager transactionManager2 = + factory2.getTwoPhaseCommitTransactionManager(); + + int retryCount = 0; + TransactionException lastException = null; + + while (true) { + if (retryCount++ > 0) { + // Retry the transaction three times maximum in this sample code. + if (retryCount >= 3) { + // Throw the last exception if the number of retries exceeds the maximum. + throw lastException; + } + + // Sleep 100 milliseconds before retrying the transaction in this sample code. + TimeUnit.MILLISECONDS.sleep(100); + } + + TwoPhaseCommitTransaction transaction1 = null; + TwoPhaseCommitTransaction transaction2 = null; + try { + // Begin a transaction. + transaction1 = transactionManager1.begin(); + + // Join the transaction that `transactionManager1` begun by using the transaction ID. + transaction2 = transactionManager2.join(transaction1.getId()); + + // Execute CRUD operations in the transaction. + Optional result = transaction1.get(...); + List results = transaction2.scan(...); + transaction1.put(...); + transaction2.delete(...); + + // Prepare the transaction. + prepare(transaction1, transaction2); + + // Validate the transaction. + validate(transaction1, transaction2); + + // Commit the transaction. + commit(transaction1, transaction2); + } catch (UnknownTransactionStatusException e) { + // If you catch `UnknownTransactionStatusException` when committing the transaction, + // it indicates that the status of the transaction, whether it was successful or not, is unknown. + // In such a case, you need to check if the transaction is committed successfully or not and + // retry the transaction if it failed. How to identify a transaction status is delegated to users. + return; + } catch (TransactionException e) { + // For other exceptions, you can try retrying the transaction. + + // For `CrudConflictException`, `PreparationConflictException`, `ValidationConflictException`, + // `CommitConflictException`, and `TransactionNotFoundException`, you can basically retry the + // transaction. However, for the other exceptions, the transaction will still fail if the cause of + // the exception is non-transient. In such a case, you will exhaust the number of retries and + // throw the last exception. + + rollback(transaction1, transaction2); + + lastException = e; + } + } + } + + private static void prepare(TwoPhaseCommitTransaction... transactions) + throws TransactionException { + // You can execute `prepare()` in parallel. + List exceptions = + Stream.of(transactions) + .parallel() + .map( + t -> { + try { + t.prepare(); + return null; + } catch (TransactionException e) { + return e; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + // If any of the transactions failed to prepare, throw the exception. + if (!exceptions.isEmpty()) { + throw exceptions.get(0); + } + } + + private static void validate(TwoPhaseCommitTransaction... transactions) + throws TransactionException { + // You can execute `validate()` in parallel. + List exceptions = + Stream.of(transactions) + .parallel() + .map( + t -> { + try { + t.validate(); + return null; + } catch (TransactionException e) { + return e; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + // If any of the transactions failed to validate, throw the exception. + if (!exceptions.isEmpty()) { + throw exceptions.get(0); + } + } + + private static void commit(TwoPhaseCommitTransaction... transactions) + throws TransactionException { + // You can execute `commit()` in parallel. + List exceptions = + Stream.of(transactions) + .parallel() + .map( + t -> { + try { + t.commit(); + return null; + } catch (TransactionException e) { + return e; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + // If any of the transactions successfully committed, you can regard the transaction as committed. + if (exceptions.size() < transactions.length) { + if (!exceptions.isEmpty()) { + // You can log the exceptions here if you want. + } + + return; // Commit was successful. + } + + // + // If all the transactions failed to commit: + // + + // If any of the transactions failed to commit due to `UnknownTransactionStatusException`, throw + // it because you should not retry the transaction in such a case. + Optional unknownTransactionStatusException = + exceptions.stream().filter(e -> e instanceof UnknownTransactionStatusException).findFirst(); + if (unknownTransactionStatusException.isPresent()) { + throw unknownTransactionStatusException.get(); + } + + // Otherwise, throw the first exception. + throw exceptions.get(0); + } + + private static void rollback(TwoPhaseCommitTransaction... transactions) { + Stream.of(transactions) + .parallel() + .filter(Objects::nonNull) + .forEach( + t -> { + try { + t.rollback(); + } catch (RollbackException e) { + // Rolling back the transaction failed. The transaction should eventually recover, + // so you don't need to do anything further. You can simply log the occurrence here. + } + }); + } +} +``` + +### `TransactionException` and `TransactionNotFoundException` + +The `begin()` API could throw `TransactionException` or `TransactionNotFoundException`: + +- If you catch `TransactionException`, this exception indicates that the transaction has failed to begin due to transient or non-transient faults. You can try retrying the transaction, but you may not be able to begin the transaction due to non-transient faults. +- If you catch `TransactionNotFoundException`, this exception indicates that the transaction has failed to begin due to transient faults. In this case, you can retry the transaction. + +The `join()` API could also throw `TransactionNotFoundException`. You can handle this exception in the same way that you handle the exceptions for the `begin()` API. + +### `CrudException` and `CrudConflictException` + +The APIs for CRUD operations (`get()`, `scan()`, `put()`, `delete()`, and `mutate()`) could throw `CrudException` or `CrudConflictException`: + +- If you catch `CrudException`, this exception indicates that the transaction CRUD operation has failed due to transient or non-transient faults. You can try retrying the transaction from the beginning, but the transaction will still fail if the cause is non-transient. +- If you catch `CrudConflictException`, this exception indicates that the transaction CRUD operation has failed due to transient faults (for example, a conflict error). In this case, you can retry the transaction from the beginning. + +### `PreparationException` and `PreparationConflictException` + +The `prepare()` API could throw `PreparationException` or `PreparationConflictException`: + +- If you catch `PreparationException`, this exception indicates that preparing the transaction fails due to transient or non-transient faults. You can try retrying the transaction from the beginning, but the transaction will still fail if the cause is non-transient. +- If you catch `PreparationConflictException`, this exception indicates that preparing the transaction has failed due to transient faults (for example, a conflict error). In this case, you can retry the transaction from the beginning. + +### `ValidationException` and `ValidationConflictException` + +The `validate()` API could throw `ValidationException` or `ValidationConflictException`: + +- If you catch `ValidationException`, this exception indicates that validating the transaction fails due to transient or non-transient faults. You can try retrying the transaction from the beginning, but the transaction will still fail if the cause is non-transient. +- If you catch `ValidationConflictException`, this exception indicates that validating the transaction has failed due to transient faults (for example, a conflict error). In this case, you can retry the transaction from the beginning. + +### `CommitException`, `CommitConflictException`, and `UnknownTransactionStatusException` + +The `commit()` API could throw `CommitException`, `CommitConflictException`, or `UnknownTransactionStatusException`: + +- If you catch `CommitException`, this exception indicates that committing the transaction fails due to transient or non-transient faults. You can try retrying the transaction from the beginning, but the transaction will still fail if the cause is non-transient. +- If you catch `CommitConflictException`, this exception indicates that committing the transaction has failed due to transient faults (for example, a conflict error). In this case, you can retry the transaction from the beginning. +- If you catch `UnknownTransactionStatusException`, this exception indicates that the status of the transaction, whether it was successful or not, is unknown. In this case, you need to check if the transaction is committed successfully and retry the transaction if it has failed. + +How to identify a transaction status is delegated to users. You may want to create a transaction status table and update it transactionally with other application data so that you can get the status of a transaction from the status table. + +### Notes about some exceptions + +Although not illustrated in the example code, the `resume()` API could also throw `TransactionNotFoundException`. This exception indicates that the transaction associated with the specified ID was not found and/or the transaction might have expired. In either case, you can retry the transaction from the beginning since the cause of this exception is basically transient. + +In the sample code, for `UnknownTransactionStatusException`, the transaction is not retried because the application must check if the transaction was successful to avoid potential duplicate operations. For other exceptions, the transaction is retried because the cause of the exception is transient or non-transient. If the cause of the exception is transient, the transaction may succeed if you retry it. However, if the cause of the exception is non-transient, the transaction will still fail even if you retry it. In such a case, you will exhaust the number of retries. + +:::note + +If you begin a transaction by specifying a transaction ID, you must use a different ID when you retry the transaction. + +In addition, in the sample code, the transaction is retried three times maximum and sleeps for 100 milliseconds before it is retried. But you can choose a retry policy, such as exponential backoff, according to your application requirements. + +::: + +## Request routing in transactions with a two-phase commit interface + +Services that use transactions with a two-phase commit interface usually execute a transaction by exchanging multiple requests and responses, as shown in the following diagram: + +![Sequence diagram for transactions with a two-phase commit interface](images/two_phase_commit_sequence_diagram.png) + +In addition, each service typically has multiple servers (or hosts) for scalability and availability and uses server-side (proxy) or client-side load balancing to distribute requests to the servers. In such a case, since transaction processing in transactions with a two-phase commit interface is stateful, requests in a transaction must be routed to the same servers while different transactions need to be distributed to balance the load, as shown in the following diagram: + +![Load balancing for transactions with a two-phase commit interface](images/two_phase_commit_load_balancing.png) + +There are several approaches to achieve load balancing for transactions with a two-phase commit interface depending on the protocol between the services. Some approaches for this include using gRPC, HTTP/1.1, and [ScalarDB Cluster](scalardb-cluster/index.mdx), which is a component that is available only in the ScalarDB Enterprise edition. + +### gRPC + +When you use a client-side load balancer, you can use the same gRPC connection to send requests in a transaction, which guarantees that the requests go to the same servers. + +When you use a server-side (proxy) load balancer, solutions are different between an L3/L4 (transport-level) load balancer and an L7 (application-level) load balancer: + +- When using an L3/L4 load balancer, you can use the same gRPC connection to send requests in a transaction, similar to when you use a client-side load balancer. In this case, requests in the same gRPC connection always go to the same server. +- When using an L7 load balancer, since requests in the same gRPC connection don't necessarily go to the same server, you need to use cookies or similar method to route requests to the correct server. + - For example, if you use [Envoy](https://www.envoyproxy.io/), you can use session affinity (sticky session) for gRPC. Alternatively, you can use [bidirectional streaming RPC in gRPC](https://grpc.io/docs/what-is-grpc/core-concepts/#bidirectional-streaming-rpc) since the L7 load balancer distributes requests in the same stream to the same server. + +For more details about load balancing in gRPC, see [gRPC Load Balancing](https://grpc.io/blog/grpc-load-balancing/). + +### HTTP/1.1 + +Typically, you use a server-side (proxy) load balancer with HTTP/1.1: + +- When using an L3/L4 load balancer, you can use the same HTTP connection to send requests in a transaction, which guarantees the requests go to the same server. +- When using an L7 load balancer, since requests in the same HTTP connection don't necessarily go to the same server, you need to use cookies or similar method to route requests to the correct server. You can use session affinity (sticky session) in that case. + +### ScalarDB Cluster + +ScalarDB Cluster addresses request routing by providing a routing mechanism that is capable of directing requests to the appropriate cluster node within the cluster. For details about ScalarDB Cluster, see [ScalarDB Cluster](scalardb-cluster/index.mdx). + +## Hands-on tutorial + +One of the use cases for transactions with a two-phase commit interface is microservice transactions. For a hands-on tutorial, see [Create a Sample Application That Supports Microservice Transactions](scalardb-samples/microservice-transaction-sample/README.mdx). diff --git a/versioned_sidebars/version-3.15-sidebars.json b/versioned_sidebars/version-3.15-sidebars.json new file mode 100644 index 00000000..80f5e930 --- /dev/null +++ b/versioned_sidebars/version-3.15-sidebars.json @@ -0,0 +1,1826 @@ +{ + "docsEnglish": [ + { + "type": "doc", + "label": "ScalarDB Docs Home", + "id": "index" + }, + { + "type": "category", + "label": "About ScalarDB", + "collapsible": true, + "link": { + "type": "doc", + "id": "overview" + }, + "items": [ + { + "type": "doc", + "id": "design", + "label": "Design" + }, + { + "type": "doc", + "id": "features", + "label": "Features" + }, + { + "type": "doc", + "id": "glossary", + "label": "Glossary" + }, + { + "type": "doc", + "id": "requirements", + "label": "Requirements" + }, + { + "type": "doc", + "id": "database-configurations", + "label": "Underlying Database Configurations" + }, + { + "type": "doc", + "id": "releases/release-notes", + "label": "Release Notes" + }, + { + "type": "doc", + "id": "releases/release-support-policy", + "label": "Release Support Policy" + }, + { + "type": "doc", + "id": "roadmap", + "label": "Roadmap" + } + ] + }, + { + "type": "category", + "label": "Quickstart", + "collapsible": true, + "link": { + "type": "doc", + "id": "quickstart-overview" + }, + "items": [ + { + "type": "category", + "label": "Try Running Transactions Through the ScalarDB Core Library", + "collapsible": true, + "link": { + "type": "doc", + "id": "quickstart-scalardb-core-overview" + }, + "items": [ + { + "type": "doc", + "id": "getting-started-with-scalardb", + "label": "Use Java" + }, + { + "type": "doc", + "id": "getting-started-with-scalardb-by-using-kotlin", + "label": "Use Kotlin" + } + ] + }, + { + "type": "category", + "label": "Try Running Transactions Through ScalarDB Cluster", + "collapsible": true, + "link": { + "type": "doc", + "id": "quickstart-scalardb-cluster-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster", + "label": "Use the Java API" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc", + "label": "Use SQL via JDBC" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc", + "label": "Use SQL via Spring Data JDBC" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-graphql", + "label": "Use GraphQL" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-dotnet", + "label": "Use .NET" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-sql-dotnet", + "label": "Use SQL via .NET" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-sql-linq", + "label": "Use SQL via .NET and LINQ" + } + ] + }, + { + "type": "category", + "label": "Try Running Analytical Queries Through ScalarDB Analytics", + "collapsible": true, + "link": { + "type": "doc", + "id": "quickstart-scalardb-analytics-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalardb-samples/scalardb-analytics-spark-sample/README", + "label": "Use Spark as an execution engine" + }, + { + "type": "doc", + "id": "scalardb-analytics-postgresql/getting-started", + "label": "Use PostgreSQL as an execution engine" + } + ] + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-vector-search", + "label": "Try Running Vector Search Through ScalarDB Cluster" + }, + { + "type": "category", + "label": "Reference", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster", + "label": "Use Go for ScalarDB Cluster" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster", + "label": "Use Python for ScalarDB Cluster" + }, + { + "type": "doc", + "id": "scalardb-analytics/design", + "label": "ScalarDB Analytics Design" + }, + { + "type": "doc", + "id": "scalardb-analytics-postgresql/installation", + "label": "Install ScalarDB Analytics with PostgreSQL Locally" + } + ] + } + ] + }, + { + "type": "category", + "label": "Develop", + "collapsible": true, + "link": { + "type": "doc", + "id": "develop-overview" + }, + "items": [ + { + "type": "category", + "label": "Run Transactions", + "collapsible": true, + "link": { + "type": "doc", + "id": "develop-run-transactions-overview" + }, + "items": [ + { + "type": "doc", + "id": "data-modeling", + "label": "Model Your Data" + }, + { + "type": "doc", + "id": "consensus-commit", + "label": "Consensus Commit Protocol" + }, + { + "type": "category", + "label": "Run Through the CRUD Interface", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "run-transactions-through-scalardb-core-library", + "label": "Use the ScalarDB Core Library" + }, + { + "type": "doc", + "id": "scalardb-cluster/run-transactions-through-scalardb-cluster", + "label": "Use ScalarDB Cluster" + } + ] + }, + { + "type": "doc", + "id": "scalardb-cluster/run-transactions-through-scalardb-cluster-sql", + "label": "Run Through the SQL Interface" + }, + { + "type": "category", + "label": "Advanced Configurations and Operations", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/scalardb-auth-with-sql", + "label": "Authenticate and Authorize Users by Using SQL" + }, + { + "type": "doc", + "id": "scalardb-cluster/authorize-with-abac", + "label": "Control User Access in a Fine-Grained Manner" + }, + { + "type": "doc", + "id": "scalardb-cluster/encrypt-data-at-rest", + "label": "Encrypt Data at Rest" + }, + { + "type": "doc", + "id": "scalardb-cluster/encrypt-wire-communications", + "label": "Encrypt Wire Communications" + }, + { + "type": "doc", + "id": "scalardb-benchmarks/README", + "label": "Run Benchmarks" + } + ] + } + ] + }, + { + "type": "category", + "label": "Run Non-Transactional Storage Operations", + "collapsible": true, + "link": { + "type": "doc", + "id": "develop-run-non-transactional-operations-overview" + }, + "items": [ + { + "type": "category", + "label": "Run Through the CRUD Interface", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "run-non-transactional-storage-operations-through-library", + "label": "Use the ScalarDB Core Library" + }, + { + "type": "doc", + "id": "scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster", + "label": "Use ScalarDB Cluster" + } + ] + }, + { + "type": "doc", + "id": "scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface", + "label": "Run Through the SQL Interface" + }, + { + "type": "doc", + "id": "run-non-transactional-storage-operations-through-primitive-crud-interface", + "label": "Run Through the Primitive CRUD Interface" + } + ] + }, + { + "type": "doc", + "id": "scalardb-analytics/run-analytical-queries", + "label": "Run Analytical Queries" + }, + { + "type": "category", + "label": "Run Sample Applications", + "collapsible": true, + "link": { + "type": "doc", + "id": "scalardb-samples/README" + }, + "items": [ + { + "type": "doc", + "id": "scalardb-samples/multi-storage-transaction-sample/README", + "label": "Multi-Storage Transactions" + }, + { + "type": "doc", + "id": "scalardb-samples/microservice-transaction-sample/README", + "label": "Microservice Transactions" + }, + { + "type": "doc", + "id": "scalardb-samples/spring-data-multi-storage-transaction-sample/README", + "label": "Multi-Storage Transactions Through Spring Data JDBC" + }, + { + "type": "doc", + "id": "scalardb-samples/spring-data-microservice-transaction-sample/README", + "label": "Microservice Transactions Through Spring Data JDBC" + }, + { + "type": "doc", + "id": "scalardb-samples/scalardb-analytics-postgresql-sample/README", + "label": "Analytical Queries by Using ScalarDB Analytics with PostgreSQL" + } + ] + }, + { + "type": "category", + "label": "Reference", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "add-scalardb-to-your-build", + "label": "Add ScalarDB to Your Build" + }, + { + "type": "doc", + "id": "configurations", + "label": "ScalarDB Configurations" + }, + { + "type": "doc", + "id": "api-guide", + "label": "API Guide" + }, + { + "type": "doc", + "id": "two-phase-commit-transactions", + "label": "Two-Phase Commit Transactions" + }, + { + "type": "doc", + "id": "multi-storage-transactions", + "label": "Multi-Storage Transactions" + }, + { + "type": "doc", + "id": "schema-loader", + "label": "Schema Loader" + }, + { + "type": "doc", + "id": "scalardb-cluster/index", + "label": "ScalarDB Cluster" + }, + { + "type": "doc", + "id": "scalardb-cluster/compatibility", + "label": "ScalarDB Cluster Compatibility Matrix" + }, + { + "type": "doc", + "id": "scalardb-cluster/deployment-patterns-for-microservices", + "label": "ScalarDB Cluster Deployment Patterns for Microservices" + }, + { + "type": "doc", + "id": "scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api", + "label": "ScalarDB Cluster Java API" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-cluster-configurations", + "label": "ScalarDB Cluster Configurations" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-cluster-grpc-api-guide", + "label": "ScalarDB Cluster gRPC API Guide" + }, + { + "type": "category", + "label": "SQL Interface", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-sql/index", + "label": "Overview" + }, + { + "type": "doc", + "id": "scalardb-sql/jdbc-guide", + "label": "JDBC Guide" + }, + { + "type": "doc", + "id": "scalardb-sql/sql-api-guide", + "label": "API Guide" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-cluster-sql-grpc-api-guide", + "label": "gRPC API Guide" + }, + { + "type": "doc", + "id": "scalardb-sql/spring-data-guide", + "label": "Spring Data Guide" + }, + { + "type": "doc", + "id": "scalardb-sql/grammar", + "label": "Grammar" + } + ] + }, + { + "type": "category", + "label": "GraphQL Interface", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-graphql/index", + "label": "Overview" + }, + { + "type": "doc", + "id": "scalardb-graphql/how-to-run-two-phase-commit-transaction", + "label": "Two-Phase Commit Transactions" + } + ] + }, + { + "type": "category", + "label": "Analytics", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-analytics/README", + "label": "Overview" + }, + { + "type": "doc", + "id": "scalardb-analytics-postgresql/scalardb-fdw", + "label": "ScalarDB FDW for PostgreSQL" + }, + { + "type": "doc", + "id": "scalardb-analytics-postgresql/schema-importer", + "label": "PostgreSQL Schema Importer for PostgreSQL" + } + ] + }, + { + "type": "category", + "label": ".NET", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/index", + "label": "Overview" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions", + "label": "Distributed Transactions" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions", + "label": "Distributed SQL Transactions" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-admin-api", + "label": "Administrative API" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-scalardb-tables-as-csharp-classes", + "label": "Tables as C# Classes" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-aspnet-and-di", + "label": "ASP.NET Core and Dependency Injection" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-linq", + "label": "LINQ" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions", + "label": "Two-Phase Commit Transactions" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-auth", + "label": "Authenticate and Authorize Users" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/exception-handling", + "label": "Handle Exceptions" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/common-reference", + "label": "Common Reference" + } + ] + } + ] + } + ] + }, + { + "type": "category", + "label": "Deploy", + "collapsible": true, + "link": { + "type": "doc", + "id": "deploy-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart", + "label": "Deploy ScalarDB Cluster Locally" + }, + { + "type": "doc", + "id": "scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS", + "label": "Deploy ScalarDB Cluster on Amazon EKS" + }, + { + "type": "doc", + "id": "scalardb-analytics/deployment", + "label": "Deploy ScalarDB Analytics in Public Cloud Environments" + }, + { + "type": "category", + "label": "Reference", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/standalone-mode", + "label": "ScalarDB Cluster Standalone Mode" + }, + { + "type": "doc", + "id": "scalar-kubernetes/ProductionChecklistForScalarDBCluster", + "label": "Production Checklist for ScalarDB Cluster" + }, + { + "type": "category", + "label": "Getting Started Guides", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "helm-charts/getting-started-scalar-helm-charts", + "label": "Use Scalar Helm Charts" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-scalardb-cluster-tls", + "label": "ScalarDB Cluster with TLS by Using a Helm Chart" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-scalardb-cluster-tls-cert-manager", + "label": "ScalarDB Cluster with TLS by Using cert-manager and a Helm Chart" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-scalardb-analytics-postgresql", + "label": "ScalarDB Analytics with PostgreSQL by Using a Helm Chart" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-monitoring", + "label": "Prometheus Operator for Monitoring by Using a Helm Chart" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-logging", + "label": "Loki Stack for Logging by Using a Helm Chart" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-scalar-manager", + "label": "Scalar Manager by Using a Helm Chart" + } + ] + }, + { + "type": "category", + "label": "Database Setup Guides", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/SetupDatabaseForAWS", + "label": "Databases on AWS" + }, + { + "type": "doc", + "id": "scalar-kubernetes/SetupDatabaseForAzure", + "label": "Databases on Azure" + } + ] + }, + { + "type": "category", + "label": "Installation Guides", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/HowToGetContainerImages", + "label": "Get Container Images" + }, + { + "type": "doc", + "id": "scalar-kubernetes/AwsMarketplaceGuide", + "label": "Install From AWS Marketplace" + }, + { + "type": "doc", + "id": "scalar-kubernetes/HowToUseContainerImages", + "label": "Use Container Images" + } + ] + }, + { + "type": "category", + "label": "Deployment Guides", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/CreateEKSClusterForScalarDBCluster", + "label": "Create an EKS Cluster for ScalarDB Cluster" + }, + { + "type": "doc", + "id": "scalar-kubernetes/CreateBastionServer", + "label": "Create a Bastion Server" + }, + { + "type": "doc", + "id": "helm-charts/how-to-deploy-scalardb-cluster", + "label": "Deploy ScalarDB Cluster by Using a Helm Chart" + }, + { + "type": "doc", + "id": "helm-charts/how-to-deploy-scalardb-analytics-postgresql", + "label": "Deploy ScalarDB Analytics with PostgreSQL by Using a Helm Chart" + } + ] + }, + { + "type": "category", + "label": "Configuration Guides", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/AccessScalarProducts", + "label": "Access Kubernetes environment from applications" + }, + { + "type": "doc", + "id": "scalar-kubernetes/HowToCreateKeyAndCertificateFiles", + "label": "Create Private Key and Certificate Files" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-scalardb-cluster", + "label": "Configure a custom values file for ScalarDB Cluster" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-scalardb-analytics-postgresql", + "label": "Configure a Custom Values File for ScalarDB Analytics with PostgreSQL" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-scalar-admin-for-kubernetes", + "label": "Configure a Custom Values File for Scalar Admin for Kubernetes" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-scalar-manager", + "label": "Configure a Custom Values File for Scalar Manager" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-envoy", + "label": "Configure a Custom Values File for Scalar Envoy" + }, + { + "type": "doc", + "id": "helm-charts/mount-files-or-volumes-on-scalar-pods", + "label": "Mount Files or Volumes on ScalarDB Pods" + }, + { + "type": "doc", + "id": "helm-charts/use-secret-for-credentials", + "label": "Use Secret Resources" + } + ] + } + ] + } + ] + }, + { + "type": "category", + "label": "Migrate", + "collapsible": true, + "link": { + "type": "doc", + "id": "migrate-overview" + }, + "items": [ + { + "type": "doc", + "id": "schema-loader-import", + "label": "Import Existing Tables" + }, + { + "type": "doc", + "id": "scalardb-sql/migration-guide", + "label": "Migrate Applications and Databases" + } + ] + }, + { + "type": "category", + "label": "Manage", + "collapsible": true, + "link": { + "type": "doc", + "id": "manage-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/HowToScaleScalarDB", + "label": "Scale" + }, + { + "type": "doc", + "id": "scalar-kubernetes/HowToUpgradeScalarDB", + "label": "Upgrade" + }, + { + "type": "category", + "label": "Monitor", + "collapsible": true, + "link": { + "type": "doc", + "id": "manage-monitor-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalar-manager/overview", + "label": "Scalar Manager Overview" + }, + { + "type": "doc", + "id": "scalar-kubernetes/K8sMonitorGuide", + "label": "Kubernetes Monitoring Guide" + }, + { + "type": "doc", + "id": "helm-charts/how-to-deploy-scalar-admin-for-kubernetes", + "label": "Deploy Scalar Admin for Kubernetes" + } + ] + }, + { + "type": "category", + "label": "Back Up and Restore", + "collapsible": true, + "link": { + "type": "doc", + "id": "manage-backup-and-restore" + }, + "items": [ + { + "type": "doc", + "id": "backup-restore", + "label": "Back Up and Restore Databases Used Through ScalarDB" + }, + { + "type": "doc", + "id": "scalar-kubernetes/BackupNoSQL", + "label": "Back Up a NoSQL Database in Kubernetes" + }, + { + "type": "doc", + "id": "scalar-kubernetes/RestoreDatabase", + "label": "Restore Databases in Kubernetes" + } + ] + } + ] + }, + { + "type": "category", + "label": "Troubleshoot", + "collapsible": true, + "items": [ + { + "type": "category", + "label": "Error Codes", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-core-status-codes", + "label": "ScalarDB Core" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-cluster-status-codes", + "label": "ScalarDB Cluster" + }, + { + "type": "doc", + "id": "scalardb-graphql/scalardb-graphql-status-codes", + "label": "ScalarDB GraphQL" + }, + { + "type": "doc", + "id": "scalardb-sql/scalardb-sql-status-codes", + "label": "ScalarDB SQL" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-auth-status-codes", + "label": "Authentication and Authorization" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-abac-status-codes", + "label": "Attributed-Based Access Control" + } + ] + } + ] + }, + { + "type": "category", + "label": "Reference", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-licensing/index", + "label": "Configure a Product License Key" + } + ] + } + ], + "docsJapanese": [ + { + "type": "doc", + "label": "ScalarDB ドキュメンテーションホーム", + "id": "index" + }, + { + "type": "category", + "label": "ScalarDB について", + "collapsible": true, + "link": { + "type": "doc", + "id": "overview" + }, + "items": [ + { + "type": "doc", + "id": "design", + "label": "デザイン" + }, + { + "type": "doc", + "id": "features", + "label": "機能" + }, + { + "type": "doc", + "id": "glossary", + "label": "用語集" + }, + { + "type": "doc", + "id": "requirements", + "label": "要件" + }, + { + "type": "doc", + "id": "database-configurations", + "label": "データベースの設定" + }, + { + "type": "doc", + "id": "releases/release-notes", + "label": "リリースノート" + }, + { + "type": "doc", + "id": "releases/release-support-policy", + "label": "リリースサポートポリシー" + }, + { + "type": "doc", + "id": "roadmap", + "label": "ロードマップ" + } + ] + }, + { + "type": "category", + "label": "クイックスタート", + "collapsible": true, + "link": { + "type": "doc", + "id": "quickstart-overview" + }, + "items": [ + { + "type": "category", + "label": "ScalarDB Core ライブラリを使用してトランザクションを実行", + "collapsible": true, + "link": { + "type": "doc", + "id": "quickstart-scalardb-core-overview" + }, + "items": [ + { + "type": "doc", + "id": "getting-started-with-scalardb", + "label": "Java を使用" + }, + { + "type": "doc", + "id": "getting-started-with-scalardb-by-using-kotlin", + "label": "Kotlin を使用" + } + ] + }, + { + "type": "category", + "label": "ScalarDB Cluster を使用してトランザクションを実行", + "collapsible": true, + "link": { + "type": "doc", + "id": "quickstart-scalardb-cluster-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster", + "label": "Java API を使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-sql-jdbc", + "label": "JDBC 経由で SQL を使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-sql-spring-data-jdbc", + "label": "Spring Data JDBC 経由で SQL を使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-graphql", + "label": "GraphQL を使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-dotnet", + "label": ".NET を使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-dotnet", + "label": ".NET 経由で SQL を使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-scalardb-cluster-dotnet", + "label": ".NET と LINQ 経由で SQL を使用" + } + ] + }, + { + "type": "category", + "label": "ScalarDB Analytics を使用して分析クエリを実行", + "collapsible": true, + "link": { + "type": "doc", + "id": "quickstart-scalardb-analytics-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalardb-samples/scalardb-analytics-spark-sample/README", + "label": "Spark を実行エンジンとして使用" + }, + { + "type": "doc", + "id": "scalardb-analytics-postgresql/getting-started", + "label": "PostgreSQL を実行エンジンとして使用" + } + ] + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-vector-search", + "label": "ScalarDB Cluster を使用してベクトル検索を実行" + }, + { + "type": "category", + "label": "関連情報", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-using-go-for-scalardb-cluster", + "label": "Go から ScalarDB Cluster を使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/getting-started-with-using-python-for-scalardb-cluster", + "label": "Python から ScalarDB Cluster を使用" + }, + { + "type": "doc", + "id": "scalardb-analytics/design", + "label": "ScalarDB Analytics の設計" + }, + { + "type": "doc", + "id": "scalardb-analytics-postgresql/installation", + "label": "ScalarDB Analytics with PostgreSQL をローカルにインストール" + } + ] + } + ] + }, + { + "type": "category", + "label": "開発", + "collapsible": true, + "link": { + "type": "doc", + "id": "develop-overview" + }, + "items": [ + { + "type": "category", + "label": "トランザクションを実行", + "collapsible": true, + "link": { + "type": "doc", + "id": "develop-run-transactions-overview" + }, + "items": [ + { + "type": "doc", + "id": "data-modeling", + "label": "データモデリング" + }, + { + "type": "doc", + "id": "consensus-commit", + "label": "Consensus Commit プロトコル" + }, + { + "type": "category", + "label": "CRUD インターフェースを使用して実行", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "run-transactions-through-scalardb-core-library", + "label": "ScalarDB Core ライブラリーを使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/run-transactions-through-scalardb-cluster", + "label": "ScalarDB Cluster を使用" + } + ] + }, + { + "type": "doc", + "id": "scalardb-cluster/run-transactions-through-scalardb-cluster-sql", + "label": "SQL インターフェースを使用して実行" + }, + { + "type": "category", + "label": "高度な設定と操作", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/scalardb-auth-with-sql", + "label": "SQL を使用してユーザーを認証および承認" + }, + { + "type": "doc", + "id": "scalardb-cluster/authorize-with-abac", + "label": "ユーザアクセスを細かく制御" + }, + { + "type": "doc", + "id": "scalardb-cluster/encrypt-data-at-rest", + "label": "保存データを暗号化" + }, + { + "type": "doc", + "id": "scalardb-cluster/encrypt-wire-communications", + "label": "ワイヤ通信を暗号化" + }, + { + "type": "doc", + "id": "scalardb-benchmarks/README", + "label": "ベンチマークを実行" + } + ] + } + ] + }, + { + "type": "category", + "label": "非トランザクションストレージ操作を実行", + "collapsible": true, + "link": { + "type": "doc", + "id": "develop-run-non-transactional-operations-overview" + }, + "items": [ + { + "type": "category", + "label": "CRUD インターフェースを使用して実行", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "run-non-transactional-storage-operations-through-library", + "label": "ScalarDB Core ライブラリーを使用" + }, + { + "type": "doc", + "id": "scalardb-cluster/run-non-transactional-storage-operations-through-scalardb-cluster", + "label": "ScalarDB Cluster を使用" + } + ] + }, + { + "type": "doc", + "id": "scalardb-cluster/run-non-transactional-storage-operations-through-sql-interface", + "label": "SQL インターフェースを使用して実行" + }, + { + "type": "doc", + "id": "run-non-transactional-storage-operations-through-primitive-crud-interface", + "label": "プリミティブ CRUD インターフェースを使用して実行" + } + ] + }, + { + "type": "doc", + "id": "scalardb-analytics/run-analytical-queries", + "label": "ScalarDB Analytics を通じた分析クエリの実行" + }, + { + "type": "category", + "label": "サンプルアプリケーションを実行", + "collapsible": true, + "link": { + "type": "doc", + "id": "scalardb-samples/README" + }, + "items": [ + { + "type": "doc", + "id": "scalardb-samples/multi-storage-transaction-sample/README", + "label": "マルチストレージトランザクション" + }, + { + "type": "doc", + "id": "scalardb-samples/microservice-transaction-sample/README", + "label": "マイクロサービストランザクション" + }, + { + "type": "doc", + "id": "scalardb-samples/spring-data-multi-storage-transaction-sample/README", + "label": "Spring Data JDBC によるマルチストレージトランザクション" + }, + { + "type": "doc", + "id": "scalardb-samples/spring-data-microservice-transaction-sample/README", + "label": "Spring Data JDBC によるマイクロサービストランザクション" + }, + { + "type": "doc", + "id": "scalardb-samples/scalardb-analytics-postgresql-sample/README", + "label": "ScalarDB Analytics with PostgreSQL を使用した分析クエリ" + } + ] + }, + { + "type": "category", + "label": "詳細", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "add-scalardb-to-your-build", + "label": "ビルドに ScalarDB を追加" + }, + { + "type": "doc", + "id": "configurations", + "label": "ScalarDB の設定" + }, + { + "type": "doc", + "id": "api-guide", + "label": "API ガイド" + }, + { + "type": "doc", + "id": "two-phase-commit-transactions", + "label": "2フェーズコミットトランザクション" + }, + { + "type": "doc", + "id": "multi-storage-transactions", + "label": "マルチストレージトランザクション" + }, + { + "type": "doc", + "id": "schema-loader", + "label": "Schema Loader" + }, + { + "type": "doc", + "id": "scalardb-cluster/index", + "label": "ScalarDB Cluster" + }, + { + "type": "doc", + "id": "scalardb-cluster/compatibility", + "label": "ScalarDB Cluster 互換性マトリックス" + }, + { + "type": "doc", + "id": "scalardb-cluster/deployment-patterns-for-microservices", + "label": "マイクロサービスにおける ScalarDB Cluster のデプロイパターン" + }, + { + "type": "doc", + "id": "scalardb-cluster/developer-guide-for-scalardb-cluster-with-java-api", + "label": "ScalarDB Cluster Java API" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-cluster-configurations", + "label": "ScalarDB Cluster の設定" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-cluster-grpc-api-guide", + "label": "ScalarDB Cluster gRPC API ガイド" + }, + { + "type": "category", + "label": "SQL インターフェース", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-sql/index", + "label": "概要" + }, + { + "type": "doc", + "id": "scalardb-sql/jdbc-guide", + "label": "JDBC ガイド" + }, + { + "type": "doc", + "id": "scalardb-sql/sql-api-guide", + "label": "API ガイド" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-cluster-sql-grpc-api-guide", + "label": "gRPC API ガイド" + }, + { + "type": "doc", + "id": "scalardb-sql/spring-data-guide", + "label": "Spring Data ガイド" + }, + { + "type": "doc", + "id": "scalardb-sql/grammar", + "label": "文法" + } + ] + }, + { + "type": "category", + "label": "GraphQL インターフェース", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-graphql/index", + "label": "概要" + }, + { + "type": "doc", + "id": "scalardb-graphql/how-to-run-two-phase-commit-transaction", + "label": "2フェーズコミットトランザクション" + } + ] + }, + { + "type": "category", + "label": "分析", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-analytics/README", + "label": "概要" + }, + { + "type": "doc", + "id": "scalardb-analytics-postgresql/scalardb-fdw", + "label": "PostgreSQL 用 ScalarDB FDW" + }, + { + "type": "doc", + "id": "scalardb-analytics-postgresql/schema-importer", + "label": "PostgreSQL 用 Schema Importer" + } + ] + }, + { + "type": "category", + "label": ".NET", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/index", + "label": "概要" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-transactions", + "label": "分散トランザクション" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-distributed-sql-transactions", + "label": "分散 SQL トランザクション" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-admin-api", + "label": "Administrative API" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-scalardb-tables-as-csharp-classes", + "label": "C# クラスとしてのテーブル" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-aspnet-and-di", + "label": "ASP.NET Core と依存性注入" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-linq", + "label": "LINQ" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-two-phase-commit-transactions", + "label": "2フェーズコミットトランザクション" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/getting-started-with-auth", + "label": "ユーザーを認証および認可" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/exception-handling", + "label": "例外処理" + }, + { + "type": "doc", + "id": "scalardb-cluster-dotnet-client-sdk/common-reference", + "label": "共通参照" + } + ] + } + ] + } + ] + }, + { + "type": "category", + "label": "デプロイ", + "collapsible": true, + "link": { + "type": "doc", + "id": "deploy-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/setup-scalardb-cluster-on-kubernetes-by-using-helm-chart", + "label": "ScalarDB Cluster をローカルにデプロイ" + }, + { + "type": "doc", + "id": "scalar-kubernetes/ManualDeploymentGuideScalarDBClusterOnEKS", + "label": "Amazon EKS に ScalarDB Cluster をデプロイ" + }, + { + "type": "doc", + "id": "scalardb-analytics/deployment", + "label": "パブリッククラウド環境への ScalarDB Analytics のデプロイ" + }, + { + "type": "category", + "label": "詳細", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-cluster/standalone-mode", + "label": "ScalarDB Cluster スタンドアロンモード" + }, + { + "type": "doc", + "id": "scalar-kubernetes/ProductionChecklistForScalarDBCluster", + "label": "ScalarDB Cluster の本番環境チェックリスト" + }, + { + "type": "category", + "label": "Getting Started Guides", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "helm-charts/getting-started-scalar-helm-charts", + "label": "Scalar Helm Charts をはじめよう" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-scalardb-cluster-tls", + "label": "Helm Chart を使用した TLS 対応 ScalarDB Cluster" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-scalardb-cluster-tls-cert-manager", + "label": "cert-manager と Helm Chart を使用した TLS 対応 ScalarDB Cluster" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-scalardb-analytics-postgresql", + "label": "Helm Chart を使用した ScalarDB Analytics with PostgreSQL" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-monitoring", + "label": "Helm Chart を使用した監視用 Prometheus Operator" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-logging", + "label": "Helm Chart を使用したログ記録用 Loki スタック" + }, + { + "type": "doc", + "id": "helm-charts/getting-started-scalar-manager", + "label": "Helm Chart を使用した Scalar Manager" + } + ] + }, + { + "type": "category", + "label": "データベースセットアップガイド", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/SetupDatabaseForAWS", + "label": "AWS が提供するデータベース" + }, + { + "type": "doc", + "id": "scalar-kubernetes/SetupDatabaseForAzure", + "label": "Azure が提供するデータベース" + } + ] + }, + { + "type": "category", + "label": "インストールガイド", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/HowToGetContainerImages", + "label": "コンテナイメージを取得" + }, + { + "type": "doc", + "id": "scalar-kubernetes/AwsMarketplaceGuide", + "label": "AWS Marketplace からインストール" + }, + { + "type": "doc", + "id": "scalar-kubernetes/HowToUseContainerImages", + "label": "コンテナイメージを使用" + } + ] + }, + { + "type": "category", + "label": "デプロイメントガイド", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/CreateEKSClusterForScalarDBCluster", + "label": "ScalarDB Cluster 用の EKS クラスターを作成" + }, + { + "type": "doc", + "id": "scalar-kubernetes/CreateBastionServer", + "label": "踏み台サーバーを作成" + }, + { + "type": "doc", + "id": "helm-charts/how-to-deploy-scalardb-cluster", + "label": "Helm Chart を使用して ScalarDB Cluster をデプロイ" + }, + { + "type": "doc", + "id": "helm-charts/how-to-deploy-scalardb-analytics-postgresql", + "label": "Helm Chart を使用して ScalarDB Analytics with PostgreSQL をデプロイ" + } + ] + }, + { + "type": "category", + "label": "設定のガイド", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/AccessScalarProducts", + "label": "アプリケーションから Kubernetes 環境にアクセス" + }, + { + "type": "doc", + "id": "scalar-kubernetes/HowToCreateKeyAndCertificateFiles", + "label": "秘密鍵と証明書ファイルを作成" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-scalardb-cluster", + "label": "ScalarDB Cluster のカスタム値ファイルを構成" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-scalardb-analytics-postgresql", + "label": "ScalarDB Analytics with PostgreSQL のカスタム値ファイルを構成" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-scalar-admin-for-kubernetes", + "label": "Scalar Admin for Kubernetes のカスタム値ファイルを構成" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-scalar-manager", + "label": "Scalar Manager のカスタム値ファイルを構成" + }, + { + "type": "doc", + "id": "helm-charts/configure-custom-values-envoy", + "label": "Scalar Envoy のカスタム値ファイルを構成" + }, + { + "type": "doc", + "id": "helm-charts/mount-files-or-volumes-on-scalar-pods", + "label": "ScalarDB ポッドにファイルまたはボリュームをマウント" + }, + { + "type": "doc", + "id": "helm-charts/use-secret-for-credentials", + "label": "シークレットリソースを使用" + } + ] + } + ] + } + ] + }, + { + "type": "category", + "label": "移行", + "collapsible": true, + "link": { + "type": "doc", + "id": "migrate-overview" + }, + "items": [ + { + "type": "doc", + "id": "schema-loader-import", + "label": "既存のテーブルをインポート" + }, + { + "type": "doc", + "id": "scalardb-sql/migration-guide", + "label": "アプリケーションとデータベースの移行" + } + ] + }, + { + "type": "category", + "label": "運用", + "collapsible": true, + "link": { + "type": "doc", + "id": "manage-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalar-kubernetes/HowToScaleScalarDB", + "label": "スケーリング" + }, + { + "type": "doc", + "id": "scalar-kubernetes/HowToUpgradeScalarDB", + "label": "アップグレード" + }, + { + "type": "category", + "label": "監視", + "collapsible": true, + "link": { + "type": "doc", + "id": "manage-monitor-overview" + }, + "items": [ + { + "type": "doc", + "id": "scalar-manager/overview", + "label": "Scalar Manager の概要" + }, + { + "type": "doc", + "id": "scalar-kubernetes/K8sMonitorGuide", + "label": "Kubernetes モニタリングガイド" + }, + { + "type": "doc", + "id": "helm-charts/how-to-deploy-scalar-admin-for-kubernetes", + "label": "Kubernetes 用の Scalar Admin をデプロイ" + } + ] + }, + { + "type": "category", + "label": "バックアップと復元", + "collapsible": true, + "link": { + "type": "doc", + "id": "manage-backup-and-restore" + }, + "items": [ + { + "type": "doc", + "id": "backup-restore", + "label": "ScalarDB を通じて使用されるデータベースのバックアップと復元" + }, + { + "type": "doc", + "id": "scalar-kubernetes/BackupNoSQL", + "label": "Kubernetes で NoSQL データベースをバックアップ" + }, + { + "type": "doc", + "id": "scalar-kubernetes/RestoreDatabase", + "label": "Kubernetes でデータベースを復元" + } + ] + } + ] + }, + { + "type": "category", + "label": "トラブルシュート", + "collapsible": true, + "items": [ + { + "type": "category", + "label": "エラーコード", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalardb-core-status-codes", + "label": "ScalarDB Core" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-cluster-status-codes", + "label": "ScalarDB Cluster" + }, + { + "type": "doc", + "id": "scalardb-graphql/scalardb-graphql-status-codes", + "label": "ScalarDB GraphQL" + }, + { + "type": "doc", + "id": "scalardb-sql/scalardb-sql-status-codes", + "label": "ScalarDB SQL" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-auth-status-codes", + "label": "認証と認可" + }, + { + "type": "doc", + "id": "scalardb-cluster/scalardb-abac-status-codes", + "label": "属性ベースのアクセス制御" + } + ] + } + ] + }, + { + "type": "category", + "label": "関連情報", + "collapsible": true, + "items": [ + { + "type": "doc", + "id": "scalar-licensing/index", + "label": "製品ライセンスキーの設定" + } + ] + } + ] +} diff --git a/versions.json b/versions.json index 8ae18153..07b7b0fd 100644 --- a/versions.json +++ b/versions.json @@ -1,4 +1,5 @@ [ + "3.15", "3.14", "3.13", "3.12",