Allow specifying a limit constraint for json column types
- Dominant language
- Go
- Stars
- 40.5k
- Forks
- 6.2k
- PR merge metrics
- PR metrics pending
Description
## Feature Request
**Is your feature request related to a problem? Please describe:**
I am unable to put constraints on the json type.
**Describe the feature you'd like:**
I would like to restrict the `json` type to a maximum of 32768. I can do this for varchar columns but I cannot do it for json columns. i.e.:
```sql
CREATE TABLE `Files` (
`Id` binary(16) NOT NULL DEFAULT UUID_TO_BIN(UUID(), true),
`Metadata` json NULL,
CONSTRAINT `PK_Files` PRIMARY KEY (`Id`)
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
```
**Describe alternatives you've considered:**
Using a string column.
Another alternative would be a checked constraint (I am unsure the implication this has on performance):
```sql
SET GLOBAL tidb_enable_check_constraint = ON;
CREATE TABLE `Files` (
`Id` binary(16) NOT NULL DEFAULT UUID_TO_BIN(UUID(), true),
`Metadata` json NULL,
CONSTRAINT `PK_Files` PRIMARY KEY (`Id`),
CONSTRAINT `CK_Files_Metadata` CHECK (LENGTH(Metadata) <= 32768)
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
```
Another alternative would be a before insert trigger, but TiDB doesn't support triggers:
```sql
DELIMITER $$
CREATE TRIGGER `before_insert_files_validate_metadata`
BEFORE INSERT ON `Files`
FOR EACH ROW
BEGIN
DECLARE metadata_size INT;
-- Check if Metadata is not NULL
IF NEW.Metadata IS NOT NULL THEN
SET metadata_size = LENGTH(NEW.Metadata);
-- Block insert if metadata exceeds 32768 bytes
IF metadata_size > 32768 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Metadata exceeds maximum allowed size of 32768 bytes';
END IF;
END IF;
END$$
DELIMITER ;
```
**Teachability, Documentation, Adoption, Migration Strategy:**
I want to restrict the limits to this data type at the database level.
Contributor guide
Assessment
This issue has not been assessed yet.