unique key
Introduction
Verify that the values in a column or set of columns in a request parameter map are unique.
Example
Assume that there is a human resources system department table with the following table structure:
CREATE TABLE `departments` (
`dept_no` char(4) NOT NULL,
`dept_name` varchar(40) NOT NULL,
PRIMARY KEY (`dept_no`),
UNIQUE KEY `dept_name` (`dept_name`)
)
Check rule constraints
- The department number is used as the primary key field and is unique. For more details about the primary key, see Primary Key
- The department name dept_name is used as the unique key and is unique
Example 1: Successful request
Add a new record with a department name that does not exist in the data table
POST http://127.0.0.1:21000
Content-Type: application/json;charset=utf-8
{
"jsonrpc": "2.0",
"method": "hrm.departments.add",
"params": {
"deptNo": "d234",
"deptName": "Human Resources"
},
"id": "client-unique-request-id"
}
Response
The response result of the above request is that the object returned after successful insertion contains the primary key name and value.
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"jsonrpc": "2.0",
"result": {
"deptNo": "d234"
},
"id": "client-unique-request-id"
}
Example 2: Failed request--department name already exists
Now we try to add a department record with the same name
POST http://127.0.0.1:21000
Content-Type: application/json;charset=utf-8
{
"jsonrpc": "2.0",
"method": "hrm.departments.add",
"params": {
"deptNo": "d235",
"deptName": "Human Resources"
},
"id": "client-unique-request-id"
}
Response results
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{
"jsonrpc": "2.0",
"error": {
"code": -32600,
"message": "checking for unique key conflicts: duplicate unique key in hrm.departments map[deptName:Human Resources]",
"data": {
"errorCode": "EU.Constraint.UK.Duplicated",
"errorDetails": [
{
"constraint": "UniqueKeyDuplicated",
"field": "deptName",
"fieldValue": "Human Resources",
"location": "hrm.departments",
"message": "duplicate unique key in hrm.departments.dept_name Human Resources"
}
],
"errorMessage": "duplicate unique key in hrm.departments map[deptName:Human Resources]"
}
},
"id": "client-unique-request-id"
}
It can be seen that dept_name is duplicated, unique key constraint verification failed, the request was intercepted, and Luwak refused to write.
Above example Tested on Luwak 1.12.9