Este tópico descreve como configurar uma coluna de chave primária com incremento automático em uma tabela, gravar dados nessa coluna e obter os valores gerados com o Tablestore SDK for Go.
Considerações
Os valores gerados para uma coluna de incremento automático são únicos e estritamente crescentes (monotônicos) no nível da chave de partição, mas não necessariamente consecutivos.
Pré-requisitos
Configure uma coluna de chave primária com incremento automático
Defina uma coluna de chave primária sem partição como incremento automático durante a criação da tabela. Essa configuração não se aplica a tabelas existentes.
Apenas colunas de chave primária sem partição do tipo inteiro podem ter incremento automático. Uma tabela admite no máximo uma coluna desse tipo, que gera valores inteiros assinados de 64 bits.
Código de exemplo
O código abaixo crie uma tabela chamada test_table. A chave primária inclui a chave de partição id e a coluna de incremento automático incr.
func CreateTableSample(client *tablestore.TableStoreClient) {
tableMeta := new(tablestore.TableMeta)
tableMeta.TableName = "test_table"
tableMeta.AddPrimaryKeyColumn("id", tablestore.PrimaryKeyType_STRING)
tableMeta.AddPrimaryKeyColumnOption("incr", tablestore.PrimaryKeyType_INTEGER, tablestore.AUTO_INCREMENT)
tableOption := new(tablestore.TableOption)
tableOption.MaxVersion = 1
tableOption.TimeToAlive = -1
reservedThroughput := new(tablestore.ReservedThroughput)
createTableRequest := new(tablestore.CreateTableRequest)
createTableRequest.TableMeta = tableMeta
createTableRequest.TableOption = tableOption
createTableRequest.ReservedThroughput = reservedThroughput
_, err := client.CreateTable(createTableRequest)
if err != nil {
fmt.Println("Failed to create table with error:", err)
} else {
fmt.Println("Create table finished.")
}
}
Gravar dados
Ao gravar dados em uma coluna de incremento automático, use um espaço reservado para o valor. Para recuperar o valor gerado e utilizá-lo em consultas e atualizações, defina o tipo de retorno de putRowChange como ReturnType_RT_PK.
Código de exemplo
O exemplo a seguir grava uma linha de dados na tabela test_table, obtém as informações de chave primária da linha inserida e as exibe.
func PutRowSample(client *tablestore.TableStoreClient) {
// Construct the primary key
putPrimaryKey := new(tablestore.PrimaryKey)
putPrimaryKey.AddPrimaryKeyColumn("id", "row1")
// Set the auto-increment column
putPrimaryKey.AddPrimaryKeyColumnWithAutoIncrement("incr")
// Construct the row data to write
putRowChange := new(tablestore.PutRowChange)
putRowChange.TableName = "test_table"
putRowChange.PrimaryKey = putPrimaryKey
putRowChange.AddColumn("col1", "val1")
putRowChange.SetCondition(tablestore.RowExistenceExpectation_IGNORE)
// Set the return type to ReturnType_RT_PK to return the primary key information of the written row
putRowChange.ReturnType = tablestore.ReturnType_RT_PK
// Call the putRow method to write the row data
putRowRequest := new(tablestore.PutRowRequest)
putRowRequest.PutRowChange = putRowChange
response, err := client.PutRow(putRowRequest)
if err != nil {
fmt.Println("Failed to put row with error:", err)
} else {
// RequestId and consumed CU
fmt.Printf("RequestId: %s \n", response.RequestId)
fmt.Printf("Read CU Cost: %d \n", response.ConsumedCapacityUnit.Read)
fmt.Printf("Write CU Cost: %d \n", response.ConsumedCapacityUnit.Write)
// Get and print the returned primary key information. If the return type is not set to ReturnType_RT_PK, the primary key information is not returned by default
fmt.Println(response.PrimaryKey)
}
}