Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- run: cargo clippy --all-targets --all-features -- -D warnings
# Default features only: optional hook-* features need upstream APIs that are not on main yet.
- run: cargo clippy --all-targets -- -D warnings

test:
name: Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo test --all-features
- run: cargo test
- run: cargo test --test slt_default
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/target
Cargo.lock
.cargo/
31 changes: 24 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,35 @@ repository = "https://github.com/alexskinner/KiteSQL-MySQL"
keywords = ["sql", "mysql", "database"]
categories = ["development-tools", "database"]

[features]
# Default builds and tests target KipData/KiteSQL main with only the hooks that
# upstream already exposes (SqlDialect::parse, comparison_type, boolean_text,
# begin_commits_active_transaction, DataTypeMapper, SqlParser::with_set_autocommit,
# prefix indexes). Optional hook-* features keep MySQL behaviour that still needs
# upstream APIs; enabling them against current main will not compile until those
# hooks land (see README "Upstream status").
default = []
hook-functions = []
hook-collation = []
hook-nulls-first = []
hook-numeric-typing = []
hook-column-display = []
hook-identity = []
hook-diagnostics = []
hook-upsert = []

[dependencies]
# Pinned to cursor/dual-mode-tests-0fca branch which contains the dialect hooks
# and test infrastructure this crate depends on.
kite_sql = { git = "https://github.com/alexskinner/KiteSQL", rev = "806503632a84aecd15bbc5d31723b125671ee224", default-features = false, features = ["parser", "decimal"] }
sqlparser = { version = "0.61", features = ["visitor"] }
# Pinned to KipData/KiteSQL main (pluggable SqlDialect / DynDialect, dialect-owned
# parsing, comparison coercion, session autocommit, prefix indexes).
kite_sql = { git = "https://github.com/KipData/KiteSQL", rev = "2a57f09d279e44c2d510d7aa72b7e24c1efe893b", default-features = false, features = ["parser", "decimal"] }
sqlparser = { version = "0.61", default-features = false, features = ["std", "visitor"] }
ordered-float = "4.6"
uuid = { version = "1.10", features = ["v4"] }
rust_decimal = { version = "1", default-features = false, features = ["std"] }
icu_normalizer = { version = "2.4", default-features = false, features = ["compiled_data"] }

[dev-dependencies]
# Pinned to cursor/dual-mode-tests-0fca branch which contains the dialect hooks
# and test infrastructure this crate depends on.
kite_sql = { git = "https://github.com/alexskinner/KiteSQL", rev = "806503632a84aecd15bbc5d31723b125671ee224", default-features = false, features = ["time", "macros", "parser", "lmdb", "spill", "decimal", "orm", "copy"] }
kite_sql = { git = "https://github.com/KipData/KiteSQL", rev = "2a57f09d279e44c2d510d7aa72b7e24c1efe893b", default-features = false, features = ["time", "macros", "parser", "lmdb", "spill", "decimal", "orm", "copy"] }
tempfile = "3.10"
sqllogictest = "0.29.1"
glob = "0.3"
88 changes: 48 additions & 40 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,40 @@ MySQL dialect support for [KiteSQL](https://github.com/KipData/KiteSQL)[^tradema

## Overview

This crate provides MySQL-specific functionality for KiteSQL through its dialect registration hooks. It enables KiteSQL to parse and execute MySQL-specific SQL syntax, type mappings, functions, and collation rules.
This crate provides MySQL-specific functionality for KiteSQL through its pluggable [`SqlDialect`](https://github.com/KipData/KiteSQL) API. It enables KiteSQL to parse and execute MySQL-specific SQL syntax, type mappings, and (where upstream hooks allow) functions and collation rules.

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
kite_sql = { git = "https://github.com/alexskinner/KiteSQL", rev = "806503632a84aecd15bbc5d31723b125671ee224" }
kite_sql = { git = "https://github.com/KipData/KiteSQL", rev = "2a57f09d279e44c2d510d7aa72b7e24c1efe893b" }
kite_sql_mysql = { git = "https://github.com/alexskinner/KiteSQL-MySQL" }
```

## Usage

Use the `with_mysql()` extension method to register the MySQL dialect with your database:
Use `with_mysql()` to set the dialect, then `install_mysql_functions` to register MySQL scalar functions through `Database::load`:

```rust
use kite_sql::db::DataBaseBuilder;
use kite_sql_mysql::MySqlBuilderExt;
use kite_sql_mysql::{install_mysql_functions, MySqlBuilderExt};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut database = DataBaseBuilder::path(".")
.with_mysql()?
.with_mysql()
.build_in_memory()?;
install_mysql_functions(&mut database)?;

// Now you can use MySQL-specific types and syntax
database.ddl("CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
id INT PRIMARY KEY,
name VARCHAR(100),
bio MEDIUMTEXT
)")?;

database.run("INSERT INTO users (name, bio) VALUES ('Alice', 'Software developer')")?
database.run("INSERT INTO users (id, name, bio) VALUES (1, 'Alice', 'Software developer')")?
.done()?;

let mut result = database.run("SELECT * FROM users WHERE id = 1")?;
Expand All @@ -51,26 +52,50 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
```

## Upstream status

Pinned to [KipData/KiteSQL](https://github.com/KipData/KiteSQL) `main` (`2a57f09`). The **default** feature set uses only hooks that already exist upstream and is what CI builds and tests.

| Cargo feature | MySQL behaviour | Upstream hook / issue |
| --- | --- | --- |
| *(default)* | `SqlDialect::parse` with sqlparser MySQL + rewrite, `DataTypeMapper`, `comparison_type`, `boolean_text`, `begin_commits_active_transaction`, `SqlParser::with_set_autocommit`, prefix indexes, fixed-arity scalar functions via `Database::load` | [#404](https://github.com/KipData/KiteSQL/pull/404), [#406](https://github.com/KipData/KiteSQL/pull/406), [#407](https://github.com/KipData/KiteSQL/pull/407), [#409](https://github.com/KipData/KiteSQL/pull/409), [#410](https://github.com/KipData/KiteSQL/pull/410) |
| `hook-functions` | Variadic / `accepts_any_args` functions (`GREATEST`/`LEAST`, open-ended `CONCAT`, …) and richer binder lookup | Implicit-cast function lookup + `ScalarFunctionImpl::{accepts_arity,accepts_any_args,return_type_for}` ([#412](https://github.com/KipData/KiteSQL/issues/412)); FunctionRegistry/packs |
| `hook-collation` | `utf8mb4_0900_ai_ci` text comparison keys | Dialect collation hooks (`text_collation` / binary-collation detection) |
| `hook-nulls-first` | NULLs first ascending / last descending | Dialect `nulls_first` hook |
| `hook-numeric-typing` | Exact DECIMAL literals, `/` and `AVG` scale rules, arithmetic result types | Dialect `number_literal` / `arithmetic_return_type` / `avg_return_type` hooks |
| `hook-column-display` | Preserve MySQL display types (`tinytext`, `bit(1)`, `serial`, …) in catalogs | `ColumnTypeSpec` / display-type mapping beyond `LogicalType` |
| `hook-identity` | `AUTO_INCREMENT` / `SERIAL` identity, `LAST_INSERT_ID()`, zero-generates | Identity / `identity_zero_generates` hooks |
| `hook-diagnostics` | MySQL warning/error codes (e.g. 1365) and statement policies | Diagnostics / `map_diagnostic` / `StatementPolicy` hooks |
| `hook-upsert` | `ON DUPLICATE KEY UPDATE` and MySQL affected-row counts | Upsert dialect hooks (upstream [#408](https://github.com/KipData/KiteSQL/pull/408) not merged) |

Optional `hook-*` features keep the MySQL-side code paths ready; enabling them against current upstream `main` will not compile until the corresponding hooks land. UDAFs and statement undo-log support are likewise waiting on upstream extension points and are not exposed yet.

## Features

### MySQL Type Mappings
### MySQL Type Mappings (default)

- **Text Types**: `TINYTEXT`, `MEDIUMTEXT`, `LONGTEXT` → `VARCHAR` without length limit
- **Bit Types**:
- `BIT(1)` → `BOOLEAN`
- `BIT(n)` (n > 1) → `UBIGINT`
- **Serial Type**: `SERIAL` → `UBIGINT NOT NULL AUTO_INCREMENT UNIQUE`
- **Integer Display Width**: `TINYINT(1)` and other display widths work as expected
- **Serial Type**: `SERIAL` → `UBIGINT` (identity/`AUTO_INCREMENT` behaviour needs `hook-identity`)
- **Integer Display Width**: `TINYINT(1)` and other display widths parse as expected

### Comparison coercion and boolean text (default)

### AUTO_INCREMENT and LAST_INSERT_ID()
- Boolean vs text/number and temporal vs number comparison casts via `SqlDialect::comparison_type`
- `CAST(true AS VARCHAR)` renders as `1` / `0` via `boolean_text`
- `BEGIN` commits an open session transaction (`begin_commits_active_transaction`); `SET autocommit` is accepted through `SqlParser::with_set_autocommit`

Identity columns with `AUTO_INCREMENT` are supported, including:
### AUTO_INCREMENT and LAST_INSERT_ID() (`hook-identity`)

Identity columns with `AUTO_INCREMENT` are supported when the identity hook is available, including:
- The `AUTO_INCREMENT = n` table option
- Explicit 0 values generate new IDs like NULL
- `LAST_INSERT_ID()` returns the last generated ID
- `LAST_INSERT_ID(expr)` sets and returns a value

### Exact-Value Arithmetic (MySQL 8 Compatibility)
### Exact-Value Arithmetic (`hook-numeric-typing`)

- **Exact Decimal Literals**: Numbers with a decimal point and no exponent (`0.1`, `.5`, `2.50`) are treated as exact `DECIMAL` values, so `0.1 + 0.2 = 0.3` exactly
- **Division**: `/` on exact values produces `DECIMAL` with scale = dividend scale + 4, so `7 / 2 = 3.5000` and `1.0 / 3 = 0.33333`
Expand All @@ -79,64 +104,47 @@ Identity columns with `AUTO_INCREMENT` are supported, including:
- `+`, `-`, `%` keep the larger scale
- `%` and `MOD()` take the dividend's sign
- **Integer Division**: `DIV` performs integer division, truncating toward zero, with the precedence of `*` and `/`
- **Division by Zero**: Returns `NULL` with warning code 1365
- **Division by Zero**: Returns `NULL` with warning code 1365 (needs `hook-diagnostics`)
- **Precision Limits**: Values hold up to 28 significant digits

### MySQL Collation (utf8mb4_0900_ai_ci)
### MySQL Collation (`hook-collation`)

Text comparison follows MySQL 8's default collation: case- and accent-insensitive, NO PAD:
- `'Smith' = 'SMITH'`, `'é' = 'e'`, `'ß' = 'ss'`
- `'a' <> 'a '` (trailing spaces matter)

Applies to: `=`, `<>`, `<`, `>`, `IN`, `BETWEEN`, `CASE`, `NULLIF`, `STRCMP`, `FIELD`, `FIND_IN_SET`, `ORDER BY`, `GROUP BY`, `DISTINCT`, `UNION`, joins, `MIN`/`MAX`, and to primary and unique keys.

**Byte-wise comparison** can be forced with:
- `BINARY x`, `CAST(x AS BINARY)`
- `COLLATE …_bin`, `…_cs`, or `binary`
- Columns declared with these collations

**LIKE** is case-insensitive by default unless an operand is marked binary, and supports:
**LIKE** is rewritten case-insensitively by default unless an operand is marked binary, and supports:
- `ESCAPE` clause for custom escape characters
- Standard `%` and `_` wildcards

### MySQL Functions

Includes MySQL-specific implementations of:
- String functions: `REPLACE`, `CONCAT`, `SUBSTRING`, `LENGTH`, and others
- Aggregate functions: `GROUP_CONCAT` with `ORDER BY` and `SEPARATOR` support
- Conditional functions: `ISNULL()`, `IFNULL()`, `IF()`
- Comparison functions: `GREATEST`, `LEAST` with MySQL type compatibility
Default build registers fixed-arity implementations through `Database::load` (for example `REPLACE`, `CONCAT` with 1..=8 arguments, `ROUND`, `UUID`, `ISNULL` over common types). Variadic/`accepts_any_args` forms and reliable use on length-bounded column types wait on `hook-functions` / [#412](https://github.com/KipData/KiteSQL/issues/412).

### NULL Ordering
### NULL Ordering (`hook-nulls-first`)

Results order NULLs as MySQL does: NULLs first when ascending, NULLs last when descending.

### Warning Codes
### Warning Codes (`hook-diagnostics`)

Division by zero and numeric truncation generate MySQL-compatible warning codes (1365).

### Type System Compatibility

Proper type comparison rules for:
- Boolean values
- Signed vs unsigned integers
- Temporal types
- Decimal precision and scale

## Limitations

Not yet modeled:
Not yet modeled, or gated on upstream hooks:
- Full Unicode Collation Algorithm for punctuation/symbol ordering
- Some collation edge cases in `GROUP BY`, `DISTINCT`, `UNION` on `_bin`/`_cs` columns
- Accent folding in `LIKE`
- Per-column collation metadata beyond "byte-wise or not"
- Error 1267 (illegal mix of collations) outside `LIKE`
- `ON DUPLICATE KEY UPDATE` (`hook-upsert`)
- User-defined aggregates and statement undo log

## See Also

- [KiteSQL](https://github.com/KipData/KiteSQL)
- [KiteSQL API documentation](https://docs.rs/kite_sql)
- [SQL dialects in KiteSQL, including writing custom dialects](https://github.com/alexskinner/KiteSQL/blob/main/docs/features.md#sql-dialects)
- [SQL dialects in KiteSQL](https://github.com/KipData/KiteSQL/blob/main/docs/features.md)

## Trademark Notice

Expand Down
18 changes: 16 additions & 2 deletions src/auto_increment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,30 @@
//! `GENERATED BY DEFAULT AS IDENTITY`; the table option `AUTO_INCREMENT = n` becomes the
//! identity's `START WITH n`. `LAST_INSERT_ID()` reads the value the core records for the
//! last insert on this thread.
//!
//! Wired from the dialect under `hook-identity`; helpers stay compiled for unit tests.

#![allow(dead_code)]

use kite_sql::errors::DatabaseError;
#[cfg(feature = "hook-identity")]
use kite_sql::expression::function::scala::{FuncMonotonicity, ScalarFunctionImpl};
use kite_sql::expression::function::{FunctionSummary, PersistencePolicy};
#[cfg(feature = "hook-identity")]
use kite_sql::expression::function::FunctionSummary;
#[cfg(feature = "hook-identity")]
use kite_sql::planner::{ExprRef, MetaArena};
#[cfg(feature = "hook-identity")]
use kite_sql::types::tuple::Input;
#[cfg(feature = "hook-identity")]
use kite_sql::types::value::DataValue;
#[cfg(feature = "hook-identity")]
use kite_sql::types::LogicalType;
use sqlparser::ast::{
ColumnDef, ColumnOption, ColumnOptionDef, CreateTable, CreateTableOptions, DataType, Expr,
GeneratedAs, KeyOrIndexDisplay, NullsDistinctOption, ObjectNamePart, SequenceOptions,
SqlOption, TableConstraint, UniqueConstraint, Value,
};
#[cfg(feature = "hook-identity")]
use std::sync::Arc;

/// MySQL error 1075.
Expand Down Expand Up @@ -207,11 +218,13 @@ pub(crate) fn rewrite_create_table(create: &mut CreateTable) -> Result<(), Datab
/// `LAST_INSERT_ID()`: the first value generated by the last INSERT on this connection that
/// generated any (0 if none), or the value last set with `LAST_INSERT_ID(expr)`.
/// `LAST_INSERT_ID(expr)` returns `expr` and makes it the value; NULL returns NULL and sets 0.
#[cfg(feature = "hook-identity")]
#[derive(Debug)]
pub struct LastInsertId {
summary: FunctionSummary,
}

#[cfg(feature = "hook-identity")]
impl LastInsertId {
pub fn new(with_arg: bool) -> Arc<Self> {
Arc::new(Self {
Expand All @@ -222,17 +235,18 @@ impl LastInsertId {
} else {
vec![]
},
persistence: PersistencePolicy::Transient,
},
})
}
}

/// MySQL reports the value as BIGINT UNSIGNED: negative values wrap around.
#[cfg(feature = "hook-identity")]
fn unsigned(value: i128) -> DataValue {
DataValue::UInt64(value as u64)
}

#[cfg(feature = "hook-identity")]
impl ScalarFunctionImpl for LastInsertId {
fn eval(
&self,
Expand Down
2 changes: 2 additions & 0 deletions src/collation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@
//! punctuation and symbols keep their code point order rather than the UCA's (where all
//! punctuation sorts before digits), and there are no contractions or per-language rules.

#[cfg(feature = "hook-collation")]
use kite_sql::types::collation::TextCollation;
use std::borrow::Cow;

/// The name tables created under this collation are marked with.
pub const UTF8MB4_0900_AI_CI: &str = "utf8mb4_0900_ai_ci";

#[cfg(feature = "hook-collation")]
pub fn utf8mb4_0900_ai_ci() -> TextCollation {
TextCollation::new(UTF8MB4_0900_AI_CI, key)
}
Expand Down
Loading
Loading