# oceanbase-database_management

Part of **OCEANBASE**

# OceanBase Database Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| View Cluster Events | Synchronous | Access historical events related to cluster operations and changes. |

## API Calling Mode

### Authentication
OceanBase Database Management APIs for system views like `v$ob_cluster_event_history` do not use HTTP-based authentication. Instead, access is granted through standard database credentials (username and password) when connecting to the OceanBase cluster via a MySQL- or Oracle-compatible client.

- Use your tenant username and password to establish a database connection.
- Required privilege: Typically requires `SELECT` access on system views (often granted to DBA or monitoring roles).
- Environment variable recommendation: Store credentials securely using `OCEANBASE_USER` and `OCEANBASE_PASSWORD`.

> **Note**: This is a database-level API accessed via SQL, not an HTTP REST API. Authentication follows standard relational database practices.

### Service Endpoint
There is no HTTP endpoint for this capability. Instead, connect directly to your OceanBase cluster using a supported client (e.g., MySQL CLI, JDBC, ODC).

- Connection string format (MySQL mode):  
  `mysql -h<host> -P<port> -u<user>@<tenant> -p`
- Common regions for Alibaba Cloud ApsaraDB for OceanBase:  
  `cn-hangzhou`, `cn-shanghai`, `cn-beijing`

### Synchronous Query Pattern
This API uses a standard synchronous SQL query pattern:

1. Establish a connection to the OceanBase tenant using a database client.
2. Execute a `SELECT` statement against the `v$ob_cluster_event_history` system view.
3. Process the result set immediately—no polling or async handling is needed.

Example query:
```sql
SELECT facility, severity, error_code, timestamp, message
FROM v$ob_cluster_event_history
ORDER BY timestamp DESC
LIMIT 10;
```

## Parameter Reference

### View Cluster Events

The `v$ob_cluster_event_history` view does not accept input parameters. It is a read-only system view that returns all recorded cluster events. Filtering is done via standard SQL `WHERE` clauses.

| Column | Type | Required | Default | Constraints | Description |
|--------|------|----------|---------|-------------|-------------|
| facility | VARCHAR | No | — | — | Component or module that generated the event (e.g., "SWITCHOVER", "FAILOVER") |
| severity | VARCHAR | No | — | Enum: INFO, WARNING, ERROR, CRITICAL | Event severity level |
| error_code | INT | No | — | — | Numeric error code associated with the event |
| timestamp | DATETIME | No | — | — | Time when the event occurred |
| message | TEXT | No | — | — | Human-readable description of the event |

## Code Examples

### Query Cluster Events - Python - cn-hangzhou

```python
import pymysql

# Connect to OceanBase tenant (MySQL mode)
conn = pymysql.connect(
    host='your-oceanbase-host.region.rds.aliyuncs.com',
    port=3306,
    user='your_user@your_tenant',
    password='your_password',
    database='oceanbase'
)

try:
    with conn.cursor() as cursor:
        cursor.execute("""
            SELECT facility, severity, error_code, timestamp, message
            FROM v$ob_cluster_event_history
            WHERE severity IN ('ERROR', 'CRITICAL')
            ORDER BY timestamp DESC
            LIMIT 20
        """)
        events = cursor.fetchall()
        for event in events:
            print(f"[{event[3]}] {event[0]} - {event[1]}: {event[4]} (Code: {event[2]})")
finally:
    conn.close()
```

### Query Cluster Events - Java - cn-shanghai

```java
import java.sql.*;

public class OceanBaseClusterEvents {
    public static void main(String[] args) {
        String url = "jdbc:mysql://your-oceanbase-host.cn-shanghai.rds.aliyuncs.com:3306/oceanbase";
        String user = "your_user@your_tenant";
        String password = "your_password";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(
                 "SELECT facility, severity, error_code, timestamp, message " +
                 "FROM v$ob_cluster_event_history " +
                 "ORDER BY timestamp DESC LIMIT 10")) {

            while (rs.next()) {
                System.out.printf("[%s] %s - %s: %s (Code: %d)%n",
                    rs.getTimestamp("timestamp"),
                    rs.getString("facility"),
                    rs.getString("severity"),
                    rs.getString("message"),
                    rs.getInt("error_code"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
```

### Query Cluster Events - Bash (MySQL CLI) - Any Region

```bash
#!/bin/bash
export OB_HOST="your-oceanbase-host.region.rds.aliyuncs.com"
export OB_USER="your_user@your_tenant"
export OB_PASS="your_password"

mysql -h"$OB_HOST" -u"$OB_USER" -p"$OB_PASS" -D oceanbase -e "
SELECT 
  facility, 
  severity, 
  error_code, 
  timestamp, 
  message 
FROM v\$ob_cluster_event_history 
WHERE timestamp > NOW() - INTERVAL 1 DAY
ORDER BY timestamp DESC;
"
```

### Filter Switchover Events - Python - cn-beijing

```python
import mysql.connector

config = {
    'user': 'monitor_user@prod_tenant',
    'password': 'secure_password',
    'host': 'ob-cluster.cn-beijing.rds.aliyuncs.com',
    'database': 'oceanbase',
    'port': 3306
}

cnx = mysql.connector.connect(**config)
cursor = cnx.cursor(dictionary=True)

query = """
SELECT timestamp, message, error_code
FROM v$ob_cluster_event_history
WHERE facility = 'SWITCHOVER'
  AND timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY)
ORDER BY timestamp DESC
"""

cursor.execute(query)
for row in cursor:
    print(f"Switchover at {row['timestamp']}: {row['message']}")

cursor.close()
cnx.close()
```

## Response Format

```json
{
  "facility": "SWITCHOVER",
  "severity": "INFO",
  "error_code": 0,
  "timestamp": "2024-06-15T08:23:45.000Z",
  "message": "Switchover from primary to standby completed successfully."
}
```

**Key Fields**:
- `facility` — Identifies the subsystem that generated the event (e.g., SWITCHOVER, FAILOVER, SYNC)
- `severity` — Indicates the urgency: INFO, WARNING, ERROR, or CRITICAL
- `error_code` — Numeric code for programmatic error handling (0 typically means success)
- `timestamp` — ISO 8601 timestamp of when the event occurred
- `message` — Detailed human-readable explanation of the event

## Error Handling

This system view does not produce HTTP-style error codes. Errors occur at the SQL execution layer (e.g., permission denied, table not found). Common issues include:

- **Access denied**: Ensure the user has `SELECT` privilege on system views.
- **View not found**: Confirm you are connected to the correct tenant and database (`oceanbase`).
- **Syntax error**: Escape the `$` in `v$ob_cluster_event_history` as `v\$ob_cluster_event_history` in some clients.

### Rate Limits & Retry
No explicit rate limits apply to querying system views. However, excessive queries may impact cluster performance. Follow general database best practices:
- Cache results when possible.
- Avoid frequent polling; use event-driven architectures where feasible.
- Monitor query performance via OceanBase’s built-in diagnostics.

## Environment Requirements

- **Python**: Requires `pymysql` or `mysql-connector-python`  
  ```bash
  pip install pymysql
  ```
- **Java**: Requires MySQL JDBC driver (Connector/J 8.0+)  
  Add to classpath or Maven dependency.
- **CLI**: MySQL client installed (`mysql` command available)
- **Credentials**: Valid OceanBase tenant username and password with system view access

Set environment variables for security:
```bash
export OCEANBASE_USER="your_user@your_tenant"
export OCEANBASE_PASSWORD="your_password"
```

## FAQ

Q: Do I need special permissions to query v$ob_cluster_event_history?
A: Yes. You typically need DBA privileges or explicit `SELECT` grants on system views. Contact your database administrator if access is denied.

Q: Is this view available in both MySQL and Oracle modes?
A: The `v$ob_cluster_event_history` view is part of OceanBase’s internal system metadata and is accessible in both MySQL and Oracle tenant modes, though column names and data types may vary slightly.

Q: How far back does the event history go?
A: Retention depends on cluster configuration and log rotation policies. By default, events may be retained for several days to weeks. Check your cluster’s audit and diagnostic settings for exact retention.

Q: Can I use this API to trigger failover or switchover?
A: No. This view is read-only and provides historical records only. To perform failover or switchover, use OceanBase Cloud Platform (OCP) or administrative SQL commands, not this diagnostic view.

Q: Why am I seeing duplicate events?
A: Some operations generate multiple log entries (e.g., start, progress, completion). Filter by `facility` and `error_code` to isolate meaningful state changes.

## Pricing & Billing

### Billing Model
Free

### Free Tier
No usage charges for querying this view.

### Usage Limits
No specific quotas mentioned; subject to general cluster resource limits.

### Billing Notes
This view is part of the internal system metadata and does not incur additional costs.