### Install and Configure OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Commands to install the Oracle Cloud Infrastructure (OCI) Command Line Interface and configure user credentials. This involves downloading an installation script, running it, and then setting up authentication using `oci setup config`. ```bash bash -c "$(curl -L https://raw.githubusercontent.com/oracle/oci-cli/master/scripts/install/install.sh)" oci setup config oci iam region list ``` -------------------------------- ### Search Oracle Database Documentation Example (JSON) Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/mcp-tools.md An example of how to use the 'search_oracle_database_documentation' tool with a specific query and maximum results. ```json { "tool": "search_oracle_database_documentation", "arguments": { "query": "VECTOR_DISTANCE function syntax", "max_results": 5 } } ``` -------------------------------- ### Install Oracle DB Documentation MCP Server Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/mcp-tools.md Instructions for installing the Oracle DB Documentation MCP Server. This involves navigating to the server's directory within the cloned repository and running npm install and npm run build. ```bash cd oracle-mcp-servers/oracle-db-doc-mcp-server npm install npm run build ``` -------------------------------- ### Install Oracle Database MCP Server Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/mcp-tools.md Steps to install the Oracle Database MCP Server. This involves cloning the repository, navigating to the server directory, and running npm install and npm run build commands. ```bash # Clone and install git clone https://github.com/oracle-samples/oracle-mcp-servers.git cd oracle-mcp-servers/database-mcp-server npm install npm run build ``` -------------------------------- ### Install Oracle DBA Skill for Claude Code Source: https://github.com/acedergren/oracle-dba-skill/blob/main/README.md Instructions for installing the Oracle DBA Skill for Claude Code. This involves copying the skill directory to the Claude Code skills directory. ```bash # Copy to your Claude Code skills directory cp -r oracle-dba-skill ~/.claude/skills/ ``` -------------------------------- ### Install and Configure Oracle SQLcl MCP Server Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/mcp-tools.md Instructions for installing the SQLcl MCP server using npx, which requires SQLcl version 25.1 or later. It also shows how to configure the server within MCP settings by specifying the command and arguments. ```bash # Install via npx (requires SQLcl 25.1+) npx @anthropics/model-context-protocol run oracle-sqlcl ``` ```json { "mcpServers": { "oracle-sqlcl": { "command": "npx", "args": ["@anthropics/model-context-protocol", "run", "oracle-sqlcl"] } } } ``` -------------------------------- ### Start Autonomous Database with Error Handling Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Starts an Autonomous Database and captures any errors during the process. If an error occurs, it prints an error message and exits. This script uses `set -e` to exit immediately if a command exits with a non-zero status. ```bash #!/bin/bash set -e # Capture output and check status output=$(oci db autonomous-database start --autonomous-database-id $ADB_ID 2>&1) || { echo "Error starting ADB: $output" exit 1 } echo "ADB started successfully" ``` -------------------------------- ### Start, Stop, and Terminate Autonomous Databases with OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Commands to manage the lifecycle of an Autonomous Database. This includes stopping the database to save costs, starting it again, and permanently terminating it. Termination is an irreversible action. ```bash # Stop ADB (saves costs) oci db autonomous-database stop --autonomous-database-id $ADB_ID # Start ADB oci db autonomous-database start --autonomous-database-id $ADB_ID # Terminate ADB (irreversible!) oci db autonomous-database delete --autonomous-database-id $ADB_ID \ --force ``` -------------------------------- ### AI Vector Search Setup in SQL Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Details the SQL commands for setting up AI vector search capabilities, including creating tables with a VECTOR column and creating a vector index with specified parameters like distance metric and target accuracy. ```sql -- Create table with vector column CREATE TABLE documents ( id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY, content CLOB, embedding VECTOR(1024, FLOAT32) ); -- Create vector index CREATE VECTOR INDEX doc_embedding_idx ON documents(embedding) ORGANIZATION NEIGHBOR PARTITIONS DISTANCE COSINE WITH TARGET ACCURACY 95; ``` -------------------------------- ### SQL Query Hints for Optimization Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Explains the use of SQL query hints in Oracle to influence the optimizer's execution plan. Examples include forcing index usage, full table scans, parallel execution, and setting optimizer goals like FIRST_ROWS or ALL_ROWS. Hints should be used judiciously. ```sql -- Force index use SELECT /*+ INDEX(o idx_orders_date) */ * FROM orders o WHERE order_date > SYSDATE - 30; -- Force full table scan SELECT /*+ FULL(o) */ * FROM orders o WHERE status = 'PENDING'; -- Parallel execution SELECT /*+ PARALLEL(o, 4) */ COUNT(*) FROM orders o; -- Optimizer goal SELECT /*+ FIRST_ROWS(10) */ * FROM orders ORDER BY created_at DESC; SELECT /*+ ALL_ROWS */ * FROM orders WHERE region = :region; ``` -------------------------------- ### Common OCI CLI Commands for Autonomous Database Management Source: https://github.com/acedergren/oracle-dba-skill/blob/main/SKILL.md Provides essential Oracle Cloud Infrastructure Command Line Interface (OCI CLI) commands for managing Autonomous Databases, including listing, starting, stopping, scaling, and creating backups. ```bash # List Autonomous Databases oci db autonomous-database list --compartment-id $C # Start/Stop ADB oci db autonomous-database start --autonomous-database-id $ADB_ID oci db autonomous-database stop --autonomous-database-id $ADB_ID # Scale ECPU oci db autonomous-database update --autonomous-database-id $ADB_ID \ --compute-count 4 # Create manual backup oci db autonomous-database-backup create \ --autonomous-database-id $ADB_ID \ --display-name "pre-upgrade-backup" ``` -------------------------------- ### Example: Analyze Performance with Oracle Database MCP Server Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/mcp-tools.md A JSON payload demonstrating the use of the 'list_top_sql' tool from the Oracle Database MCP Server to identify top SQL statements. It specifies the metric 'elapsed_time', a limit of 10 results, and a time window of the last 1 hour. ```json { "tool": "list_top_sql", "arguments": { "metric": "elapsed_time", "limit": 10, "since_hours": 1 } } ``` -------------------------------- ### Date Operations in SQL Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Provides examples of common date and time operations in SQL, including retrieving current timestamps, performing date arithmetic, formatting dates, truncating dates, and defining date ranges. ```sql -- Current timestamp SELECT SYSTIMESTAMP FROM dual; SELECT CURRENT_TIMESTAMP FROM dual; -- Session timezone -- Date arithmetic SELECT order_date + 7 AS delivery_date FROM orders; -- Add 7 days SELECT order_date + INTERVAL '2' HOUR FROM orders; -- Add 2 hours -- Date formatting SELECT TO_CHAR(created_at, 'YYYY-MM-DD HH24:MI:SS') FROM events; SELECT TO_DATE('2024-01-15', 'YYYY-MM-DD') FROM dual; SELECT TO_TIMESTAMP('2024-01-15 10:30:00', 'YYYY-MM-DD HH24:MI:SS') FROM dual; -- Date truncation SELECT TRUNC(order_date) AS order_day FROM orders; -- Day SELECT TRUNC(order_date, 'MM') AS order_month FROM orders; -- Month SELECT TRUNC(order_date, 'Q') AS order_quarter FROM orders; -- Quarter -- Date ranges SELECT * FROM orders WHERE created_at BETWEEN :start_date AND :end_date; SELECT * FROM orders WHERE created_at >= TRUNC(SYSDATE) - 30; -- Last 30 days ``` -------------------------------- ### List Autonomous Databases with JMESPath Query Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Lists Autonomous Databases within a compartment and filters/formats the output using a JMESPath query. This example selects databases that are in the AVAILABLE lifecycle state and extracts their display name and ECPU count. ```bash oci db autonomous-database list --compartment-id $C \ --query 'data[?lifecycle-state==`AVAILABLE`].{name:"display-name",ecpu:"compute-count"}' ``` -------------------------------- ### Create Autonomous Databases with OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Provides examples for creating different types of Autonomous Databases, including Transaction Processing (OLTP), Data Warehouse (DW), with auto-scaling enabled, and Free Tier instances. Requires specifying compartment, database name, workload type, compute count, storage size, and admin password. ```bash # Create ATP (Transaction Processing) oci db autonomous-database create \ --compartment-id $C \ --db-name "MYATP" \ --display-name "My ATP Database" \ --db-workload OLTP \ --compute-count 2 \ --data-storage-size-in-tbs 1 \ --admin-password "ComplexPass123#" # Create ADW (Data Warehouse) oci db autonomous-database create \ --compartment-id $C \ --db-name "MYADW" \ --display-name "My ADW Database" \ --db-workload DW \ --compute-count 2 \ --data-storage-size-in-tbs 1 \ --admin-password "ComplexPass123#" # Create with auto-scaling enabled oci db autonomous-database create \ --compartment-id $C \ --db-name "AUTOSCALE" \ --display-name "Auto-Scaling DB" \ --db-workload OLTP \ --compute-count 2 \ --data-storage-size-in-tbs 1 \ --is-auto-scaling-enabled true \ --admin-password "ComplexPass123#" # Create Free Tier ADB oci db autonomous-database create \ --compartment-id $C \ --db-name "FREEADB" \ --display-name "Free Tier ADB" \ --db-workload OLTP \ --is-free-tier true \ --admin-password "ComplexPass123#" ``` -------------------------------- ### Create Application User and Grant Privileges (SQL) Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/adb-security.md Demonstrates the creation of a standard application user with specific privileges and the setup of a view for controlled data access. It emphasizes granting minimal necessary permissions and using views instead of direct table access. ```sql -- Standard application user CREATE USER app_user IDENTIFIED BY :password DEFAULT TABLESPACE data TEMPORARY TABLESPACE temp QUOTA UNLIMITED ON data; -- Grant minimal privileges GRANT CREATE SESSION TO app_user; GRANT SELECT, INSERT, UPDATE ON app_schema.orders TO app_user; GRANT EXECUTE ON app_schema.process_order TO app_user; -- No direct table access - use views CREATE VIEW app_user.orders_v AS SELECT order_id, customer_id, order_date, status FROM app_schema.orders WHERE customer_id = SYS_CONTEXT('APP_CTX', 'CUSTOMER_ID'); GRANT SELECT ON app_user.orders_v TO app_user; ``` -------------------------------- ### Get Autonomous Database Details (Raw Output) Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Retrieves detailed information about a specific Autonomous Database without any formatting. This command requires the Autonomous Database OCID and the `--raw-output` flag. ```bash oci db autonomous-database get --autonomous-database-id $ADB_ID --raw-output ``` -------------------------------- ### SQL: Oracle Bind Variables and Result Limiting Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt Demonstrates the use of bind variables for secure and performant queries, and the `FETCH FIRST` clause for limiting result sets in Oracle SQL. Includes examples for pagination with `OFFSET`. ```sql -- Always use bind variables (security + performance) SELECT * FROM users WHERE id = :user_id; SELECT * FROM orders WHERE created_at > :start_date; UPDATE inventory SET quantity = :qty WHERE product_id = :pid; -- Use FETCH FIRST (not LIMIT) SELECT * FROM orders ORDER BY created_at DESC FETCH FIRST 10 ROWS ONLY; -- With offset (pagination) SELECT * FROM orders ORDER BY created_at DESC OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY; ``` -------------------------------- ### Oracle SQL Best Practices Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt Guidelines and examples for writing efficient and secure SQL queries in Oracle, focusing on bind variables, pagination, null handling, and date operations. ```APIDOC ## SQL Best Practices and Oracle-Specific Syntax ### Description This section outlines recommended practices for writing SQL queries in Oracle databases, emphasizing security, performance, and the use of Oracle-specific functions and syntax. ### Method N/A (SQL Statements) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### SQL Examples #### Use Bind Variables Bind variables are crucial for preventing SQL injection vulnerabilities and improving query performance through plan reuse. ```sql -- Security + Performance SELECT * FROM users WHERE id = :user_id; SELECT * FROM orders WHERE created_at > :start_date; UPDATE inventory SET quantity = :qty WHERE product_id = :pid; ``` #### Limit Results with FETCH FIRST Oracle uses `FETCH FIRST` for limiting rows, not `LIMIT`. ```sql -- Fetch first 10 rows SELECT * FROM orders ORDER BY created_at DESC FETCH FIRST 10 ROWS ONLY; -- With offset for pagination SELECT * FROM orders ORDER BY created_at DESC OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY; ``` #### Handle NULL Values with NVL/COALESCE Use `NVL` or `COALESCE` to provide default values for NULL columns. ```sql SELECT NVL(nickname, first_name) AS display_name FROM users; SELECT COALESCE(phone_mobile, phone_home, phone_work) AS contact FROM users; ``` #### Generate UUIDs with SYS_GUID() Use `SYS_GUID()` to generate universally unique identifiers. ```sql INSERT INTO orders (id, customer_id) VALUES (SYS_GUID(), :customer_id); ``` #### String Concatenation with || Oracle uses the `||` operator for string concatenation. ```sql SELECT first_name || ' ' || last_name AS full_name FROM users; ``` #### Date and Time Operations Oracle provides various functions for date and time manipulation. ```sql -- Get current timestamp SELECT SYSTIMESTAMP FROM dual; -- Add days to a date SELECT order_date + 7 AS delivery_date FROM orders; -- Add 7 days -- Add interval SELECT order_date + INTERVAL '2' HOUR FROM orders; -- Add 2 hours -- Format date to string SELECT TO_CHAR(created_at, 'YYYY-MM-DD HH24:MI:SS') FROM events; -- Truncate date to the beginning of the day SELECT TRUNC(order_date) AS order_day FROM orders; -- Select records from the last 30 days SELECT * FROM orders WHERE created_at >= TRUNC(SYSDATE) - 30; ``` ``` -------------------------------- ### Example: Execute SQL Query using Oracle SQLcl MCP Server Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/mcp-tools.md A JSON payload demonstrating how to use the 'run-sql' tool provided by the Oracle SQLcl MCP server to execute a SQL query. The query retrieves table names and row counts, ordered by row count in descending order, and limits the results to the top 5. ```json { "tool": "run-sql", "arguments": { "sql": "SELECT table_name, num_rows FROM user_tables ORDER BY num_rows DESC FETCH FIRST 5 ROWS ONLY" } } ``` -------------------------------- ### Get Autonomous Database Details (JSON Output) Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Retrieves detailed information about a specific Autonomous Database in JSON format, which is the default output. This command requires the Autonomous Database OCID. ```bash oci db autonomous-database get --autonomous-database-id $ADB_ID ``` -------------------------------- ### Get CPU Utilization Metric for Autonomous Database Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Retrieves the average CPU utilization metric for an Autonomous Database over a specified period. This command requires the compartment OCID, the ADB OCID, and uses a specific query text for the OCI monitoring service. ```bash oci monitoring metric-data summarize-metrics-data \ --compartment-id $C \ --namespace oci_autonomous_database \ --query-text 'CpuUtilization[1h]{resourceId="'$ADB_ID'"}.mean()' ``` -------------------------------- ### Get Storage Utilization Metric for Autonomous Database Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Retrieves the maximum storage utilization metric for an Autonomous Database over a specified period. This command requires the compartment OCID, the ADB OCID, and uses a specific query text for the OCI monitoring service. ```bash oci monitoring metric-data summarize-metrics-data \ --compartment-id $C \ --namespace oci_autonomous_database \ --query-text 'StorageUtilization[1d]{resourceId="'$ADB_ID'"}.max()' ``` -------------------------------- ### Get Work Request Logs Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Lists the logs associated with a specific work request. This command requires the work request OCID. ```bash oci work-requests work-request-log list \ --work-request-id $WORK_REQUEST_ID ``` -------------------------------- ### Get Session Count Metric for Autonomous Database Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Retrieves the average number of active sessions for an Autonomous Database over a specified period. This command requires the compartment OCID, the ADB OCID, and uses a specific query text for the OCI monitoring service. ```bash oci monitoring metric-data summarize-metrics-data \ --compartment-id $C \ --namespace oci_autonomous_database \ --query-text 'Sessions[1h]{resourceId="'$ADB_ID'"}.mean()' ``` -------------------------------- ### Configure and Use Select AI for Natural Language to SQL Queries Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt This snippet demonstrates how to configure an AI profile using OCI GenAI for natural language to SQL translation, set the profile for a session, and execute natural language queries. It includes examples for direct translation, conversational chat mode, and data narration. ```sql BEGIN DBMS_CLOUD_AI.CREATE_PROFILE( profile_name => 'OCI_GENAI', attributes => '{"provider":"oci", "model":"cohere.command-r-plus", "oci_compartment_id":"ocid1.compartment...", "object_list":[{"owner":"SALES","name":"ORDERS"}, {"owner":"SALES","name":"CUSTOMERS"}]}' ); END; / -- Set profile for session EXEC DBMS_CLOUD_AI.SET_PROFILE('OCI_GENAI'); -- Natural language to SQL SELECT AI('Show me total sales by region for last month'); -- Chat mode for conversational queries SELECT AI CHAT('What were our top 5 products by revenue?'); -- Narrate data in natural language SELECT AI NARRATE('Explain this sales data') FROM sales_summary; ``` -------------------------------- ### Manage Oracle Autonomous Databases with OCI CLI Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt Provides OCI CLI commands for the complete lifecycle management of Oracle Autonomous Databases. This includes creating, listing, retrieving details, starting, stopping, scaling compute and storage, and enabling auto-scaling. Requires compartment and ADB IDs. ```bash # Environment setup export C="ocid1.compartment.oc1..your_compartment_id" export ADB_ID="ocid1.autonomousdatabase.oc1..your_db_id" # List all Autonomous Databases in compartment oci db autonomous-database list --compartment-id $C # Get specific ADB details oci db autonomous-database get --autonomous-database-id $ADB_ID # Query output with jq filtering oci db autonomous-database list --compartment-id $C \ --query 'data[*].{name:"display-name",state:"lifecycle-state",ecpu:"compute-count"}' # Create ATP (Transaction Processing) database oci db autonomous-database create \ --compartment-id $C \ --db-name "MYATP" \ --display-name "My ATP Database" \ --db-workload OLTP \ --compute-count 2 \ --data-storage-size-in-tbs 1 \ --admin-password "ComplexPass123#" # Create ADW (Data Warehouse) database oci db autonomous-database create \ --compartment-id $C \ --db-name "MYADW" \ --display-name "My ADW Database" \ --db-workload DW \ --compute-count 2 \ --data-storage-size-in-tbs 1 \ --admin-password "ComplexPass123#" # Create Free Tier ADB oci db autonomous-database create \ --compartment-id $C \ --db-name "FREEADB" \ --display-name "Free Tier ADB" \ --db-workload OLTP \ --is-free-tier true \ --admin-password "ComplexPass123#" # Start/Stop ADB oci db autonomous-database start --autonomous-database-id $ADB_ID oci db autonomous-database stop --autonomous-database-id $ADB_ID # Scale ECPU (compute) oci db autonomous-database update --autonomous-database-id $ADB_ID \ --compute-count 4 # Scale storage oci db autonomous-database update --autonomous-database-id $ADB_ID \ --data-storage-size-in-tbs 2 # Enable auto-scaling oci db autonomous-database update --autonomous-database-id $ADB_ID \ --is-auto-scaling-enabled true ``` -------------------------------- ### Oracle PL/SQL Autonomous Transaction for Logging Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Illustrates the use of autonomous transactions in Oracle PL/SQL to create a logging procedure that commits independently of the main transaction. This ensures log entries are preserved even if the main transaction is rolled back. The example shows logging at the start and end of an order process. ```sql -- Logging procedure that commits independently CREATE OR REPLACE PROCEDURE log_event( p_event_type IN VARCHAR2, p_message IN VARCHAR2 ) IS PRAGMA AUTONOMOUS_TRANSACTION; BEGIN INSERT INTO event_log (event_type, message, created_at) VALUES (p_event_type, p_message, SYSTIMESTAMP); COMMIT; END; / -- Usage: Log persists even if main transaction rolls back BEGIN log_event('ORDER_START', 'Processing order ' || :order_id); -- Process order... -- If this fails and rolls back, log entry is preserved log_event('ORDER_COMPLETE', 'Order ' || :order_id || ' processed'); EXCEPTION WHEN OTHERS THEN log_event('ORDER_ERROR', SQLERRM); RAISE; END; / ``` -------------------------------- ### List and Query Autonomous Databases with OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Demonstrates how to list Autonomous Databases (ADBs) within a specified compartment and retrieve details for a specific ADB. It also shows how to filter by workload type and query specific fields using JMESPath syntax. ```bash # List all ADBs in compartment oci db autonomous-database list --compartment-id $C # List with specific workload type oci db autonomous-database list --compartment-id $C \ --db-workload DW # Get specific ADB details oci db autonomous-database get --autonomous-database-id $ADB_ID # Query output with jq oci db autonomous-database list --compartment-id $C \ --query 'data[*].{name:"display-name",state:"lifecycle-state",ecpu:"compute-count"}' ``` -------------------------------- ### Connect to ADB via SQLcl Source: https://github.com/acedergren/oracle-dba-skill/blob/main/SKILL.md Demonstrates how to connect to an Oracle Autonomous Database using SQLcl, with options for using a wallet or Cloud Shell configuration. ```bash # Using wallet sql admin@charlstn_high?TNS_ADMIN=/path/to/wallet # Using Cloud Shell (no wallet needed) sql -cloudconfig wallet.zip admin@adb_name_high ``` -------------------------------- ### Oracle SQL: Pivot and Unpivot Data Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Illustrates data transformation using Oracle SQL's PIVOT and UNPIVOT operators. The PIVOT example transforms rows into columns (e.g., quarters into columns for sales), while the UNPIVOT example converts columns back into rows. ```sql -- Pivot: Rows to columns SELECT * FROM ( SELECT region, quarter, sales FROM quarterly_sales ) PIVOT ( SUM(sales) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4') ); -- Unpivot: Columns to rows SELECT region, quarter, sales FROM quarterly_wide UNPIVOT (sales FOR quarter IN (q1, q2, q3, q4)); ``` -------------------------------- ### Get Work Request Status Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Retrieves the status of a specific work request. This command requires the work request OCID. ```bash oci work-requests work-request get \ --work-request-id $WORK_REQUEST_ID ``` -------------------------------- ### AI Vector Similarity Search in SQL Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Illustrates how to perform vector similarity searches using SQL. It covers basic similarity searches, searches with a distance threshold, and hybrid searches combining vector similarity with keyword matching. ```sql -- Basic similarity search SELECT id, content, VECTOR_DISTANCE(embedding, :query_embedding, COSINE) AS score FROM documents ORDER BY score FETCH FIRST 10 ROWS ONLY; -- With threshold SELECT id, content, VECTOR_DISTANCE(embedding, :query_embedding, COSINE) AS score FROM documents WHERE VECTOR_DISTANCE(embedding, :query_embedding, COSINE) < 0.5 ORDER BY score FETCH FIRST 10 ROWS ONLY; -- Hybrid search (vector + keyword) SELECT id, content, (0.6 * vector_score + 0.4 * text_score) AS combined_score FROM ( SELECT id, content, VECTOR_DISTANCE(embedding, :query_embedding, COSINE) AS vector_score, CASE WHEN CONTAINS(content, :keywords, 1) > 0 THEN SCORE(1) ELSE 0 END AS text_score FROM documents WHERE CONTAINS(content, :keywords, 1) > 0 OR VECTOR_DISTANCE(embedding, :query_embedding, COSINE) < 0.7 ) ORDER BY combined_score FETCH FIRST 10 ROWS ONLY; ``` -------------------------------- ### MCP Server: Get Table DDL Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt Instructs the MCP Server to retrieve the Data Definition Language (DDL) for a specific table. This requires both the schema name and the table name as arguments. ```json { "tool": "get_table_ddl", "arguments": { "schema": "HR", "table_name": "EMPLOYEES" } } ``` -------------------------------- ### Scale Autonomous Database Resources with OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Instructions for scaling the compute (ECPU) and storage resources of an Autonomous Database. It also covers enabling and disabling auto-scaling, and performing combined scaling operations. ```bash # Scale ECPU (compute) oci db autonomous-database update --autonomous-database-id $ADB_ID \ --compute-count 4 # Scale storage oci db autonomous-database update --autonomous-database-id $ADB_ID \ --data-storage-size-in-tbs 2 # Enable auto-scaling oci db autonomous-database update --autonomous-database-id $ADB_ID \ --is-auto-scaling-enabled true # Disable auto-scaling oci db autonomous-database update --autonomous-database-id $ADB_ID \ --is-auto-scaling-enabled false # Scale compute and storage together oci db autonomous-database update --autonomous-database-id $ADB_ID \ --compute-count 8 \ --data-storage-size-in-tbs 4 ``` -------------------------------- ### Oracle DB Documentation MCP Server Tool Source: https://github.com/acedergren/oracle-dba-skill/blob/main/SKILL.md Introduces the Oracle DB Documentation MCP Server tool, designed to search official Oracle documentation directly from AI conversations. ```bash search_oracle_database_documentation | Search Oracle docs by phrase ``` -------------------------------- ### MCP Server: Run Query with Explain Plan Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt This configuration enables the MCP Server to execute a given SQL query and provide its execution plan. It takes the SQL statement as an argument, allowing for query optimization analysis. ```json { "tool": "explain_plan", "arguments": { "sql": "SELECT * FROM orders WHERE customer_id = :cid" } } ``` -------------------------------- ### Update Maintenance Window for Autonomous Database Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Updates the maintenance window for an Autonomous Database, specifying the day of the week and the start and stop times. This requires the Autonomous Database OCID and a JSON payload defining the scheduled operations. ```bash oci db autonomous-database update \ --autonomous-database-id $ADB_ID \ --scheduled-operations '[{"day-of-week":"SUNDAY","scheduled-start-time":"02:00","scheduled-stop-time":"06:00"}]' ``` -------------------------------- ### SQL Best Practices for Oracle Autonomous Database Source: https://github.com/acedergren/oracle-dba-skill/blob/main/SKILL.md Highlights key SQL best practices for Oracle Autonomous Databases, including the use of bind variables, `FETCH FIRST` clause, and vector similarity search syntax for version 26ai. ```sql -- Always use bind variables SELECT * FROM users WHERE id = :user_id; -- Use FETCH FIRST (not LIMIT) SELECT * FROM orders ORDER BY created_at DESC FETCH FIRST 10 ROWS ONLY; -- Vector similarity search (26ai) SELECT id, content, VECTOR_DISTANCE(embedding, :query_vec, COSINE) AS score FROM documents ORDER BY score FETCH FIRST 5 ROWS ONLY; ``` -------------------------------- ### Configure Oracle SQL Firewall Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/adb-security.md Illustrates how to configure Oracle SQL Firewall to protect against SQL injection and unauthorized SQL statements. This involves enabling the firewall, starting capture mode to generate an allow list, and then enabling enforcement based on the captured rules. ```sql -- Enable SQL Firewall BEGIN DBMS_SQL_FIREWALL.ENABLE; END; / -- Start capture mode for user BEGIN DBMS_SQL_FIREWALL.CREATE_CAPTURE( username => 'APP_USER', top_level_only => TRUE, start_capture => TRUE ); END; / -- Stop capture and generate allow list BEGIN DBMS_SQL_FIREWALL.STOP_CAPTURE(username => 'APP_USER'); DBMS_SQL_FIREWALL.GENERATE_ALLOW_LIST(username => 'APP_USER'); END; / -- Enable enforcement BEGIN DBMS_SQL_FIREWALL.ENABLE_ALLOW_LIST( username => 'APP_USER', enforce => DBMS_SQL_FIREWALL.ENFORCE_ALL, block => TRUE ); END; / ``` -------------------------------- ### Manage Autonomous Database Wallets with OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Commands for managing the security wallet for an Autonomous Database. This includes downloading a regional wallet, downloading an instance-specific wallet, and rotating the wallet credentials. ```bash # Download wallet (regional) oci db autonomous-database generate-wallet \ --autonomous-database-id $ADB_ID \ --password "WalletPass123#" \ --file wallet.zip # Download instance wallet oci db autonomous-database generate-wallet \ --autonomous-database-id $ADB_ID \ --password "WalletPass123#" \ --generate-type SINGLE \ --file wallet_instance.zip # Rotate wallet oci db autonomous-database rotate-wallet \ --autonomous-database-id $ADB_ID ``` -------------------------------- ### Create Autonomous Database and Wait for Availability Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Creates a new Autonomous Database and automatically waits until it reaches the AVAILABLE state before exiting. This command requires compartment OCID, database name, display name, workload type, compute count, storage size, and admin password. ```bash oci db autonomous-database create \ --compartment-id $C \ --db-name "WAITDB" \ --display-name "Wait DB" \ --db-workload OLTP \ --compute-count 2 \ --data-storage-size-in-tbs 1 \ --admin-password "ComplexPass123#" \ --wait-for-state AVAILABLE ``` -------------------------------- ### Manage Autonomous Database Backups with OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Operations for managing backups of an Autonomous Database. This includes listing existing backups, creating manual backups (standard and long-term retention), retrieving backup details, and deleting backups. ```bash # List backups oci db autonomous-database-backup list \ --autonomous-database-id $ADB_ID # Create manual backup oci db autonomous-database-backup create \ --autonomous-database-id $ADB_ID \ --display-name "pre-upgrade-backup" # Create long-term backup (retained beyond automatic policy) oci db autonomous-database-backup create \ --autonomous-database-id $ADB_ID \ --display-name "quarterly-backup" \ --retention-period-in-days 365 # Get backup details oci db autonomous-database-backup get \ --autonomous-database-backup-id $BACKUP_ID # Delete backup oci db autonomous-database-backup delete \ --autonomous-database-backup-id $BACKUP_ID ``` -------------------------------- ### Oracle Execution Plan Analysis Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Demonstrates how to analyze SQL query performance using Oracle's execution plan features. This includes generating explain plans, displaying detailed plans, and retrieving plans from the cursor cache or AWR history. Understanding execution plans is key to identifying performance bottlenecks. ```sql -- Explain plan EXPLAIN PLAN FOR SELECT * FROM orders WHERE customer_id = :cid; SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY); -- With statistics SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY(NULL, NULL, 'ALL')); -- From cursor cache SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(:sql_id, NULL, 'ALL')); -- AWR historical SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_AWR(:sql_id)); ``` -------------------------------- ### SQL: Oracle String Concatenation and Date Operations Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt Shows Oracle SQL syntax for string concatenation using the `||` operator and various functions for date manipulation, including getting the current timestamp, adding intervals, formatting dates, truncating dates, and filtering by date ranges. ```sql -- String concatenation with || SELECT first_name || ' ' || last_name AS full_name FROM users; -- Date operations SELECT SYSTIMESTAMP FROM dual; SELECT order_date + 7 AS delivery_date FROM orders; -- Add 7 days SELECT order_date + INTERVAL '2' HOUR FROM orders; -- Add 2 hours SELECT TO_CHAR(created_at, 'YYYY-MM-DD HH24:MI:SS') FROM events; SELECT TRUNC(order_date) AS order_day FROM orders; SELECT * FROM orders WHERE created_at >= TRUNC(SYSDATE) - 30; -- Last 30 days ``` -------------------------------- ### Oracle SQL JSON Operations and Duality Views Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt Demonstrates Oracle's native JSON support, including creating tables with JSON columns, inserting, querying, and manipulating JSON data. Includes examples of JSON_VALUE, JSON_QUERY, JSON_EXISTS, JSON_TABLE, JSON_TRANSFORM, and JSON Duality Views (23ai+). ```sql -- JSON column definition CREATE TABLE documents ( id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY, data CLOB CHECK (data IS JSON) ); -- Insert JSON INSERT INTO documents (data) VALUES ('{"name": "John", "age": 30}'); -- Query JSON values SELECT JSON_VALUE(data, '$.name') AS name FROM documents; SELECT JSON_VALUE(data, '$.age' RETURNING NUMBER) AS age FROM documents; -- JSON query (returns JSON) SELECT JSON_QUERY(data, '$.address') FROM documents; -- JSON exists check SELECT * FROM documents WHERE JSON_EXISTS(data, '$.premium'); -- JSON table (unnest arrays) SELECT d.id, jt.item_name, jt.quantity FROM documents d, JSON_TABLE(d.data, '$.items[*]' COLUMNS ( item_name VARCHAR2(100) PATH '$.name', quantity NUMBER PATH '$.qty' ) ) jt; -- Update JSON UPDATE documents SET data = JSON_TRANSFORM(data, SET '$.status' = 'active') WHERE id = :id; -- JSON Duality Views (23ai+) CREATE JSON RELATIONAL DUALITY VIEW orders_dv AS SELECT JSON { '_id': o.order_id, 'customer': c.customer_name, 'items': [ SELECT JSON {'product': p.name, 'qty': oi.quantity} FROM order_items oi, products p WHERE oi.order_id = o.order_id AND oi.product_id = p.product_id ] } FROM orders o, customers c WHERE o.customer_id = c.customer_id; ``` -------------------------------- ### Clone Autonomous Database with OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/oci-cli.md Command to create a clone of an existing Autonomous Database. This allows for creating copies for development, testing, or other purposes. Supports full clones. ```bash # Create full clone oci db autonomous-database create-clone \ --source-autonomous-database-id $ADB_ID \ --compartment-id $C \ --clone-type FULL \ --db-name "CLONE01" \ --display-name "Dev Clone" ``` -------------------------------- ### Efficient Joins in SQL Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Illustrates best practices for writing efficient JOIN clauses in SQL queries. It emphasizes using explicit JOIN syntax over older implicit methods and preferring EXISTS over IN for subqueries to improve performance. These techniques are standard SQL and applicable across most relational databases. ```sql -- Use explicit JOIN syntax SELECT o.order_id, c.customer_name, p.product_name FROM orders o INNER JOIN customers c ON o.customer_id = c.customer_id INNER JOIN order_items oi ON o.order_id = oi.order_id INNER JOIN products p ON oi.product_id = p.product_id WHERE o.order_date >= TRUNC(SYSDATE) - 30; -- Use EXISTS instead of IN for subqueries SELECT * FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.order_date >= TRUNC(SYSDATE) - 30 ); ``` -------------------------------- ### Query Oracle Unified Audit Trail Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/adb-security.md Provides SQL queries to retrieve information from the Oracle Unified Audit Trail. Examples include fetching recent audit events, identifying failed login attempts, and reviewing privileged user activity. These queries help in security monitoring and incident investigation. ```sql -- Recent audit events SELECT event_timestamp, dbusername, action_name, object_schema, object_name, return_code, client_program_name FROM unified_audit_trail WHERE event_timestamp > SYSDATE - 1 ORDER BY event_timestamp DESC FETCH FIRST 100 ROWS ONLY; -- Failed login attempts SELECT event_timestamp, dbusername, os_username, userhost, authentication_type, return_code FROM unified_audit_trail WHERE action_name = 'LOGON' AND return_code != 0 ORDER BY event_timestamp DESC; -- Privileged user activity SELECT event_timestamp, dbusername, action_name, sql_text FROM unified_audit_trail WHERE dbusername IN ('ADMIN', 'SYS') ORDER BY event_timestamp DESC; ``` -------------------------------- ### Connect and Manage Oracle Databases with SQLcl MCP Server Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt This snippet shows how to install and configure the SQLcl MCP Server for AI agents to interact with Oracle databases. It includes commands for listing connections, establishing connections, executing SQL statements, and retrieving schema information. Requires SQLcl 25.1 or later. ```bash # Installation via npx npx @anthropics/model-context-protocol run oracle-sqlcl # MCP configuration in claude settings { "mcpServers": { "oracle-sqlcl": { "command": "npx", "args": ["@anthropics/model-context-protocol", "run", "oracle-sqlcl"] } } } # Connect to ADB via SQLcl directly sql admin@charlstn_high?TNS_ADMIN=/path/to/wallet # Using Cloud Shell (no wallet needed) sql -cloudconfig wallet.zip admin@adb_name_high ``` -------------------------------- ### Define and Assign Least Privilege Roles (SQL) Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/adb-security.md Illustrates the creation of roles with specific privilege sets, such as read-only access or developer permissions. It then shows how to grant these roles to different database users. ```sql -- Read-only role CREATE ROLE read_only_role; GRANT SELECT ANY TABLE TO read_only_role; GRANT SELECT ON dba_tables TO read_only_role; -- Developer role CREATE ROLE developer_role; GRANT CREATE SESSION, CREATE TABLE, CREATE VIEW, CREATE PROCEDURE, CREATE SEQUENCE TO developer_role; -- Assign roles GRANT read_only_role TO report_user; GRANT developer_role TO dev_user; ``` -------------------------------- ### Oracle SQL: Top N Rows Within Groups Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/sql-patterns.md Provides an Oracle SQL query to find the top N records within each group. This example specifically shows how to retrieve the top 3 orders per customer based on the total amount, using the ROW_NUMBER() window function for ranking. ```sql -- Top 3 orders per customer SELECT customer_id, order_id, total_amount, rn FROM ( SELECT customer_id, order_id, total_amount, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY total_amount DESC) AS rn FROM orders ) WHERE rn <= 3; ``` -------------------------------- ### Create and Manage Manual Backups via OCI CLI Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/adb-ha-dr.md Commands to create manual backups, including long-term retention, and list existing backups for an Oracle Autonomous Database using the OCI CLI. These operations are crucial for custom backup strategies and compliance. ```bash # Create manual backup oci db autonomous-database-backup create \ --autonomous-database-id $ADB_ID \ --display-name "Pre-Upgrade-Backup-$(date +%Y%m%d)" # Long-term backup (1 year) oci db autonomous-database-backup create \ --autonomous-database-id $ADB_ID \ --display-name "Annual-Backup-2024" \ --retention-period-in-days 365 # List backups oci db autonomous-database-backup list \ --autonomous-database-id $ADB_ID \ --query 'data[*].{name:"display-name",state:"lifecycle-state",type:"type",time:"time-ended"}' ``` -------------------------------- ### Oracle SQL AI Vector Search Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt SQL examples for Oracle AI Vector Search (23ai/26ai), enabling semantic similarity queries. Covers creating tables with vector columns, creating vector indexes with different distance metrics, performing basic and threshold-based similarity searches, and hybrid search combining vector and keyword matching. ```sql -- Create table with vector column CREATE TABLE documents ( id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY, content CLOB, embedding VECTOR(1024, FLOAT32) ); -- Create vector index CREATE VECTOR INDEX doc_embedding_idx ON documents(embedding) ORGANIZATION NEIGHBOR PARTITIONS DISTANCE COSINE WITH TARGET ACCURACY 95; -- Basic similarity search SELECT id, content, VECTOR_DISTANCE(embedding, :query_embedding, COSINE) AS score FROM documents ORDER BY score FETCH FIRST 10 ROWS ONLY; -- With similarity threshold SELECT id, content, VECTOR_DISTANCE(embedding, :query_embedding, COSINE) AS score FROM documents WHERE VECTOR_DISTANCE(embedding, :query_embedding, COSINE) < 0.5 ORDER BY score FETCH FIRST 10 ROWS ONLY; -- Hybrid search (vector + keyword) SELECT id, content, (0.6 * vector_score + 0.4 * text_score) AS combined_score FROM ( SELECT id, content, VECTOR_DISTANCE(embedding, :query_embedding, COSINE) AS vector_score, CASE WHEN CONTAINS(content, :keywords, 1) > 0 THEN SCORE(1) ELSE 0 END AS text_score FROM documents WHERE CONTAINS(content, :keywords, 1) > 0 OR VECTOR_DISTANCE(embedding, :query_embedding, COSINE) < 0.7 ) ORDER BY combined_score FETCH FIRST 10 ROWS ONLY; -- Generate embeddings with DBMS_VECTOR DECLARE v_embedding VECTOR; BEGIN v_embedding := DBMS_VECTOR.UTL_TO_EMBEDDING( 'This is the text to embed', JSON('{"provider":"oci", "model":"cohere.embed-english-v3.0"}') ); END; / ``` -------------------------------- ### OCI Database Tools MCP Server Connection Management (Bash) Source: https://github.com/acedergren/oracle-dba-skill/blob/main/references/mcp-tools.md Bash commands to test connectivity and check TNS resolution for OCI Database Tools MCP Server connections. ```bash # Test connectivity sql -L admin@adb_high # Check TNS resolution tnsping adb_high ``` -------------------------------- ### OCI CLI - Wallet and Backup Management Source: https://context7.com/acedergren/oracle-dba-skill/llms.txt Manage ADB wallets for secure connections and utilize backup management features for point-in-time recovery and long-term retention. ```APIDOC ## OCI CLI - Wallet and Backup Management ### Description This section covers managing Oracle Autonomous Database (ADB) wallets for secure client connections and details the backup management capabilities, including automatic backups and point-in-time recovery options. ### Method OCI CLI Command ### Endpoint N/A (OCI CLI Interface) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Command Examples **Wallet Management (Downloading Wallet):** ```bash # Replace $ADB_ID with your Autonomous Database OCID oci db autonomous-database generate-wallet --autonomous-database-id $ADB_ID --file "adb_wallet.zip" ``` **Backup Management (Listing Backups):** ```bash # Replace $ADB_ID with your Autonomous Database OCID oci db autonomous-database backup list --autonomous-database-id $ADB_ID ``` **Backup Management (Getting Backup Details):** ```bash # Replace $ADB_ID and $BACKUP_ID with your Autonomous Database OCID and Backup OCID oci db autonomous-database backup get --autonomous-database-id $ADB_ID --autonomous-database-backup-id $BACKUP_ID ``` **Backup Management (Restoring from Backup):** ```bash # This operation creates a new ADB instance from a backup # Replace $ADB_ID, $BACKUP_ID, and $C with your Autonomous Database OCID, Backup OCID, and Compartment OCID respectively oci db autonomous-database restore --autonomous-database-id $ADB_ID --autonomous-database-backup-id $BACKUP_ID --compartment-id $C --db-name "RESTORED_ADB" ``` ### Response #### Success Response (200) - The OCI CLI command output will indicate the success or failure of the operation, often returning JSON or text describing the resource state or backup information. #### Response Example ```json // Example for 'backup list' command { "data": [ { "compartment-id": "ocid1.compartment.oc1..your_compartment_id", "autonomous-database-id": "ocid1.autonomousdatabase.oc1..your_db_id", "display-name": "Daily Backup 2023-10-27T03:00:00Z", "lifecycle-state": "SUCCEEDED", "backup-type": "INCREMENTAL", "time-started": "2023-10-27T03:00:00Z", "time-ended": "2023-10-27T03:15:00Z" // ... other backup details } // ... more backups ] } ``` ```