Skip to main content

wtx/database/schema_manager/fixed_sql_commands/
mysql.rs

1use crate::{
2  collection::Vector,
3  database::{Executor, FromRecords, Identifier, client::mysql::Mysql},
4};
5
6pub(crate) const CREATE_MIGRATION_TABLES: &str = concat!(
7  "CREATE TABLE IF NOT EXISTS _wtx_migration_group (",
8  _wtx_migration_group_columns!(),
9  ");
10  CREATE TABLE IF NOT EXISTS _wtx_migration (",
11  _serial_id!(),
12  "created_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,",
13  _wtx_migration_columns!(),
14  ");"
15);
16
17// https://stackoverflow.com/questions/12403662/how-to-remove-all-mysql-tables-from-the-command-line-without-drop-database-permi/18625545#18625545
18pub(crate) async fn clear<E, ERR>(executor: &mut E) -> Result<(), ERR>
19where
20  E: Executor<Database = Mysql<ERR>>,
21  ERR: From<crate::Error>,
22{
23  let cmd = "
24    SET FOREIGN_KEY_CHECKS = 0;
25    SET GROUP_CONCAT_MAX_LEN=32768;
26    SET @tables = NULL;
27    SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables
28      FROM information_schema.tables
29      WHERE table_schema = (SELECT DATABASE());
30    SELECT IFNULL(@tables,'dummy') INTO @tables;
31
32    SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
33    PREPARE stmt FROM @tables;
34    EXECUTE stmt;
35    DEALLOCATE PREPARE stmt;
36    SET FOREIGN_KEY_CHECKS = 1;
37  ";
38  executor.execute_ignored(cmd).await?;
39  Ok(())
40}
41
42// https://github.com/flyway/flyway/blob/master/flyway-core/src/main/java/org/flywaydb/core/internal/database/mysql/MySQLSchema.java
43pub(crate) async fn table_names<E, ERR>(
44  executor: &mut E,
45  results: &mut Vector<Identifier>,
46) -> Result<(), ERR>
47where
48  E: Executor<Database = Mysql<ERR>>,
49  ERR: From<crate::Error>,
50{
51  let cmd = "SELECT
52      all_tables.table_name AS table_name
53    FROM
54      information_schema.tables AS all_tables
55    WHERE
56      all_tables.table_schema NOT IN ('performance_schema') AND all_tables.table_type IN ('BASE TABLE', 'SYSTEM VERSIONED')";
57  let records = executor.execute_stmt_many(cmd, (), |_| Ok(())).await?;
58  for elem in <Identifier as FromRecords<E::Database>>::many(&records) {
59    results.push(elem?)?;
60  }
61  Ok(())
62}