edit-icon download-icon

Primary key column auto-increment

Last Updated: Mar 20, 2018

C++ SDK supports auto increments in primary key columns. If you set a primary key column to be an auto-increment column, when you write a row of data, leave the value of this column empty, as Table Store automatically generates this value. This generated value is unique on the partition key and obeys a strict incremental order. See Auto increments in primary key columns for more information.

Create a table

Note: An auto-increment primary key column must be an integer and PrimaryKeyColumnSchema::AutoIncrement must be set.

  1. CreateTableRequest req;
  2. {
  3. // immutable configurations of the table
  4. TableMeta& meta = req.mutableMeta();
  5. meta.mutableTableName() = kTableName;
  6. Schema& schema = meta.mutableSchema();
  7. {
  8. PrimaryKeyColumnSchema& pkColSchema = schema.append();
  9. pkColSchema.mutableName() = "ShardKey";
  10. pkColSchema.mutableType() = kPKT_String;
  11. }
  12. {
  13. PrimaryKeyColumnSchema& pkColSchema = schema.append();
  14. pkColSchema.mutableName() = "AutoIncrKey";
  15. pkColSchema.mutableType() = kPKT_Integer;
  16. pkColSchema.mutableOption().reset(PrimaryKeyColumnSchema::AutoIncrement);
  17. }
  18. }
  19. CreateTableResponse resp;
  20. Optional<OTSError> res = client.createTable(resp, req);

Write data

The value of an auto-increment primary key column is filled by the Table Store service. Therefore, the primary key column must be filled with a special placeholder when writing. PrimaryKeyValue::toAutoIncrement() can obtain this placeholder object. To read this row of data, you can set the return value to include the primary key. The Table Store service replaces the placeholder for the auto-increment primary key column in the primary key with the actual column values before returning them. You can record this primary key for subsequent use.

This example is based on a single-row overwrite. Writing with other interfaces is similar.

  1. PutRowRequest req;
  2. {
  3. RowPutChange& chg = req.mutableRowChange();
  4. chg.mutableTable() = kTableName;
  5. chg.mutableReturnType() = RowChange::kRT_PrimaryKey;
  6. PrimaryKey& pkey = chg.mutablePrimaryKey();
  7. pkey.append() = PrimaryKeyColumn(
  8. "ShardKey",
  9. PrimaryKeyValue::toStr("shard0"));
  10. pkey.append() = PrimaryKeyColumn(
  11. "AutoIncrKey",
  12. PrimaryKeyValue::toAutoIncrement());
  13. }
Thank you! We've received your feedback.