### Install hstore extension Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/24.txt Basic installation of the hstore extension. ```sql CREATE EXTENSION hstore ``` -------------------------------- ### Quick Setup for Druid Monitoring Source: https://github.com/alibaba/druid/blob/master/doc/monitoring-guide.md A consolidated quick setup configuration for enabling Druid's monitoring features, including StatFilter, the web monitoring servlet, and the web stat filter. ```yaml spring: datasource: druid: filter: stat: enabled: true log-slow-sql: true slow-sql-millis: 2000 stat-view-servlet: enabled: true login-username: admin login-password: your_password web-stat-filter: enabled: true url-pattern: /* exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" ``` -------------------------------- ### Create Table Definitions Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/teradata/0.txt Examples of creating volatile and standard tables. ```sql CREATE VOLATILE MULTISET TABLE TMP_MEMBER_INFO2 ( MBR_CARD_NBR VARCHAR(50), MBR_CARD_NBR_OLD VARCHAR(50), CUST_NBR CHAR(50) , NM VARCHAR(50) , ID_CARD VARCHAR(20) , ID_CARD_FLAG VARCHAR(20) , SEX_CD VARCHAR(20) , HMTON_CD VARCHAR(20) , BIRTH_DT_OLD DATE FORMAT 'YYYY-MM-DD' , BIRTH_DT DATE FORMAT 'YYYY-MM-DD' , REG_TM TIMESTAMP(0) , CONTACT_TEL VARCHAR(20) , HOME_ADDR VARCHAR(100) , AFFL_SITE_ID VARCHAR(100) , AFFL_BUSI_DIST_CD VARCHAR(20) , BUSI_DIST_DISTANCE_CD VARCHAR(20) , COMBINE_TYPE VARCHAR(20), COMBINE_SEQ INTEGER , ONLINE_REG_FLAG VARCHAR(2) , ACTIVE_FLAG VARCHAR(2), BIZ_SPACE_ID VARCHAR(40), BIZ_SPACE_NAME VARCHAR(64), BIZ_SPACE_CODE VARCHAR(40), DATA_UPD_TM TIMESTAMP(0), COMBINE_SEQ2 INTEGER, REG_CHANNEL_CODE VARCHAR(32), REG_CHANNEL_NAME VARCHAR(64) ) PRIMARY INDEX ( MBR_CARD_NBR , MBR_CARD_NBR_OLD , BIZ_SPACE_CODE , CUST_NBR , BIZ_SPACE_ID ) ON COMMIT PRESERVE ROWS ``` ```sql CREATE TABLE TMP_MEMBER_INFO2 ( MBR_CARD_NBR VARCHAR(50), MBR_CARD_NBR_OLD VARCHAR(50), CUST_NBR CHAR(50), NM VARCHAR(50), ID_CARD VARCHAR(20), ID_CARD_FLAG VARCHAR(20), SEX_CD VARCHAR(20), HMTON_CD VARCHAR(20), BIRTH_DT_OLD DATE FORMAT 'YYYY-MM-DD', BIRTH_DT DATE FORMAT 'YYYY-MM-DD', REG_TM TIMESTAMP(0), CONTACT_TEL VARCHAR(20), HOME_ADDR VARCHAR(100), AFFL_SITE_ID VARCHAR(100), AFFL_BUSI_DIST_CD VARCHAR(20), BUSI_DIST_DISTANCE_CD VARCHAR(20), COMBINE_TYPE VARCHAR(20), COMBINE_SEQ INTEGER, ONLINE_REG_FLAG VARCHAR(2), ``` -------------------------------- ### Conditionally install hstore extension Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/24.txt Installs the hstore extension only if it does not already exist. ```sql CREATE EXTENSION IF NOT EXISTS hstore ``` -------------------------------- ### Start PostgreSQL container with Docker Compose Source: https://github.com/alibaba/druid/blob/master/druid-demo-petclinic/src/main/resources/db/postgres/petclinic_db_setup_postgres.txt Initializes the database environment required for the application. ```bash $ docker-compose up ``` -------------------------------- ### Multiple DataSource Configuration Example Source: https://github.com/alibaba/druid/blob/master/druid-spring-boot-starter/README_EN.md Example configuration for setting up multiple data sources, demonstrating how Druid properties can extend and override standard Spring datasource properties. ```xml spring.datasource.url= sspring.datasource.username= sspring.datasource.password= # DruidDataSurce configuration, extents spring.datasource. * configuration,, the same will be replaced. spring.datasource.druid.initial-size=5 spring.datasource.druid.max-active=5 ... ``` -------------------------------- ### SQL Parameterization Example Source: https://github.com/alibaba/druid/wiki/Druid连接池介绍 Demonstrates the transformation of non-parameterized SQL queries into parameterized forms for effective monitoring. ```sql select * from t where id = 1 select * from t where id = 2 select * from t where id = 3 ``` ```sql select * from t where id = ? ``` -------------------------------- ### Create Temporary Table Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/redshift/2.txt Example of creating a global temporary table with specified columns. ```sql CREATE TEMPORARY TABLE t1( col1 INT, col2 INT ) ``` ```sql CREATE TEMPORARY TABLE t1 ( col1 INT, col2 INT ) ``` -------------------------------- ### Install hstore in specific schema Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/24.txt Installs the hstore extension into the specified addons schema. ```sql CREATE EXTENSION hstore SCHEMA addons ``` -------------------------------- ### Begin Transaction Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/sqlserver/1.txt Starts a named transaction. ```sql BEGIN TRAN T1 ``` ```sql BEGIN TRANSACTION T1 ``` -------------------------------- ### Execute SELECT queries Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/mysql/2.txt Examples of selecting data with concatenation, aliases, and pagination. ```sql SELECT CONCAT(last_name, ', ', first_name) AS full_name FROM mytable ORDER BY full_name ``` ```sql SELECT * FROM tournament ORDER BY 2, 3 LIMIT 10 ``` -------------------------------- ### SQL Server JOIN Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/sqlserver/0.txt Demonstrates a LEFT JOIN clause in SQL Server. ```sql LEFT JOIN dbo.[Order History] oh ON c.customer_id = oh.customer_id; ``` -------------------------------- ### Install postgis with schema and version Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/24.txt Installs a specific version of postgis into the public schema, including dependencies. ```sql CREATE EXTENSION IF NOT EXISTS postgis SCHEMA public VERSION '3.4' CASCADE ``` -------------------------------- ### Install postgis with dependencies Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/24.txt Installs postgis and its dependencies using the CASCADE option. ```sql CREATE EXTENSION IF NOT EXISTS postgis CASCADE ``` -------------------------------- ### Install pg_trgm with version Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/24.txt Installs a specific version of the pg_trgm extension. ```sql CREATE EXTENSION pg_trgm VERSION '1.5' ``` -------------------------------- ### Create Local Temporary Table Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/redshift/2.txt Example of creating a local temporary table with specified columns. ```sql CREATE LOCAL TEMPORARY TABLE t1( col1 INT, col2 INT ) ``` ```sql CREATE LOCAL TEMPORARY TABLE t1 ( col1 INT, col2 INT ) ``` -------------------------------- ### Create Temporary Table (Alternative Syntax) Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/gaussdb/0.txt Create a temporary table using an alternative syntax. Functionally equivalent to the previous example. ```sql CREATE TEMPORARY TABLE test_temp ( L_ORDERKEY BIGINT NOT NULL ) ``` -------------------------------- ### SQL UNION ALL Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/0.txt Demonstrates combining results from two identical SELECT statements using UNION ALL. ```sql select son_id,parent_id from ((select son_id,parent_id from lance_temp limit 10) union all (select son_id,parent_id from lance_temp limit 10)) a; ``` -------------------------------- ### Multi-DataSource Configuration Source: https://github.com/alibaba/druid/blob/master/druid-spring-boot-starter/README.md Example configuration for multiple Druid data sources. ```properties spring.datasource.url= spring.datasource.username= spring.datasource.password= # Druid 数据源配置,继承spring.datasource.* 配置,相同则覆盖 ... spring.datasource.druid.initial-size=5 spring.datasource.druid.max-active=5 ... # Druid 数据源 1 配置,继承spring.datasource.druid.* 配置,相同则覆盖 ... spring.datasource.druid.one.max-active=10 spring.datasource.druid.one.max-wait=10000 ... # Druid 数据源 2 配置,继承spring.datasource.druid.* 配置,相同则覆盖 ... spring.datasource.druid.two.max-active=20 spring.datasource.druid.two.max-wait=20000 ... ``` -------------------------------- ### Create Simple Table in SQL Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/hologres/0.txt A basic example of creating a table with a single text column. ```sql CREATE TABLE blink_demo ( id text ); ``` -------------------------------- ### Integer Addition Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/mysql/1.txt A basic example of integer addition in SQL. ```sql SELECT 3 + 5 ``` ```sql SELECT 3 + 5 ``` -------------------------------- ### SQL INNER JOIN Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/0.txt Shows how to join multiple tables using INNER JOIN. ```sql select * from mc_job a inner join (mc_role b inner join mc_source c on b.id = c.id) as tem2 on tem2.user_id = a.id; ``` ```sql SELECT * FROM mc_job a INNER JOIN (mc_role b INNER JOIN mc_source c ON b.id = c.id) AS tem2 ON tem2.user_id = a.id; ``` -------------------------------- ### SQL Group By Clause Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/clickhouse/0.txt Demonstrates the use of the GROUP BY clause with aliases for columns. ```sql SELECT a, b, count(1) FROM test GROUP BY a AS c, b AS d ``` -------------------------------- ### Create Temporary Table #Test Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/sqlserver/1.txt Example of creating a temporary table named #Test with specified columns and data types. ```sql CREATE TABLE #Test (C1 nvarchar(10), C2 nvarchar(50), C3 datetime) ``` ```sql CREATE TABLE #Test ( C1 nvarchar(10), C2 nvarchar(50), C3 datetime ) ``` -------------------------------- ### Run Spring Boot application with PostgreSQL profile Source: https://github.com/alibaba/druid/blob/master/druid-demo-petclinic/src/main/resources/db/postgres/petclinic_db_setup_postgres.txt Starts the application using Maven while activating the postgres profile. ```bash mvn spring-boot:run -Dspring-boot.run.profiles=postgres ``` -------------------------------- ### SQL Basic Query Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/clickhouse/0.txt A simple SQL query to select a column from a table. Includes a comment for context. ```sql -- test SELECT a FROM b ``` -------------------------------- ### Show All Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/17.txt Displays all available configuration parameters. ```sql show all; ``` ```sql SHOW ALL; ``` -------------------------------- ### Start Transaction Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/17.txt Explicitly starts a new transaction. ```sql start transaction; ``` ```sql START TRANSACTION; ``` -------------------------------- ### Create Table with LIST Partitioning and HASH Subpartitioning Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/oceanbase/0.txt This example shows table creation with LIST partitioning on an integer column and HASH subpartitioning on another integer column. Note the NOT NULL constraints on relevant columns. ```sql CREATE TABLE t2_m_lh (col1 INT NOT NULL,col2 varchar(50),col3 INT NOT NULL) PARTITION BY LIST (col1) SUBPARTITION BY HASH(col3) SUBPARTITIONS 3 ( PARTITION p0 VALUES IN(100), PARTITION p1 VALUES IN(200), PARTITION p2 VALUES IN(300) ); ``` ```sql CREATE TABLE t2_m_lh ( col1 INT NOT NULL, col2 varchar(50), col3 INT NOT NULL ) PARTITION BY LIST (col1) SUBPARTITION BY HASH (col3) SUBPARTITIONS 3 ( PARTITION p0 VALUES IN (100), PARTITION p1 VALUES IN (200), PARTITION p2 VALUES IN (300) ); ``` -------------------------------- ### Install pg_stat_statements in pg_catalog Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/24.txt Installs the pg_stat_statements extension into the pg_catalog schema. ```sql CREATE EXTENSION IF NOT EXISTS pg_stat_statements SCHEMA pg_catalog ``` -------------------------------- ### Install uuid-ossp extension Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/postgresql/24.txt Installs the uuid-ossp extension using conditional syntax. ```sql CREATE EXTENSION IF NOT EXISTS "uuid-ossp" ``` -------------------------------- ### SQL Server Select Name and Password Hash with Brackets Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/sqlserver/0.txt Similar to the previous example, but uses bracket notation for schema and object names. ```sql SELECT name, password_hash FROM [master].[sys].sql_logins ``` -------------------------------- ### Build Druid with Maven Source: https://github.com/alibaba/druid/blob/master/AGENTS.md Use these Maven commands for building and testing the Druid project. Ensure Java 8+ JDK and Apache Maven 3.6+ are installed. ```bash mvn clean install # Full build with tests ``` ```bash mvn test -pl core # Core module tests only ``` ```bash mvn test -pl core -Dtest= # Single test class ``` -------------------------------- ### SQL CREATE TABLE Basic Syntax Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/clickhouse/0.txt Demonstrates the basic syntax for creating a table with an Array(UInt64) column. ```sql CREATE TABLE test.test ( `aa` ARRAY(UInt64) ) ENGINE = MergeTree() ``` -------------------------------- ### Create Table with Dynamic Partitioning Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/starrocks/1.txt Sets up a table with dynamic partitioning enabled, specifying time unit, start/end ranges, prefix, and buckets. Storage medium can also be defined. ```sql CREATE TABLE example_db.dynamic_partition ( k1 DATE, k2 INT, k3 SMALLINT, v1 VARCHAR(2048), v2 DATETIME DEFAULT "2014-02-04 15:36:00" ) ENGINE=olap DUPLICATE KEY(k1, k2, k3) PARTITION BY RANGE (k1) ( PARTITION p1 VALUES LESS THAN ("2014-01-01"), PARTITION p2 VALUES LESS THAN ("2014-06-01"), PARTITION p3 VALUES LESS THAN ("2014-12-01") ) DISTRIBUTED BY HASH(k2) PROPERTIES( "storage_medium" = "SSD", "dynamic_partition.enable" = "true", "dynamic_partition.time_unit" = "DAY", "dynamic_partition.start" = "-3", "dynamic_partition.end" = "3", "dynamic_partition.prefix" = "p", "dynamic_partition.buckets" = "10" ) ``` ```sql CREATE TABLE example_db.dynamic_partition ( k1 DATE, k2 INT, k3 SMALLINT, v1 VARCHAR(2048), v2 DATETIME DEFAULT "2014-02-04 15:36:00" ) ENGINE = olap DUPLICATE KEY (k1, k2, k3) PARTITION BY RANGE (k1) ( PARTITION p1 VALUES LESS THAN ("2014-01-01"), PARTITION p2 VALUES LESS THAN ("2014-06-01"), PARTITION p3 VALUES LESS THAN ("2014-12-01") ) DISTRIBUTED BY HASH (k2) PROPERTIES ( "storage_medium" = "SSD", "dynamic_partition.enable" = "true", "dynamic_partition.time_unit" = "DAY", "dynamic_partition.start" = "-3", "dynamic_partition.end" = "3", "dynamic_partition.prefix" = "p", "dynamic_partition.buckets" = "10" ) ``` -------------------------------- ### Show Schemas Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/hive/0.txt Lists all available databases. ```sql show schemas ``` ```sql SHOW DATABASES ``` -------------------------------- ### Deep Inheritance Chain Example Source: https://github.com/alibaba/druid/blob/master/docs/PARSER_DEEP_ANALYSIS.md Shows an example of a deep, 4-level inheritance chain in the parser hierarchy. ```text Lexer → HiveLexer → SparkLexer → DatabricksLexer SQLExprParser → HiveExprParser → SparkExprParser → DatabricksExprParser ``` -------------------------------- ### SQL FOR UPDATE Example 1 Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/oracle-3.txt A basic example of using the FOR UPDATE clause with a subquery. This locks the selected employee_id rows. ```sql SELECT employee_id FROM (SELECT employee_id+1 AS employee_id FROM employees) FOR UPDATE; ``` -------------------------------- ### Create Table with Aggregate Key and HLL/BITMAP Columns Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/doris/1.txt Sets up a table with TINYINT and DECIMAL keys, and HLL/BITMAP value columns using aggregate key and hash distribution. ```sql CREATE TABLE example_db.example_table ( k1 TINYINT, k2 DECIMAL(10, 2) DEFAULT "10.5", v1 HLL HLL_UNION, v2 BITMAP BITMAP_UNION ) ENGINE=olap AGGREGATE KEY(k1, k2) DISTRIBUTED BY HASH(k1) BUCKETS 32 ``` ```sql CREATE TABLE example_db.example_table ( k1 TINYINT, k2 DECIMAL(10, 2) DEFAULT "10.5", v1 HLL HLL_UNION, v2 BITMAP BITMAP_UNION ) ENGINE = olap AGGREGATE KEY (k1, k2) DISTRIBUTED BY HASH (k1) BUCKETS 32 ``` -------------------------------- ### Example Druid SQL Log Output Source: https://github.com/alibaba/druid/wiki/Druid中使用log4j2进行日志输出 This is an example of the detailed SQL execution logs generated by Druid when the SLF4J filter is enabled and configured. ```log [2018-02-07 14:15:50] DEBUG 134 statementLog - {conn-10001, pstmt-20000} created. INSERT INTO city ( id,name,state ) VALUES( ?,?,? ) [2018-02-07 14:15:50] DEBUG 134 statementLog - {conn-10001, pstmt-20000} Parameters : [null, b2ffa7bd-6b53-4392-aa39-fdf8e172ddf9, a9eb5f01-f6e6-414a-bde3-865f72097550] [2018-02-07 14:15:50] DEBUG 134 statementLog - {conn-10001, pstmt-20000} Types : [OTHER, VARCHAR, VARCHAR] [2018-02-07 14:15:50] DEBUG 134 statementLog - {conn-10001, pstmt-20000} executed. 5.113815 millis. INSERT INTO city ( id,name,state ) VALUES( ?,?,? ) [2018-02-07 14:15:50] DEBUG 134 statementLog - {conn-10001, stmt-20001} executed. 0.874903 millis. SELECT LAST_INSERT_ID() [2018-02-07 14:15:52] DEBUG 134 statementLog - {conn-10001, stmt-20002, rs-50001} query executed. 0.622665 millis. SELECT 1 ``` -------------------------------- ### Create Partitioned Table in SQL Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/hologres/0.txt Shows the syntax for creating a logically partitioned table with specific column types and partitioning keys. ```sql CREATE TABLE IF NOT EXISTS my_partitioned_table ( id INT, name text, value FLOAT, arr INT[], dt TEXT NOT NULL, region TEXT NOT NULL ) LOGICAL PARTITION BY LIST (dt, region) WITH ( orientation = 'column', partition_require_filter = false ); ``` -------------------------------- ### SQL REGEXP_SUBSTR Function Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/snowflake/9.txt Extract substrings that match a regular expression using REGEXP_SUBSTR. This example extracts the first sequence of digits. ```sql SELECT REGEXP_SUBSTR(description, '[0-9]+') AS first_number FROM t1 ``` ```sql SELECT REGEXP_SUBSTR(description, '[0-9]+') AS first_number FROM t1 ``` -------------------------------- ### SQL FOR UPDATE Example 2 Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/oracle-3.txt Another example of the FOR UPDATE clause, showing a slightly different formatting of the subquery. It also locks the selected employee_id rows. ```sql SELECT employee_id FROM ( SELECT employee_id + 1 AS employee_id FROM employees ) FOR UPDATE; ``` -------------------------------- ### Initialize and Use SchemaRepository Source: https://github.com/alibaba/druid/wiki/SQL_Schema_Repository Initialize SchemaRepository with a database type (e.g., MySQL) and use it to execute SQL commands like CREATE TABLE and SHOW COLUMNS. ```java import com.alibaba.druid.sql.repository.SchemaRepository; // SchemaRepository是和数据库类型相关的,构造时需要传入dbType final String dbType = JdbcConstants.MYSQL; SchemaRepository repository = new SchemaRepository(dbType); repository.console("use sc00;"); String sql = "CREATE TABLE `test1` (\n" + " `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',\n" + " `c_tinyint` tinyint(4) DEFAULT '1' COMMENT 'tinyint',\n" + " `c_smallint` smallint(6) DEFAULT 0 COMMENT 'smallint',\n" + " `c_mediumint` mediumint(9) DEFAULT NULL COMMENT 'mediumint',\n" + " `c_int` int(11) DEFAULT NULL COMMENT 'int',\n" + " `c_bigint` bigint(20) DEFAULT NULL COMMENT 'bigint',\n" + " `c_decimal` decimal(10,3) DEFAULT NULL COMMENT 'decimal',\n" + " `c_date` date DEFAULT '0000-00-00' COMMENT 'date',\n" + " `c_datetime` datetime DEFAULT '0000-00-00 00:00:00' COMMENT 'datetime',\n" + " `c_timestamp` timestamp NULL DEFAULT NULL COMMENT 'timestamp' ON UPDATE CURRENT_TIMESTAMP ,\n" + " `c_time` time DEFAULT NULL COMMENT 'time',\n" + " `c_char` char(10) DEFAULT NULL COMMENT 'char',\n" + " `c_varchar` varchar(10) DEFAULT 'hello' COMMENT 'varchar',\n" + " `c_blob` blob COMMENT 'blob',\n" + " `c_text` text COMMENT 'text',\n" + " `c_mediumtext` mediumtext COMMENT 'mediumtext',\n" + " `c_longblob` longblob COMMENT 'longblob',\n" + " PRIMARY KEY (`id`,`c_tinyint`),\n" + " UNIQUE KEY `uk_a` (`c_varchar`,`c_mediumint`),\n" + " KEY `k_c` (`c_tinyint`,`c_int`),\n" + " KEY `k_d` (`c_char`,`c_bigint`)\n" + ") ENGINE=InnoDB AUTO_INCREMENT=1769503 DEFAULT CHARSET=utf8mb4 COMMENT='10000000'" ; repository.console(sql); // 在如下的代码中可以知道repository中已经存在表test1 MySqlCreateTableStatement createTableStmt = (MySqlCreateTableStatement) repository.findTable("test1").getStatement(); assertEquals(21, createTableStmt.getTableElementList().size()); // 通过执行命令"show columns from test1"可以获得mysql console风格的输出 assertEquals("+--------------+---------------+------+-----+---------------------+-----------------------------+\n" + "| Field | Type | Null | Key | Default | Extra |\n" + "+--------------+---------------+------+-----+---------------------+-----------------------------+\n" + "| id | bigint(20) | NO | PRI | NULL | auto_increment |\n" + "| c_tinyint | tinyint(4) | YES | PRI | 1 | |\n" + "| c_smallint | smallint(6) | YES | | 0 | |\n" + "| c_mediumint | mediumint(9) | YES | | NULL | |\n" + "| c_int | int(11) | YES | | NULL | |\n" + "| c_bigint | bigint(20) | YES | | NULL | |\n" + "| c_decimal | decimal(10,3) | YES | | NULL | |\n" + "| c_date | date | YES | | 0000-00-00 | |\n" + "| c_datetime | datetime | YES | | 0000-00-00 00:00:00 | |\n" + "| c_timestamp | timestamp | YES | | NULL | on update CURRENT_TIMESTAMP |\n" + "| c_time | time | YES | | NULL | |\n" + "| c_char | char(10) | YES | MUL | NULL | |\n" + "| c_varchar | varchar(10) | YES | MUL | hello | |\n" + "| c_blob | blob | YES | | NULL | |\n" + "| c_text | text | YES | | NULL | |\n" + "| c_mediumtext | mediumtext | YES | | NULL | |\n" + "| c_longblob | longblob | YES | | NULL | |\n" + "+--------------+---------------+------+-----+---------------------+-----------------------------+\n", repository.console("show columns from test1")); // 执行alter语句,修改repository中内容 repository.console("alter table test1 drop column c_decimal;"); assertEquals(20, createTableStmt.getTableElementList().size()); assertEquals("+--------------+--------------+------+-----+---------------------+-----------------------------+\n" + "| Field | Type | Null | Key | Default | Extra |\n" + "+--------------+--------------+------+-----+---------------------+-----------------------------+\n" + ``` -------------------------------- ### Create Tables and Parse SQL with Druid Source: https://github.com/alibaba/druid/wiki/SQL_Schema_Repository Demonstrates creating tables and parsing a SQL join statement using Druid's SQLUtils. It also shows how to resolve table and column information using a SchemaRepository. ```java final String dbType = JdbcConstants.MYSQL; SchemaRepository repository = new SchemaRepository(dbType); repository.console("create table t_emp(emp_id bigint, name varchar(20));"); repository.console("create table t_org(org_id bigint, name varchar(20));"); String sql = "SELECT emp_id, a.name AS emp_name, org_id, b.name AS org_name\n" + "FROM t_emp a\n" + "\tINNER JOIN t_org b ON a.emp_id = b.org_id"; List stmtList = SQLUtils.parseStatements(sql, dbType); assertEquals(1, stmtList.size()); SQLSelectStatement stmt = (SQLSelectStatement) stmtList.get(0); SQLSelectQueryBlock queryBlock = stmt.getSelect().getQueryBlock(); // 大小写不敏感 assertNotNull(queryBlock.findTableSource("A")); same(queryBlock.findTableSource("a"), queryBlock.findTableSource("A")); assertNull(queryBlock.findTableSourceWithColumn("emp_id")); // 使用repository做column resolve repository.resolve(stmt); assertNotNull(queryBlock.findTableSourceWithColumn("emp_id")); SQLExprTableSource tableSource = (SQLExprTableSource) queryBlock.findTableSourceWithColumn("emp_id"); assertNotNull(tableSource.getSchemaObject()); SQLCreateTableStatement createTableStmt = (SQLCreateTableStatement) tableSource.getSchemaObject().getStatement(); assertNotNull(createTableStmt); SQLSelectItem selectItem = queryBlock.findSelectItem("org_name"); assertNotNull(selectItem); SQLPropertyExpr selectItemExpr = (SQLPropertyExpr) selectItem.getExpr(); SQLColumnDefinition column = selectItemExpr.getResolvedColumn(); assertNotNull(column); assertEquals("name", column.getName().toString()); assertEquals("t_org", (((SQLCreateTableStatement)column.getParent()).getName().toString())); same(queryBlock.findTableSource("B"), selectItemExpr.getResolvedTableSource()); ``` -------------------------------- ### SQL UNPIVOT Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/spark/0.txt Use UNPIVOT to transform pivoted data back into rows. This example unpivots 'oncall_for_unpivot' table, separating primary and secondary contact information. ```sql SELECT * FROM oncall_for_unpivot UNPIVOT ( (name, email, phone) FOR precedence IN ((name1, email1, phone1) AS primary, (name2, email2, phone2) AS secondary)) ``` -------------------------------- ### SQL UNION Example 2 with AS Alias Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/oracle-43.txt An alternative syntax for the UNION operator using the AS keyword for column aliasing. This example also combines department and warehouse data. ```sql SELECT location_id, department_name AS "Department", TO_CHAR(NULL) AS "Warehouse" FROM departments UNION SELECT location_id, TO_CHAR(NULL) AS "Department", warehouse_name FROM warehouses; ``` -------------------------------- ### Configure Spring Boot Starter Source: https://github.com/alibaba/druid/blob/master/README_EN.md Add the Spring Boot 3.x starter dependency and configure the datasource in application.yml. ```xml com.alibaba druid-spring-boot-3-starter 1.2.24 ``` ```yaml # application.yml spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: password druid: initial-size: 5 max-active: 20 min-idle: 5 max-wait: 60000 filter: stat: enabled: true log-slow-sql: true slow-sql-millis: 2000 wall: enabled: true ``` -------------------------------- ### SQL CAST Function Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/snowflake/9.txt Use the CAST function to convert a value from one data type to another. This example converts an amount to a DECIMAL type with specified precision and scale. ```sql SELECT CAST(amount AS DECIMAL(10, 2)) FROM transactions ``` ```sql SELECT CAST(amount AS DECIMAL(10, 2)) FROM transactions ``` -------------------------------- ### Build Druid from Source Source: https://github.com/alibaba/druid/blob/master/README_EN.md Commands to clone the repository and build the project using Maven. ```bash git clone https://github.com/alibaba/druid.git cd druid mvn clean install ``` -------------------------------- ### Druid Data Source Statistics Example Source: https://github.com/alibaba/druid/blob/master/druid-spring-boot-starter/README_EN.md An example JSON structure representing the monitoring data for a Druid data source. This data includes connection pool statistics, query counts, and transaction information. ```json [ { "Identity": 1583082378, "Name": "DataSource-1583082378", "DbType": "h2", "DriverClassName": "org.h2.Driver", "URL": "jdbc:h2:file:./demo-db", "UserName": "sa", "FilterClassNames": [ "com.alibaba.druid.filter.stat.StatFilter" ], "WaitThreadCount": 0, "NotEmptyWaitCount": 0, "NotEmptyWaitMillis": 0, "PoolingCount": 2, "PoolingPeak": 2, "PoolingPeakTime": 1533782955104, "ActiveCount": 0, "ActivePeak": 1, "ActivePeakTime": 1533782955178, "InitialSize": 2, "MinIdle": 2, "MaxActive": 30, "QueryTimeout": 0, "TransactionQueryTimeout": 0, "LoginTimeout": 0, "ValidConnectionCheckerClassName": null, "ExceptionSorterClassName": null, "TestOnBorrow": true, "TestOnReturn": true, "TestWhileIdle": true, "DefaultAutoCommit": true, "DefaultReadOnly": null, "DefaultTransactionIsolation": null, "LogicConnectCount": 103, "LogicCloseCount": 103, "LogicConnectErrorCount": 0, "PhysicalConnectCount": 2, "PhysicalCloseCount": 0, "PhysicalConnectErrorCount": 0, "ExecuteCount": 102, "ErrorCount": 0, "CommitCount": 100, "RollbackCount": 0, "PSCacheAccessCount": 100, "PSCacheHitCount": 99, "PSCacheMissCount": 1, "StartTransactionCount": 100, "TransactionHistogram": [ 55, 44, 1, 0, 0, 0, 0 ], "ConnectionHoldTimeHistogram": [ 53, 47, 3, 0, 0, 0, 0, 0 ], "RemoveAbandoned": false, "ClobOpenCount": 0, "BlobOpenCount": 0, "KeepAliveCheckCount": 0, "KeepAlive": false, "FailFast": false, "MaxWait": 1234, "MaxWaitThreadCount": -1, "PoolPreparedStatements": true, "MaxPoolPreparedStatementPerConnectionSize": 5, "MinEvictableIdleTimeMillis": 30001, "MaxEvictableIdleTimeMillis": 25200000, "LogDifferentThread": true, "RecycleErrorCount": 0, "PreparedStatementOpenCount": 1, "PreparedStatementClosedCount": 0, "UseUnfairLock": true, "InitGlobalVariants": false, "InitVariants": false } ] ``` -------------------------------- ### Create Table with Dynamic Partitioning Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/doris/1.txt Configures a table with DATE and INT keys, and DATETIME values. It uses dynamic partitioning based on a DATE column with specified time unit, start, and end ranges. ```sql CREATE TABLE example_db.dynamic_partition ( k1 DATE, k2 INT, k3 SMALLINT, v1 VARCHAR(2048), v2 DATETIME DEFAULT "2014-02-04 15:36:00" ) DUPLICATE KEY(k1, k2, k3) PARTITION BY RANGE (k1) () DISTRIBUTED BY HASH(k2) BUCKETS 32 PROPERTIES( "dynamic_partition.time_unit" = "DAY", "dynamic_partition.start" = "-3", "dynamic_partition.end" = "3", "dynamic_partition.prefix" = "p", "dynamic_partition.buckets" = "32" ) ``` ```sql CREATE TABLE example_db.dynamic_partition ( k1 DATE, k2 INT, k3 SMALLINT, v1 VARCHAR(2048), v2 DATETIME DEFAULT "2014-02-04 15:36:00" ) DUPLICATE KEY (k1, k2, k3) PARTITION BY RANGE (k1) () DISTRIBUTED BY HASH (k2) BUCKETS 32 PROPERTIES ( "dynamic_partition.time_unit" = "DAY", "dynamic_partition.start" = "-3", "dynamic_partition.end" = "3", "dynamic_partition.prefix" = "p", "dynamic_partition.buckets" = "32" ) ``` -------------------------------- ### Hierarchical Query with Pagination Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/oracle-21.txt This SQL query retrieves hierarchical data from tables x_1_2 and k_2_3. It uses CONNECT BY to traverse parent-child relationships and START WITH to define the starting point. Pagination is implemented using rownum. ```sql select * from ( select rownum rnm, z.* from ( select distinct(tt.id) use_less_id, tt.* from ( select t.*, rct.parent_id, RCT.NAME as trunk_name from x_1_2 t, k_2_3 rct where t.is_deleted ='n' and t.trunk_id = rct.id ) tt CONNECT BY prior parent_id = trunk_id start with trunk_name = 'rc.mf.Caesar' order by load_order nulls last ) z where rownum < ? ) where rnm >= ? ``` ```sql SELECT * FROM ( SELECT rownum AS rnm, z.* FROM ( SELECT DISTINCT tt.id AS use_less_id, tt.* FROM ( SELECT t.*, rct.parent_id, RCT.NAME AS trunk_name FROM x_1_2 t, k_2_3 rct WHERE t.is_deleted = 'n' AND t.trunk_id = rct.id ) tt START WITH trunk_name = 'rc.mf.Caesar' CONNECT BY PRIOR parent_id = trunk_id ORDER BY load_order NULLS LAST ) z WHERE rownum < ? ) WHERE rnm >= ? ``` -------------------------------- ### Initialize Druid SQL Detail Module Source: https://github.com/alibaba/druid/blob/master/druid-admin/src/main/resources/support/http/resources/sql-detail.html Initializes the druid.sqlDetail module, fetches the SQL ID and service ID from URL parameters, and sets up the JSON API link. This is the main entry point for the SQL detail view. ```javascript $.namespace("druid.sqlDetail"); druid.sqlDetail = function () { var sqlId = druid.common.getUrlVar("sqlId"); var serviceId = druid.common.getUrlVar("serviceId"); return { init : function() { druid.common.buildHead(2); this.ajaxRequestForBasicInfo(); $("#viewJsonApi").attr("href", 'sql-' + sqlId + ".json"); }, ajaxRequestForBasicInfo : function() { $.ajax({ type: 'POST', url: 'serviceId='+serviceId+'&sql-' + sqlId + ".json", success: function(data) { console.log("--------------"); console.log(data); var sqlInfo = data.Content; console.log("sqlInfo:" + sqlInfo.SQL); if (sqlInfo == null) return; var sql = sqlInfo.SQL; if (sql != null) { sql = sql.replace(//g,">"); } else { sql = ''; } $("#fullSql").text(sql) $("#formattedSql").text(sqlInfo.formattedSql) $("#parsedtable").text(sqlInfo.parsedTable) $("#parsedfields").text(sqlInfo.parsedFields) $("#parsedConditions").text(sqlInfo.parsedConditions) $("#parsedRelationships").text(sqlInfo.parsedRelationships) $("#parsedOrderbycolumns").text(sqlInfo.parsedOrderbycolumns) $("#MaxTimespanOccurTime").text(sqlInfo.MaxTimespanOccurTime) $("#LastSlowParameters").text(sqlInfo.LastSlowParameters) $("#MaxTimespan").text(sqlInfo.MaxTimespan) $("#LastErrorMessage").text(sqlInfo.LastErrorMessage) $("#LastErrorClass").text(sqlInfo.LastErrorClass) $("#LastErrorTime").text(sqlInfo.LastErrorTime) $("#LastErrorStackTrace").text(sqlInfo.LastErrorStackTrace) $("#BatchSizeMax").text(sqlInfo.BatchSizeMax) $("#BatchSizeTotal").text(sqlInfo.BatchSizeTotal) $("#BlobOpenCount").text(sqlInfo.BlobOpenCount) $("#ClobOpenCount").text(sqlInfo.ClobOpenCount) $("#InputStreamOpenCount").text(sqlInfo.InputStreamOpenCount) $("#ReaderOpenCount").text(sqlInfo.ReaderOpenCount) $("#ReadStringLength").text(sqlInfo.ReadStringLength) $("#ReadBytesLength").text(sqlInfo.ReadBytesLength) druid.lang.trigger(); }, dataType: "json" }); } } }(); $(document).ready(function() { druid.sqlDetail.init(); }); ``` -------------------------------- ### Integer Multiplication Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/mysql/1.txt A basic example of integer multiplication in SQL. ```sql SELECT 3*5 ``` ```sql SELECT 3 * 5 ``` -------------------------------- ### Initialize Druid SQL Detail Module Source: https://github.com/alibaba/druid/blob/master/core/src/main/resources/support/http/resources/sql-detail.html Initializes the druid.sqlDetail module, fetches the SQL ID from the URL, and sets up the JSON API link. This should be called when the document is ready. ```javascript $.namespace("druid.sqlDetail"); druid.sqlDetail = function () { var sqlId = druid.common.getUrlVar("sqlId"); return { init: function () { druid.common.buildHead(2); this.ajaxRequestForBasicInfo(); $("#viewJsonApi").attr("href", 'sql-' + sqlId + ".json"); }, ajaxRequestForBasicInfo: function () { $.ajax({ type: 'POST', url: 'sql-' + sqlId + ".json", success: function (data) { var sqlInfo = data.Content; if (sqlInfo == null) return; var sql = sqlInfo.SQL; if (sql != null) { sql = sql.replace(//g, ">"); } else { sql = ''; } $("#fullSql").text(sql) $("#formattedSql").text(sqlInfo.formattedSql) $("#parsedtable").text(sqlInfo.parsedTable) $("#parsedfields").text(sqlInfo.parsedFields) $("#parsedConditions").text(sqlInfo.parsedConditions) $("#parsedRelationships").text(sqlInfo.parsedRelationships) $("#parsedOrderbycolumns").text(sqlInfo.parsedOrderbycolumns) $("#MaxTimespanOccurTime").text(sqlInfo.MaxTimespanOccurTime) $("#LastSlowParameters").text(sqlInfo.LastSlowParameters) $("#MaxTimespan").text(sqlInfo.MaxTimespan) $("#LastErrorMessage").text(sqlInfo.LastErrorMessage) $("#LastErrorClass").text(sqlInfo.LastErrorClass) $("#LastErrorTime").text(sqlInfo.LastErrorTime) $("#LastErrorStackTrace").text(sqlInfo.LastErrorStackTrace) $("#BatchSizeMax").text(sqlInfo.BatchSizeMax) $("#BatchSizeTotal").text(sqlInfo.BatchSizeTotal) $("#BlobOpenCount").text(sqlInfo.BlobOpenCount) $("#ClobOpenCount").text(sqlInfo.ClobOpenCount) $("#InputStreamOpenCount").text(sqlInfo.InputStreamOpenCount) $("#ReaderOpenCount").text(sqlInfo.ReaderOpenCount) $("#ReadStringLength").text(sqlInfo.ReadStringLength) $("#ReadBytesLength").text(sqlInfo.ReadBytesLength) druid.lang.trigger(); }, dataType: "json" }); } } }(); $(document).ready(function () { druid.sqlDetail.init(); }); ``` -------------------------------- ### Integer Subtraction Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/mysql/1.txt A basic example of integer subtraction in SQL. ```sql SELECT 3-5 ``` ```sql SELECT 3 - 5 ``` -------------------------------- ### Normalize Data Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/teradata/0.txt Examples of using the NORMALIZE clause for temporal data. ```sql SELECT NORMALIZE ON MEETS OR OVERLAPS emp_id, duration FROM project ``` ```sql SELECT NORMALIZE ON MEETS OR OVERLAPS emp_id, duration FROM project ``` ```sql SELECT NORMALIZE project_name, duration FROM project ``` ```sql SELECT NORMALIZE project_name, duration FROM project ``` -------------------------------- ### Show Functions Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/hive/0.txt Lists all available functions. ```sql show functions ``` ```sql SHOW FUNCTIONS ``` -------------------------------- ### Get Current Schema in SQL Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/hologres/0.txt Retrieves the name of the current schema. ```sql SELECT current_schema(); ``` -------------------------------- ### SQL Server Subquery Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/sqlserver/0.txt Demonstrates a SELECT statement with a subquery in the WHERE clause. ```sql SELECT * FROM [test].[test] WHERE [a] IN ( SELECT [c] FROM [test] ) ``` -------------------------------- ### Create Table with LIST COLUMNS and HASH Subpartitioning Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/oceanbase/0.txt Use this syntax to create a table partitioned by a list of column values and subpartitioned by hash. Ensure the column types match the partitioning strategy. ```sql CREATE TABLE t2_m_lch(col1 INT,col2 INT) PARTITION BY LIST COLUMNS(col1) SUBPARTITION BY HASH(col2) SUBPARTITIONS 5 ( PARTITION p0 VALUES IN(100), PARTITION p1 VALUES IN(200), PARTITION p2 VALUES IN(300) ); ``` ```sql CREATE TABLE t2_m_lch ( col1 INT, col2 INT ) PARTITION BY LIST COLUMNS (col1) SUBPARTITION BY HASH (col2) SUBPARTITIONS 5 ( PARTITION p0 VALUES IN (100), PARTITION p1 VALUES IN (200), PARTITION p2 VALUES IN (300) ); ``` -------------------------------- ### SQL Window Functions LAG and LEAD Example Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/snowflake/9.txt Illustrates the use of window functions LAG and LEAD to access previous and next rows within a partition, ordered by a specified column. Requires an ORDER BY clause within the OVER() clause. ```sql SELECT id, LAG(value, 1) OVER (ORDER BY id) AS prev_value, LEAD(value, 1) OVER (ORDER BY id) AS next_value FROM time_series ``` ```sql SELECT id, LAG(value, 1) OVER (ORDER BY id) AS prev_value , LEAD(value, 1) OVER (ORDER BY id) AS next_value FROM time_series ``` -------------------------------- ### Job Get Query Results API Source: https://github.com/alibaba/druid/blob/master/core/src/test/resources/bvt/parser/bigquery/0.txt Retrieves the results of a query job. ```APIDOC ## POST /api/jobs/getQueryResults ### Description Retrieves the results of a query job. ### Method POST ### Endpoint /api/jobs/getQueryResults ### Request Body - **jobGetQueryResultsRequest** (STRUCT) - Required - The request object for getting query results. - **maxResults** (INT64) - Optional - The maximum number of results to return. - **startRow** (INT64) - Optional - The starting row index for the results. ### Response #### Success Response (200) - **queryOutputRowCount** (INT64) - The total number of rows in the query output. - **totalLoadOutputBytes** (INT64) - The total bytes loaded for the query output. - **referencedTables** (ARRAY>) - List of tables referenced in the query. - **referencedViews** (ARRAY>) - List of views referenced in the query. - **totalTablesProcessed** (INT64) - Total number of tables processed. - **totalViewsProcessed** (INT64) - Total number of views processed. ### Response Example ```json { "queryOutputRowCount": 100, "totalLoadOutputBytes": 10240, "referencedTables": [ { "projectId": "my-project", "datasetId": "my-dataset", "tableId": "my-table" } ], "totalTablesProcessed": 1 } ``` ``` -------------------------------- ### GET /datasource/status Source: https://github.com/alibaba/druid/blob/master/core/src/main/resources/support/http/resources/datasource.html Retrieves the current configuration and runtime statistics for the Druid datasource. ```APIDOC ## GET /datasource/status ### Description Retrieves the current state, configuration settings, and performance metrics of the Druid datasource. ### Method GET ### Endpoint /datasource/status ### Response #### Success Response (200) - **DefaultReadOnly** (boolean) - Default read-only status - **DefaultTransactionIsolation** (integer) - Default transaction isolation level - **MinEvictableIdleTimeMillis** (long) - Minimum time a connection can remain idle before eviction - **MaxEvictableIdleTimeMillis** (long) - Maximum time a connection can remain idle before eviction - **KeepAlive** (boolean) - Whether keep-alive is enabled - **FailFast** (boolean) - Whether fail-fast is enabled - **PoolPreparedStatements** (boolean) - Whether prepared statement pooling is enabled - **MaxPoolPreparedStatementPerConnectionSize** (integer) - Max prepared statements per connection - **MaxWait** (long) - Maximum wait time for a connection - **MaxWaitThreadCount** (integer) - Maximum number of threads waiting for a connection - **LogDifferentThread** (boolean) - Whether to log different threads - **UseUnfairLock** (boolean) - Whether to use unfair locking - **InitGlobalVariants** (string) - Initial global variants - **InitVariants** (string) - Initial variants - **NotEmptyWaitCount** (long) - Total times for wait to get a connection - **NotEmptyWaitMillis** (long) - Total milliseconds for wait to get a connection - **WaitThreadCount** (integer) - The current waiting thread count - **StartTransactionCount** (long) - The count of start transaction - **TransactionHistogram** (array) - The histogram values of transaction time - **PoolingCount** (integer) - The current useful connection count - **PoolingPeak** (integer) - The peak connection count ```