# How Chat2DB Redis Key Management Handles TTL and Data Types

> Discover how Chat2DB's Redis key management efficiently handles TTL and data types using TTL commands and a TypeScript enum for precise Redis operations.

- Repository: [OtterMind/Chat2DB](https://github.com/OtterMind/Chat2DB)
- Tags: internals
- Published: 2026-07-26

---

**Chat2DB's Redis key management service executes the `TTL` command to read expiration times, appends `EX` arguments during key creation, and uses the `RedisDataType` enum to map Redis type strings to concrete `ITypeScript` implementations for type-specific operations.**

Chat2DB provides a SQL-like abstraction layer over native Redis commands, enabling unified key management across diverse data structures. The implementation in the `OtterMind/Chat2DB` repository centralizes TTL handling and type detection within dedicated executor classes and builder utilities. This architecture allows Chat2DB Redis key management to treat expiration times and data type variations as consistent, queryable properties.

## Reading and Writing TTL in Chat2DB

The service manages time-to-live through explicit Redis command execution and constant-based field mapping defined in [`RedisConstants.java`](https://github.com/OtterMind/Chat2DB/blob/main/RedisConstants.java).

### Retrieving Key Expiration

When reading a key, the `RedisScriptExecutor` class invokes `getTtl(key)` to execute the `TTL %s` command. The returned string value—where `"-1"` indicates no expiration—is stored in the `FIELD_TTL` constant.

```java
String ttl = RedisScriptExecutor.getInstance()
    .getTtl("myKey");                // Executes: TTL myKey
// ttl is a string ("-1" means no expiration)

```

### Applying TTL During Creation

During key creation, the TTL attaches to the command string via `COMMAND_EXPIRE_ARGUMENT_PREFIX` (`EX <seconds>`). The `StringTypeScript` class and other type-specific implementations generate commands that include this expiration argument.

```java
RedisKey newKey = new RedisKey();
newKey.setName("session:123");
newKey.setValue("payload");
newKey.setTtl(300L);               // 5 minutes

List<String> cmds = new StringTypeScript()
    .createKey(newKey);
// cmds contains: SET session:123 "payload" EX 300

```

### Batch Renaming and TTL Updates

For rename or update operations, `RedisSqlBuilder#renameOrUpdateTtl` checks the `FIELD_TTL` entry in the result map. If present, it appends `EXPIRE <key> <ttl>` to a multi-command batch wrapped in `MULTI`/`EXEC` transactions.

```java
Map<String, Object> extra = Map.of(
    RedisConstants.FIELD_KEY, "newKeyName",
    RedisConstants.FIELD_TTL, "600"      // 10 minutes
);

String multiCmd = new StringBuilder()
    .append(RedisConstants.REDIS_MULTI_COMMAND)               // MULTI
    .append(RedisSqlBuilder.renameOrUpdateTtl(
        new QueryResponse().setTableName("oldKey").setExtra(extra)))
    .append(RedisConstants.REDIS_EXEC_COMMAND)                // EXEC
    .toString();
// Resulting script runs: RENAME oldKey newKeyName; EXPIRE newKeyName 600

```

## Data Type Detection and Script Selection

Chat2DB handles Redis's type system through enum-based routing and strategy-pattern implementations located in the `enums/type` and `type` packages.

### Type Detection via `getKeyType`

The service determines a key's data type using `COMMAND_TYPE_KEY` (`type %s`) executed through `RedisScriptExecutor#getKeyType`. The raw type string (e.g., `"string"`, `"list"`) populates the `FIELD_KEY_TYPE` entry in the result map.

```java
String rawType = RedisScriptExecutor.getInstance()
    .getKeyType("myList");           // Executes: type myList   →  "list"

```

### The `RedisDataType` Enum Strategy

`RedisDataType.fromCode(typeString)` maps the raw type to an enum constant (`STRING`, `LIST`, `SET`, `ZSET`, `HASH`, `STREAM`). Each enum value provides a concrete `ITypeScript` implementation (e.g., `StringTypeScript`, `ListTypeScript`) capable of generating type-specific commands.

```java
RedisDataType type = RedisDataType.fromCode(rawType);
ITypeScript script = type.getScript();   // Returns ListTypeScript

```

### Type-Specific Command Generation

The selected script object generates appropriate commands for reading, creating, or updating its specific data type. For example, `ListTypeScript` produces `LRANGE` commands, while `StringTypeScript` generates `SET` operations.

```java
// Use the script to read the whole list
String readCmd = script.getKey(new RedisKey("myList"));
// readCmd = "LRANGE myList 0 -1"

```

## Summary

- **TTL Retrieval**: `RedisScriptExecutor#getTtl` executes the `TTL` command and stores results using the `FIELD_TTL` constant defined in [`RedisConstants.java`](https://github.com/OtterMind/Chat2DB/blob/main/RedisConstants.java).
- **TTL Persistence**: New keys include expiration via `EX` arguments, while updates use `EXPIRE` commands appended by `RedisSqlBuilder#renameOrUpdateTtl`.
- **Type Detection**: `RedisScriptExecutor#getKeyType` executes `TYPE` commands, mapping results to `FIELD_KEY_TYPE`.
- **Type Routing**: The `RedisDataType` enum converts type strings to concrete `ITypeScript` implementations like `StringTypeScript` or `ListTypeScript`.
- **Command Generation**: Type-specific script classes generate native Redis commands appropriate to the key's data structure.

## Frequently Asked Questions

### How does Chat2DB retrieve the TTL of an existing Redis key?

Chat2DB retrieves TTL by calling `RedisScriptExecutor.getInstance().getTtl(key)`, which executes the native `TTL` command against the Redis instance. The method returns a string representation of the remaining seconds, where `"-1"` indicates the key has no expiration time set.

### What happens to the TTL when a key is renamed in Chat2DB?

When renaming a key, the `RedisSqlBuilder.renameOrUpdateTtl` method checks for the `FIELD_TTL` entry in the operation's extra map. If a TTL value exists, it appends an `EXPIRE` command to the multi-command batch after the `RENAME` operation, ensuring the expiration time persists on the new key name.

### How does Chat2DB determine which commands to use for different Redis data types?

The service executes `TYPE` via `RedisScriptExecutor#getKeyType` to obtain the raw type string, then passes this to `RedisDataType.fromCode()` to retrieve the appropriate enum constant. Each enum value returns a specific `ITypeScript` implementation (such as `HashTypeScript` or `ZSetTypeScript`) that generates commands tailored to that data structure's protocol.

### Where does Chat2DB store TTL information when returning query results?

TTL information is stored in the result map under the `FIELD_TTL` constant defined in [`RedisConstants.java`](https://github.com/OtterMind/Chat2DB/blob/main/RedisConstants.java). This field accompanies the key data through the result set, allowing the UI or subsequent operations to display or modify the expiration time as needed.