Module schema

Source
Expand description

Facility for parsing SQL schemas into a terse format that can be used for typing statements.

use sql_type::{schema::parse_schemas, TypeOptions, SQLDialect, Issues};
let schemas = "
    -- Table structure for table `events`
    DROP TABLE IF EXISTS `events`;
    CREATE TABLE `events` (
      `id` bigint(20) NOT NULL,
      `user` int(11) NOT NULL,
      `event_key` int(11) NOT NULL,
      `time` datetime NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    -- Table structure for table `events_keys`
    DROP TABLE IF EXISTS `event_keys`;
    CREATE TABLE `event_keys` (
      `id` int(11) NOT NULL,
      `name` text NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    -- Stand-in structure for view `events_view`
    -- (See below for the actual view)
    DROP VIEW IF EXISTS `events_view`;
    CREATE TABLE `events_view` (
        `id` int(11),
        `user` int(11) NOT NULL,
        `event_key` text NOT NULL,
        `time` datetime NOT NULL
    );

    -- Indexes for table `events`
    ALTER TABLE `events`
      ADD PRIMARY KEY (`id`),
      ADD KEY `time` (`time`),
      ADD KEY `event_key` (`event_key`);

    -- Indexes for table `event_keys`
    ALTER TABLE `event_keys`
      ADD PRIMARY KEY (`id`);

    -- Constraints for table `events`
    ALTER TABLE `events`
      ADD CONSTRAINT `event_key` FOREIGN KEY (`event_key`) REFERENCES `event_keys` (`id`);

    -- Structure for view `events_view`
    DROP TABLE IF EXISTS `events_view`;
    DROP VIEW IF EXISTS `events_view`;
    CREATE ALGORITHM=UNDEFINED DEFINER=`phpmyadmin`@`localhost`
        SQL SECURITY DEFINER VIEW `events_view` AS
        SELECT
            `events`.`id` AS `id`,
            `events`.`user` AS `user`,
            `event_keys`.`name` AS `event_key`,
            `events`.`time` AS `time`
        FROM `events`, `event_keys`
        WHERE `events`.`event_key` = `event_keys`.`id`;
    ";

let mut issues = Issues::new(schemas);
let schemas = parse_schemas(schemas,
    &mut issues,
    &TypeOptions::new().dialect(SQLDialect::MariaDB));

assert!(issues.is_ok());

for (name, schema) in schemas.schemas {
    println!("{name}: {schema:?}")
}

Structs§

Column
A column in a schema
Functions
A function
IndexKey
Procedure
A procedure
Schema
Schema representing a table or view
Schemas
A description of tables, view, procedures and function in a schemas definition file

Functions§

parse_schemas
Parse a schema definition and return a terse description