Added #![forbid(missing_docs)] and documented all methods and attributes

This commit is contained in:
Luca 2025-12-18 20:52:09 +01:00
parent 3037ddf663
commit b819480a55
23 changed files with 2652 additions and 302 deletions

View file

@ -174,7 +174,16 @@ pub enum Comment {
/// until end-of-line or end-of-file in the source code.
///
/// Note: `content` will include the terminating new-line character, if any.
SingleLine { content: String, prefix: String },
/// A single-line comment, typically introduced with a prefix and spanning
/// until end-of-line or end-of-file in the source code.
///
/// Note: `content` will include the terminating new-line character, if any.
SingleLine {
/// The content of the comment (including trailing newline, if any).
content: String,
/// The prefix introducing the comment (e.g. `--`, `#`).
prefix: String,
},
/// A multi-line comment, typically enclosed in `/* .. */` markers. The
/// string represents the content excluding the markers.

View file

@ -32,7 +32,9 @@ use super::{value::escape_single_quote_string, ColumnDef};
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// A member of an ENUM type.
pub enum EnumMember {
/// Just a name.
Name(String),
/// ClickHouse allows to specify an integer value for each enum value.
///
@ -957,18 +959,31 @@ impl fmt::Display for TimezoneInfo {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum IntervalFields {
/// `YEAR` field
Year,
/// `MONTH` field
Month,
/// `DAY` field
Day,
/// `HOUR` field
Hour,
/// `MINUTE` field
Minute,
/// `SECOND` field
Second,
/// `YEAR TO MONTH` field
YearToMonth,
/// `DAY TO HOUR` field
DayToHour,
/// `DAY TO MINUTE` field
DayToMinute,
/// `DAY TO SECOND` field
DayToSecond,
/// `HOUR TO MINUTE` field
HourToMinute,
/// `HOUR TO SECOND` field
HourToSecond,
/// `MINUTE TO SECOND` field
MinuteToSecond,
}
@ -1000,11 +1015,11 @@ impl fmt::Display for IntervalFields {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum ExactNumberInfo {
/// No additional information, e.g. `DECIMAL`
/// No additional information, e.g. `DECIMAL`.
None,
/// Only precision information, e.g. `DECIMAL(10)`
/// Only precision information, e.g. `DECIMAL(10)`.
Precision(u64),
/// Precision and scale information, e.g. `DECIMAL(10,2)`
/// Precision and scale information, e.g. `DECIMAL(10,2)`.
PrecisionAndScale(u64, i64),
}
@ -1031,13 +1046,14 @@ impl fmt::Display for ExactNumberInfo {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum CharacterLength {
/// Integer length with optional unit (e.g. `CHAR(10)` or `VARCHAR(10 CHARACTERS)`).
IntegerLength {
/// Default (if VARYING) or maximum (if not VARYING) length
length: u64,
/// Optional unit. If not informed, the ANSI handles it as CHARACTERS implicitly
unit: Option<CharLengthUnits>,
},
/// VARCHAR(MAX) or NVARCHAR(MAX), used in T-SQL (Microsoft SQL Server)
/// VARCHAR(MAX) or NVARCHAR(MAX), used in T-SQL (Microsoft SQL Server).
Max,
}
@ -1087,12 +1103,16 @@ impl fmt::Display for CharLengthUnits {
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// Information about [binary length][1], including length and possibly unit.
///
/// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#binary-length
pub enum BinaryLength {
/// Integer length for binary types (e.g. `VARBINARY(100)`).
IntegerLength {
/// Default (if VARYING)
length: u64,
},
/// VARBINARY(MAX) used in T-SQL (Microsoft SQL Server)
/// VARBINARY(MAX) used in T-SQL (Microsoft SQL Server).
Max,
}
@ -1118,13 +1138,13 @@ impl fmt::Display for BinaryLength {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum ArrayElemTypeDef {
/// `ARRAY`
/// Use `ARRAY` style without an explicit element type.
None,
/// `ARRAY<INT>`
/// Angle-bracket style, e.g. `ARRAY<INT>`.
AngleBracket(Box<DataType>),
/// `INT[]` or `INT[2]`
/// Square-bracket style, e.g. `INT[]` or `INT[2]`.
SquareBracket(Box<DataType>, Option<u64>),
/// `Array(Int64)`
/// Parenthesis style, e.g. `Array(Int64)`.
Parenthesis(Box<DataType>),
}
@ -1136,12 +1156,19 @@ pub enum ArrayElemTypeDef {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum GeometricTypeKind {
/// Point geometry
Point,
/// Line geometry
Line,
/// Line segment geometry
LineSegment,
/// Box geometry
GeometricBox,
/// Path geometry
GeometricPath,
/// Polygon geometry
Polygon,
/// Circle geometry
Circle,
}

View file

@ -39,15 +39,25 @@ use crate::tokenizer::Span;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum RoleOption {
/// Enable or disable BYPASSRLS.
BypassRLS(bool),
/// Connection limit expression.
ConnectionLimit(Expr),
/// CREATEDB flag.
CreateDB(bool),
/// CREATEROLE flag.
CreateRole(bool),
/// INHERIT flag.
Inherit(bool),
/// LOGIN flag.
Login(bool),
/// Password value or NULL password.
Password(Password),
/// Replication privilege flag.
Replication(bool),
/// SUPERUSER flag.
SuperUser(bool),
/// `VALID UNTIL` expression.
ValidUntil(Expr),
}
@ -104,8 +114,11 @@ impl fmt::Display for RoleOption {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum SetConfigValue {
/// Use the default value.
Default,
/// Use the current value (`FROM CURRENT`).
FromCurrent,
/// Set to the provided expression value.
Value(Expr),
}
@ -116,7 +129,9 @@ pub enum SetConfigValue {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum ResetConfig {
/// Reset all configuration parameters.
ALL,
/// Reset the named configuration parameter.
ConfigName(ObjectName),
}
@ -127,28 +142,48 @@ pub enum ResetConfig {
pub enum AlterRoleOperation {
/// Generic
RenameRole {
/// Role name to rename.
role_name: Ident,
},
/// MS SQL Server
/// <https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-role-transact-sql>
AddMember {
/// Member name to add to the role.
member_name: Ident,
},
/// MS SQL Server
///
/// <https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-role-transact-sql>
DropMember {
/// Member name to remove from the role.
member_name: Ident,
},
/// PostgreSQL
/// <https://www.postgresql.org/docs/current/sql-alterrole.html>
WithOptions {
/// Role options to apply.
options: Vec<RoleOption>,
},
/// PostgreSQL
/// <https://www.postgresql.org/docs/current/sql-alterrole.html>
///
/// `SET configuration_parameter { TO | = } { value | DEFAULT }`
Set {
/// Configuration name to set.
config_name: ObjectName,
/// Value to assign to the configuration.
config_value: SetConfigValue,
/// Optional database scope for the setting.
in_database: Option<ObjectName>,
},
/// PostgreSQL
/// <https://www.postgresql.org/docs/current/sql-alterrole.html>
///
/// `RESET configuration_parameter` | `RESET ALL`
Reset {
/// Configuration to reset.
config_name: ResetConfig,
/// Optional database scope for the reset.
in_database: Option<ObjectName>,
},
}
@ -205,14 +240,22 @@ impl fmt::Display for AlterRoleOperation {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum Use {
Catalog(ObjectName), // e.g. `USE CATALOG foo.bar`
Schema(ObjectName), // e.g. `USE SCHEMA foo.bar`
Database(ObjectName), // e.g. `USE DATABASE foo.bar`
Warehouse(ObjectName), // e.g. `USE WAREHOUSE foo.bar`
Role(ObjectName), // e.g. `USE ROLE PUBLIC`
SecondaryRoles(SecondaryRoles), // e.g. `USE SECONDARY ROLES ALL`
Object(ObjectName), // e.g. `USE foo.bar`
Default, // e.g. `USE DEFAULT`
/// Switch to the given catalog (e.g. `USE CATALOG ...`).
Catalog(ObjectName),
/// Switch to the given schema (e.g. `USE SCHEMA ...`).
Schema(ObjectName),
/// Switch to the given database (e.g. `USE DATABASE ...`).
Database(ObjectName),
/// Switch to the given warehouse (e.g. `USE WAREHOUSE ...`).
Warehouse(ObjectName),
/// Switch to the given role (e.g. `USE ROLE ...`).
Role(ObjectName),
/// Use secondary roles specification (e.g. `USE SECONDARY ROLES ...`).
SecondaryRoles(SecondaryRoles),
/// Use the specified object (e.g. `USE foo.bar`).
Object(ObjectName),
/// Reset to default (e.g. `USE DEFAULT`).
Default,
}
impl fmt::Display for Use {
@ -239,8 +282,11 @@ impl fmt::Display for Use {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum SecondaryRoles {
/// Use all secondary roles.
All,
/// Use no secondary roles.
None,
/// Explicit list of secondary roles.
List(Vec<Ident>),
}
@ -260,25 +306,43 @@ impl fmt::Display for SecondaryRoles {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct CreateRole {
/// Role names to create.
pub names: Vec<ObjectName>,
/// Whether `IF NOT EXISTS` was specified.
pub if_not_exists: bool,
// Postgres
/// Whether `LOGIN` was specified.
pub login: Option<bool>,
/// Whether `INHERIT` was specified.
pub inherit: Option<bool>,
/// Whether `BYPASSRLS` was specified.
pub bypassrls: Option<bool>,
/// Optional password for the role.
pub password: Option<Password>,
/// Whether `SUPERUSER` was specified.
pub superuser: Option<bool>,
/// Whether `CREATEDB` was specified.
pub create_db: Option<bool>,
/// Whether `CREATEROLE` was specified.
pub create_role: Option<bool>,
/// Whether `REPLICATION` privilege was specified.
pub replication: Option<bool>,
/// Optional connection limit expression.
pub connection_limit: Option<Expr>,
/// Optional account validity expression.
pub valid_until: Option<Expr>,
/// Members of `IN ROLE` clause.
pub in_role: Vec<Ident>,
/// Members of `IN GROUP` clause.
pub in_group: Vec<Ident>,
/// Roles listed in `ROLE` clause.
pub role: Vec<Ident>,
/// Users listed in `USER` clause.
pub user: Vec<Ident>,
/// Admin users listed in `ADMIN` clause.
pub admin: Vec<Ident>,
// MSSQL
/// Optional authorization owner.
pub authorization_owner: Option<ObjectName>,
}

File diff suppressed because it is too large Load diff

View file

@ -68,6 +68,7 @@ pub struct Insert {
pub after_columns: Vec<Ident>,
/// whether the insert has the table keyword (Hive)
pub has_table_keyword: bool,
/// ON INSERT
pub on: Option<OnInsert>,
/// RETURNING
pub returning: Option<Vec<SelectItem>>,
@ -331,7 +332,7 @@ pub struct Merge {
pub on: Box<Expr>,
/// Specifies the actions to perform when values match or do not match.
pub clauses: Vec<MergeClause>,
// Specifies the output to save changes in MSSQL
/// Specifies the output to save changes in MSSQL
pub output: Option<OutputClause>,
}
@ -367,8 +368,11 @@ impl Display for Merge {
pub struct MergeClause {
/// The `WHEN` token that starts the sub-expression.
pub when_token: AttachedToken,
/// The type of `WHEN` clause.
pub clause_kind: MergeClauseKind,
/// An optional predicate to further restrict the clause.
pub predicate: Option<Expr>,
/// The action to perform when the clause is matched.
pub action: MergeAction,
}
@ -607,13 +611,20 @@ impl Display for MergeUpdateExpr {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum OutputClause {
/// `OUTPUT` clause
Output {
/// The `OUTPUT` token that starts the sub-expression.
output_token: AttachedToken,
/// The select items to output
select_items: Vec<SelectItem>,
/// Optional `INTO` table to direct the output
into_table: Option<SelectInto>,
},
/// `RETURNING` clause
Returning {
/// The `RETURNING` token that starts the sub-expression.
returning_token: AttachedToken,
/// The select items to return
select_items: Vec<SelectItem>,
},
}

View file

@ -34,24 +34,33 @@ use crate::ast::{display_comma_separated, display_separated, Value};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// A collection of key-value options.
pub struct KeyValueOptions {
/// The list of key-value options.
pub options: Vec<KeyValueOption>,
/// The delimiter used between options.
pub delimiter: KeyValueOptionsDelimiter,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// The delimiter used between key-value options.
pub enum KeyValueOptionsDelimiter {
/// Options are separated by spaces.
Space,
/// Options are separated by commas.
Comma,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// A single key-value option.
pub struct KeyValueOption {
/// The name of the option.
pub option_name: String,
/// The value of the option.
pub option_value: KeyValueOptionKind,
}
@ -63,9 +72,13 @@ pub struct KeyValueOption {
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// The kind of value for a key-value option.
pub enum KeyValueOptionKind {
/// A single value.
Single(Value),
/// Multiple values.
Multi(Vec<Value>),
/// A nested list of key-value options.
KeyValueOptions(Box<KeyValueOptions>),
}

View file

@ -14,8 +14,14 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/// Helper utilities for attached tokens used by AST helpers.
pub mod attached_token;
/// Utilities for parsing key/value style options in helper statements.
pub mod key_value_options;
/// Helpers for `CREATE DATABASE` statement construction/parsing.
pub mod stmt_create_database;
/// Helpers for `CREATE TABLE` statement construction/parsing.
pub mod stmt_create_table;
/// Helpers for data loading/unloading related statements (stages, PUT, COPY INTO).
pub mod stmt_data_loading;

View file

@ -55,29 +55,54 @@ use crate::parser::ParserError;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct CreateDatabaseBuilder {
/// The database name to create.
pub db_name: ObjectName,
/// Whether `IF NOT EXISTS` was specified.
pub if_not_exists: bool,
/// Optional storage location for the database.
pub location: Option<String>,
/// Optional managed storage location.
pub managed_location: Option<String>,
/// Whether `OR REPLACE` was specified.
pub or_replace: bool,
/// Whether the database is `TRANSIENT`.
pub transient: bool,
/// Optional `CLONE` source object name.
pub clone: Option<ObjectName>,
/// Optional data retention time in days.
pub data_retention_time_in_days: Option<u64>,
/// Optional max data extension time in days.
pub max_data_extension_time_in_days: Option<u64>,
/// Optional external volume identifier.
pub external_volume: Option<String>,
/// Optional catalog name.
pub catalog: Option<String>,
/// Whether to replace invalid characters.
pub replace_invalid_characters: Option<bool>,
/// Optional default DDL collation.
pub default_ddl_collation: Option<String>,
/// Optional storage serialization policy.
pub storage_serialization_policy: Option<StorageSerializationPolicy>,
/// Optional comment attached to the database.
pub comment: Option<String>,
/// Optional catalog sync configuration.
pub catalog_sync: Option<String>,
/// Optional catalog sync namespace mode.
pub catalog_sync_namespace_mode: Option<CatalogSyncNamespaceMode>,
/// Optional namespace flatten delimiter for catalog sync.
pub catalog_sync_namespace_flatten_delimiter: Option<String>,
/// Optional tags attached to the database.
pub with_tags: Option<Vec<Tag>>,
/// Optional contact entries associated with the database.
pub with_contacts: Option<Vec<ContactEntry>>,
}
impl CreateDatabaseBuilder {
/// Create a new `CreateDatabaseBuilder` with the given database name.
///
/// # Arguments
///
/// * `name` - The name of the database to be created.
pub fn new(name: ObjectName) -> Self {
Self {
db_name: name,
@ -103,41 +128,49 @@ impl CreateDatabaseBuilder {
}
}
/// Set the location for the database.
pub fn location(mut self, location: Option<String>) -> Self {
self.location = location;
self
}
/// Set the managed location for the database.
pub fn managed_location(mut self, managed_location: Option<String>) -> Self {
self.managed_location = managed_location;
self
}
/// Set whether this is an `OR REPLACE` operation.
pub fn or_replace(mut self, or_replace: bool) -> Self {
self.or_replace = or_replace;
self
}
/// Set whether this is a transient database.
pub fn transient(mut self, transient: bool) -> Self {
self.transient = transient;
self
}
/// Set whether to use `IF NOT EXISTS`.
pub fn if_not_exists(mut self, if_not_exists: bool) -> Self {
self.if_not_exists = if_not_exists;
self
}
/// Set the clone clause for the database.
pub fn clone_clause(mut self, clone: Option<ObjectName>) -> Self {
self.clone = clone;
self
}
/// Set the data retention time in days.
pub fn data_retention_time_in_days(mut self, data_retention_time_in_days: Option<u64>) -> Self {
self.data_retention_time_in_days = data_retention_time_in_days;
self
}
/// Set the maximum data extension time in days.
pub fn max_data_extension_time_in_days(
mut self,
max_data_extension_time_in_days: Option<u64>,
@ -146,26 +179,31 @@ impl CreateDatabaseBuilder {
self
}
/// Set the external volume for the database.
pub fn external_volume(mut self, external_volume: Option<String>) -> Self {
self.external_volume = external_volume;
self
}
/// Set the catalog for the database.
pub fn catalog(mut self, catalog: Option<String>) -> Self {
self.catalog = catalog;
self
}
/// Set whether to replace invalid characters.
pub fn replace_invalid_characters(mut self, replace_invalid_characters: Option<bool>) -> Self {
self.replace_invalid_characters = replace_invalid_characters;
self
}
/// Set the default DDL collation.
pub fn default_ddl_collation(mut self, default_ddl_collation: Option<String>) -> Self {
self.default_ddl_collation = default_ddl_collation;
self
}
/// Set the storage serialization policy.
pub fn storage_serialization_policy(
mut self,
storage_serialization_policy: Option<StorageSerializationPolicy>,
@ -174,16 +212,19 @@ impl CreateDatabaseBuilder {
self
}
/// Set the comment for the database.
pub fn comment(mut self, comment: Option<String>) -> Self {
self.comment = comment;
self
}
/// Set the catalog sync for the database.
pub fn catalog_sync(mut self, catalog_sync: Option<String>) -> Self {
self.catalog_sync = catalog_sync;
self
}
/// Set the catalog sync namespace mode for the database.
pub fn catalog_sync_namespace_mode(
mut self,
catalog_sync_namespace_mode: Option<CatalogSyncNamespaceMode>,
@ -192,6 +233,7 @@ impl CreateDatabaseBuilder {
self
}
/// Set the catalog sync namespace flatten delimiter for the database.
pub fn catalog_sync_namespace_flatten_delimiter(
mut self,
catalog_sync_namespace_flatten_delimiter: Option<String>,
@ -200,16 +242,19 @@ impl CreateDatabaseBuilder {
self
}
/// Set the tags for the database.
pub fn with_tags(mut self, with_tags: Option<Vec<Tag>>) -> Self {
self.with_tags = with_tags;
self
}
/// Set the contacts for the database.
pub fn with_contacts(mut self, with_contacts: Option<Vec<ContactEntry>>) -> Self {
self.with_contacts = with_contacts;
self
}
/// Build the `CREATE DATABASE` statement.
pub fn build(self) -> Statement {
Statement::CreateDatabase {
db_name: self.db_name,

View file

@ -64,60 +64,112 @@ use crate::parser::ParserError;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct CreateTableBuilder {
/// Whether the statement uses `OR REPLACE`.
pub or_replace: bool,
/// Whether the table is `TEMPORARY`.
pub temporary: bool,
/// Whether the table is `EXTERNAL`.
pub external: bool,
/// Optional `GLOBAL` flag for dialects that support it.
pub global: Option<bool>,
/// Whether `IF NOT EXISTS` was specified.
pub if_not_exists: bool,
/// Whether `TRANSIENT` was specified.
pub transient: bool,
/// Whether `VOLATILE` was specified.
pub volatile: bool,
/// Iceberg-specific table flag.
pub iceberg: bool,
/// Whether `DYNAMIC` table option is set.
pub dynamic: bool,
/// The table name.
pub name: ObjectName,
/// Column definitions for the table.
pub columns: Vec<ColumnDef>,
/// Table-level constraints.
pub constraints: Vec<TableConstraint>,
/// Hive distribution style.
pub hive_distribution: HiveDistributionStyle,
/// Optional Hive format settings.
pub hive_formats: Option<HiveFormat>,
/// Optional file format for storage.
pub file_format: Option<FileFormat>,
/// Optional storage location.
pub location: Option<String>,
/// Optional `AS SELECT` query for the table.
pub query: Option<Box<Query>>,
/// Whether `WITHOUT ROWID` is set.
pub without_rowid: bool,
/// Optional `LIKE` clause kind.
pub like: Option<CreateTableLikeKind>,
/// Optional `CLONE` source object name.
pub clone: Option<ObjectName>,
/// Optional table version.
pub version: Option<TableVersion>,
/// Optional table comment.
pub comment: Option<CommentDef>,
/// Optional `ON COMMIT` behavior.
pub on_commit: Option<OnCommit>,
/// Optional cluster identifier.
pub on_cluster: Option<Ident>,
/// Optional primary key expression.
pub primary_key: Option<Box<Expr>>,
/// Optional `ORDER BY` for clustering/sorting.
pub order_by: Option<OneOrManyWithParens<Expr>>,
/// Optional `PARTITION BY` expression.
pub partition_by: Option<Box<Expr>>,
/// Optional `CLUSTER BY` expressions.
pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
/// Optional `CLUSTERED BY` clause.
pub clustered_by: Option<ClusteredBy>,
/// Optional parent tables (`INHERITS`).
pub inherits: Option<Vec<ObjectName>>,
/// `STRICT` table flag.
pub strict: bool,
/// Whether to copy grants from the source.
pub copy_grants: bool,
/// Optional flag for schema evolution support.
pub enable_schema_evolution: Option<bool>,
/// Optional change tracking flag.
pub change_tracking: Option<bool>,
/// Optional data retention time in days.
pub data_retention_time_in_days: Option<u64>,
/// Optional max data extension time in days.
pub max_data_extension_time_in_days: Option<u64>,
/// Optional default DDL collation.
pub default_ddl_collation: Option<String>,
/// Optional aggregation policy object name.
pub with_aggregation_policy: Option<ObjectName>,
/// Optional row access policy applied to the table.
pub with_row_access_policy: Option<RowAccessPolicy>,
/// Optional tags/labels attached to the table metadata.
pub with_tags: Option<Vec<Tag>>,
/// Optional base location for staged data.
pub base_location: Option<String>,
/// Optional external volume identifier.
pub external_volume: Option<String>,
/// Optional catalog name.
pub catalog: Option<String>,
/// Optional catalog synchronization option.
pub catalog_sync: Option<String>,
/// Optional storage serialization policy.
pub storage_serialization_policy: Option<StorageSerializationPolicy>,
/// Parsed table options from the statement.
pub table_options: CreateTableOptions,
/// Optional target lag configuration.
pub target_lag: Option<String>,
/// Optional warehouse identifier.
pub warehouse: Option<Ident>,
/// Optional refresh mode for materialized tables.
pub refresh_mode: Option<RefreshModeKind>,
/// Optional initialization kind for the table.
pub initialize: Option<InitializeKind>,
/// Whether operations require a user identity.
pub require_user: bool,
}
impl CreateTableBuilder {
/// Create a new `CreateTableBuilder` for the given table name.
pub fn new(name: ObjectName) -> Self {
Self {
or_replace: false,
@ -173,175 +225,178 @@ impl CreateTableBuilder {
require_user: false,
}
}
/// Set `OR REPLACE` for the CREATE TABLE statement.
pub fn or_replace(mut self, or_replace: bool) -> Self {
self.or_replace = or_replace;
self
}
/// Mark the table as `TEMPORARY`.
pub fn temporary(mut self, temporary: bool) -> Self {
self.temporary = temporary;
self
}
/// Mark the table as `EXTERNAL`.
pub fn external(mut self, external: bool) -> Self {
self.external = external;
self
}
/// Set optional `GLOBAL` flag (dialect-specific).
pub fn global(mut self, global: Option<bool>) -> Self {
self.global = global;
self
}
/// Set `IF NOT EXISTS`.
pub fn if_not_exists(mut self, if_not_exists: bool) -> Self {
self.if_not_exists = if_not_exists;
self
}
/// Set `TRANSIENT` flag.
pub fn transient(mut self, transient: bool) -> Self {
self.transient = transient;
self
}
/// Set `VOLATILE` flag.
pub fn volatile(mut self, volatile: bool) -> Self {
self.volatile = volatile;
self
}
/// Enable Iceberg table semantics.
pub fn iceberg(mut self, iceberg: bool) -> Self {
self.iceberg = iceberg;
self
}
/// Set `DYNAMIC` table option.
pub fn dynamic(mut self, dynamic: bool) -> Self {
self.dynamic = dynamic;
self
}
/// Set the table column definitions.
pub fn columns(mut self, columns: Vec<ColumnDef>) -> Self {
self.columns = columns;
self
}
/// Set table-level constraints.
pub fn constraints(mut self, constraints: Vec<TableConstraint>) -> Self {
self.constraints = constraints;
self
}
/// Set Hive distribution style.
pub fn hive_distribution(mut self, hive_distribution: HiveDistributionStyle) -> Self {
self.hive_distribution = hive_distribution;
self
}
/// Set Hive-specific formats.
pub fn hive_formats(mut self, hive_formats: Option<HiveFormat>) -> Self {
self.hive_formats = hive_formats;
self
}
/// Set file format for the table (e.g., PARQUET).
pub fn file_format(mut self, file_format: Option<FileFormat>) -> Self {
self.file_format = file_format;
self
}
/// Set storage `location` for the table.
pub fn location(mut self, location: Option<String>) -> Self {
self.location = location;
self
}
/// Set an underlying `AS SELECT` query for the table.
pub fn query(mut self, query: Option<Box<Query>>) -> Self {
self.query = query;
self
}
/// Set `WITHOUT ROWID` option.
pub fn without_rowid(mut self, without_rowid: bool) -> Self {
self.without_rowid = without_rowid;
self
}
/// Set `LIKE` clause for the table.
pub fn like(mut self, like: Option<CreateTableLikeKind>) -> Self {
self.like = like;
self
}
// Different name to allow the object to be cloned
/// Set `CLONE` source object name.
pub fn clone_clause(mut self, clone: Option<ObjectName>) -> Self {
self.clone = clone;
self
}
/// Set table `VERSION`.
pub fn version(mut self, version: Option<TableVersion>) -> Self {
self.version = version;
self
}
/// Set a comment for the table or following column definitions.
pub fn comment_after_column_def(mut self, comment: Option<CommentDef>) -> Self {
self.comment = comment;
self
}
/// Set `ON COMMIT` behavior for temporary tables.
pub fn on_commit(mut self, on_commit: Option<OnCommit>) -> Self {
self.on_commit = on_commit;
self
}
/// Set cluster identifier for the table.
pub fn on_cluster(mut self, on_cluster: Option<Ident>) -> Self {
self.on_cluster = on_cluster;
self
}
/// Set a primary key expression for the table.
pub fn primary_key(mut self, primary_key: Option<Box<Expr>>) -> Self {
self.primary_key = primary_key;
self
}
/// Set `ORDER BY` clause for clustered/sorted tables.
pub fn order_by(mut self, order_by: Option<OneOrManyWithParens<Expr>>) -> Self {
self.order_by = order_by;
self
}
/// Set `PARTITION BY` expression.
pub fn partition_by(mut self, partition_by: Option<Box<Expr>>) -> Self {
self.partition_by = partition_by;
self
}
/// Set `CLUSTER BY` expression(s).
pub fn cluster_by(mut self, cluster_by: Option<WrappedCollection<Vec<Expr>>>) -> Self {
self.cluster_by = cluster_by;
self
}
/// Set `CLUSTERED BY` clause.
pub fn clustered_by(mut self, clustered_by: Option<ClusteredBy>) -> Self {
self.clustered_by = clustered_by;
self
}
/// Set parent tables via `INHERITS`.
pub fn inherits(mut self, inherits: Option<Vec<ObjectName>>) -> Self {
self.inherits = inherits;
self
}
/// Set `STRICT` option.
pub fn strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
}
/// Enable copying grants from source object.
pub fn copy_grants(mut self, copy_grants: bool) -> Self {
self.copy_grants = copy_grants;
self
}
/// Enable or disable schema evolution features.
pub fn enable_schema_evolution(mut self, enable_schema_evolution: Option<bool>) -> Self {
self.enable_schema_evolution = enable_schema_evolution;
self
}
/// Enable or disable change tracking.
pub fn change_tracking(mut self, change_tracking: Option<bool>) -> Self {
self.change_tracking = change_tracking;
self
}
/// Set data retention time (in days).
pub fn data_retention_time_in_days(mut self, data_retention_time_in_days: Option<u64>) -> Self {
self.data_retention_time_in_days = data_retention_time_in_days;
self
}
/// Set maximum data extension time (in days).
pub fn max_data_extension_time_in_days(
mut self,
max_data_extension_time_in_days: Option<u64>,
@ -349,17 +404,17 @@ impl CreateTableBuilder {
self.max_data_extension_time_in_days = max_data_extension_time_in_days;
self
}
/// Set default DDL collation.
pub fn default_ddl_collation(mut self, default_ddl_collation: Option<String>) -> Self {
self.default_ddl_collation = default_ddl_collation;
self
}
/// Set aggregation policy object.
pub fn with_aggregation_policy(mut self, with_aggregation_policy: Option<ObjectName>) -> Self {
self.with_aggregation_policy = with_aggregation_policy;
self
}
/// Attach a row access policy to the table.
pub fn with_row_access_policy(
mut self,
with_row_access_policy: Option<RowAccessPolicy>,
@ -367,32 +422,32 @@ impl CreateTableBuilder {
self.with_row_access_policy = with_row_access_policy;
self
}
/// Attach tags/labels to the table metadata.
pub fn with_tags(mut self, with_tags: Option<Vec<Tag>>) -> Self {
self.with_tags = with_tags;
self
}
/// Set a base storage location for staged data.
pub fn base_location(mut self, base_location: Option<String>) -> Self {
self.base_location = base_location;
self
}
/// Set an external volume identifier.
pub fn external_volume(mut self, external_volume: Option<String>) -> Self {
self.external_volume = external_volume;
self
}
/// Set the catalog name for the table.
pub fn catalog(mut self, catalog: Option<String>) -> Self {
self.catalog = catalog;
self
}
/// Set catalog synchronization option.
pub fn catalog_sync(mut self, catalog_sync: Option<String>) -> Self {
self.catalog_sync = catalog_sync;
self
}
/// Set a storage serialization policy.
pub fn storage_serialization_policy(
mut self,
storage_serialization_policy: Option<StorageSerializationPolicy>,
@ -400,37 +455,37 @@ impl CreateTableBuilder {
self.storage_serialization_policy = storage_serialization_policy;
self
}
/// Set arbitrary table options parsed from the statement.
pub fn table_options(mut self, table_options: CreateTableOptions) -> Self {
self.table_options = table_options;
self
}
/// Set a target lag configuration (dialect-specific).
pub fn target_lag(mut self, target_lag: Option<String>) -> Self {
self.target_lag = target_lag;
self
}
/// Associate the table with a warehouse identifier.
pub fn warehouse(mut self, warehouse: Option<Ident>) -> Self {
self.warehouse = warehouse;
self
}
/// Set refresh mode for materialized/managed tables.
pub fn refresh_mode(mut self, refresh_mode: Option<RefreshModeKind>) -> Self {
self.refresh_mode = refresh_mode;
self
}
/// Set initialization mode for the table.
pub fn initialize(mut self, initialize: Option<InitializeKind>) -> Self {
self.initialize = initialize;
self
}
/// Require a user identity for table operations.
pub fn require_user(mut self, require_user: bool) -> Self {
self.require_user = require_user;
self
}
/// Consume the builder and produce a `Statement::CreateTable`.
pub fn build(self) -> Statement {
CreateTable {
or_replace: self.or_replace,

View file

@ -34,11 +34,17 @@ use sqlparser_derive::{Visit, VisitMut};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// Parameters for a named stage object used in data loading/unloading.
pub struct StageParamsObject {
/// Optional URL for the stage.
pub url: Option<String>,
/// Encryption-related key/value options.
pub encryption: KeyValueOptions,
/// Optional endpoint string.
pub endpoint: Option<String>,
/// Optional storage integration identifier.
pub storage_integration: Option<String>,
/// Credentials for accessing the stage.
pub credentials: KeyValueOptions,
}
@ -48,7 +54,9 @@ pub struct StageParamsObject {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum StageLoadSelectItemKind {
/// A standard SQL select item expression.
SelectItem(SelectItem),
/// A Snowflake-specific select item used for stage loading.
StageLoadSelectItem(StageLoadSelectItem),
}
@ -64,10 +72,15 @@ impl fmt::Display for StageLoadSelectItemKind {
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// A single item in the `SELECT` list for data loading from staged files.
pub struct StageLoadSelectItem {
/// Optional alias for the input source.
pub alias: Option<Ident>,
/// Column number within the staged file (1-based).
pub file_col_num: i32,
/// Optional element identifier following the column reference.
pub element: Option<Ident>,
/// Optional alias for the item (AS clause).
pub item_as: Option<Ident>,
}
@ -116,9 +129,12 @@ impl fmt::Display for StageLoadSelectItem {
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// A command to stage files to a named stage.
pub struct FileStagingCommand {
/// The stage to which files are being staged.
#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
pub stage: ObjectName,
/// Optional file matching `PATTERN` expression.
pub pattern: Option<String>,
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -155,10 +155,13 @@ impl fmt::Display for TableConstraint {
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// A `CHECK` constraint (`[ CONSTRAINT <name> ] CHECK (<expr>) [[NOT] ENFORCED]`).
pub struct CheckConstraint {
/// Optional constraint name.
pub name: Option<Ident>,
/// The boolean expression the CHECK constraint enforces.
pub expr: Box<Expr>,
/// MySQL-specific syntax
/// MySQL-specific `ENFORCED` / `NOT ENFORCED` flag.
/// <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
pub enforced: Option<bool>,
}
@ -197,16 +200,24 @@ impl crate::ast::Spanned for CheckConstraint {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct ForeignKeyConstraint {
/// Optional constraint name.
pub name: Option<Ident>,
/// MySQL-specific field
/// MySQL-specific index name associated with the foreign key.
/// <https://dev.mysql.com/doc/refman/8.4/en/create-table-foreign-keys.html>
pub index_name: Option<Ident>,
/// Columns in the local table that participate in the foreign key.
pub columns: Vec<Ident>,
/// Referenced foreign table name.
pub foreign_table: ObjectName,
/// Columns in the referenced table.
pub referred_columns: Vec<Ident>,
/// Action to perform `ON DELETE`.
pub on_delete: Option<ReferentialAction>,
/// Action to perform `ON UPDATE`.
pub on_update: Option<ReferentialAction>,
/// Optional `MATCH` kind (FULL | PARTIAL | SIMPLE).
pub match_kind: Option<ConstraintReferenceMatchKind>,
/// Optional characteristics (e.g., `DEFERRABLE`).
pub characteristics: Option<ConstraintCharacteristics>,
}
@ -344,6 +355,7 @@ pub struct IndexConstraint {
/// Referred column identifier list.
pub columns: Vec<IndexColumn>,
/// Optional index options such as `USING`; see [`IndexOption`].
/// Options applied to the index (e.g., `COMMENT`, `WITH` options).
pub index_options: Vec<IndexOption>,
}
@ -413,7 +425,9 @@ pub struct PrimaryKeyConstraint {
pub index_type: Option<IndexType>,
/// Identifiers of the columns that form the primary key.
pub columns: Vec<IndexColumn>,
/// Optional index options such as `USING`.
pub index_options: Vec<IndexOption>,
/// Optional characteristics like `DEFERRABLE`.
pub characteristics: Option<ConstraintCharacteristics>,
}
@ -458,6 +472,7 @@ impl crate::ast::Spanned for PrimaryKeyConstraint {
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// Unique constraint definition.
pub struct UniqueConstraint {
/// Constraint name.
///
@ -473,7 +488,9 @@ pub struct UniqueConstraint {
pub index_type: Option<IndexType>,
/// Identifiers of the columns that are unique.
pub columns: Vec<IndexColumn>,
/// Optional index options such as `USING`.
pub index_options: Vec<IndexOption>,
/// Optional characteristics like `DEFERRABLE`.
pub characteristics: Option<ConstraintCharacteristics>,
/// Optional Postgres nulls handling: `[ NULLS [ NOT ] DISTINCT ]`
pub nulls_distinct: NullsDistinctOption,

View file

@ -23,7 +23,9 @@ use super::*;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum TriggerObject {
/// The trigger fires once for each row affected by the triggering event
Row,
/// The trigger fires once for the triggering SQL statement
Statement,
}
@ -36,12 +38,14 @@ impl fmt::Display for TriggerObject {
}
}
/// This clause indicates whether the following relation name is for the before-image transition relation or the after-image transition relation
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// This clause indicates whether the following relation name is for the before-image transition relation or the after-image transition relation
pub enum TriggerReferencingType {
/// The transition relation containing the old rows affected by the triggering statement
OldTable,
/// The transition relation containing the new rows affected by the triggering statement
NewTable,
}
@ -59,8 +63,11 @@ impl fmt::Display for TriggerReferencingType {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct TriggerReferencing {
/// The referencing type (`OLD TABLE` or `NEW TABLE`).
pub refer_type: TriggerReferencingType,
/// True if the `AS` keyword is present in the referencing clause.
pub is_as: bool,
/// The transition relation name provided by the referencing clause.
pub transition_relation_name: ObjectName,
}
@ -81,9 +88,13 @@ impl fmt::Display for TriggerReferencing {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum TriggerEvent {
/// Trigger on INSERT event
Insert,
/// Trigger on UPDATE event, with optional list of columns
Update(Vec<Ident>),
/// Trigger on DELETE event
Delete,
/// Trigger on TRUNCATE event
Truncate,
}
@ -110,9 +121,13 @@ impl fmt::Display for TriggerEvent {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum TriggerPeriod {
/// The trigger fires once for each row affected by the triggering event
For,
/// The trigger fires once for the triggering SQL statement
After,
/// The trigger fires before the triggering event
Before,
/// The trigger fires instead of the triggering event
InsteadOf,
}
@ -132,7 +147,9 @@ impl fmt::Display for TriggerPeriod {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum TriggerExecBodyType {
/// Execute a function
Function,
/// Execute a procedure
Procedure,
}
@ -149,7 +166,9 @@ impl fmt::Display for TriggerExecBodyType {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct TriggerExecBody {
/// Whether the body is a `FUNCTION` or `PROCEDURE` invocation.
pub exec_type: TriggerExecBodyType,
/// Description of the function/procedure to execute.
pub func_desc: FunctionDesc,
}

View file

@ -64,11 +64,14 @@ use sqlparser_derive::{Visit, VisitMut};
/// // convert back to `Value`
/// let value: Value = value_with_span.into();
/// ```
/// A `Value` paired with its source `Span` location.
#[derive(Debug, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct ValueWithSpan {
/// The wrapped `Value`.
pub value: Value,
/// The source `Span` covering the token(s) that produced the value.
pub span: Span,
}
@ -127,7 +130,7 @@ pub enum Value {
Number(BigDecimal, bool),
/// 'string value'
SingleQuotedString(String),
// $<tag_name>$string value$<tag_name>$ (postgres syntax)
/// Dollar-quoted string literal, e.g. `$$...$$` or `$tag$...$tag$` (Postgres syntax).
DollarQuotedString(DollarQuotedString),
/// Triple single quoted strings: Example '''abc'''
/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_literals)
@ -176,6 +179,7 @@ pub enum Value {
/// X'hex value'
HexStringLiteral(String),
/// Double quoted string literal, e.g. `"abc"`.
DoubleQuotedString(String),
/// Boolean value true or false
Boolean(bool),
@ -219,10 +223,12 @@ impl Value {
}
}
/// Attach the provided `span` to this `Value` and return `ValueWithSpan`.
pub fn with_span(self, span: Span) -> ValueWithSpan {
ValueWithSpan { value: self, span }
}
/// Convenience for attaching an empty span to this `Value`.
pub fn with_empty_span(self) -> ValueWithSpan {
self.with_span(Span::empty())
}
@ -268,11 +274,14 @@ impl fmt::Display for Value {
}
}
/// A dollar-quoted string literal, e.g. `$$...$$` or `$tag$...$tag$`.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct DollarQuotedString {
/// Inner string contents.
pub value: String,
/// Optional tag used in the opening/closing delimiter.
pub tag: Option<String>,
}
@ -311,59 +320,102 @@ impl fmt::Display for QuoteDelimitedString {
}
}
/// Represents the date/time fields used by functions like `EXTRACT`.
///
/// Each variant corresponds to a supported date/time part (for example
/// `YEAR`, `MONTH`, `DAY`, etc.). The `Custom` variant allows arbitrary
/// identifiers (e.g. dialect-specific abbreviations).
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum DateTimeField {
/// `YEAR`
Year,
/// `YEARS` (plural form)
Years,
/// `MONTH`
Month,
/// `MONTHS` (plural form)
Months,
/// Week optionally followed by a WEEKDAY.
///
/// ```sql
/// WEEK(MONDAY)
/// ```
/// `WEEK`, optionally followed by a weekday, e.g. `WEEK(MONDAY)`.
///
/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#extract)
Week(Option<Ident>),
/// `WEEKS` (plural form)
Weeks,
/// `DAY`
Day,
/// `DAYOFWEEK`
DayOfWeek,
/// `DAYOFYEAR`
DayOfYear,
/// `DAYS` (plural form)
Days,
/// `DATE`
Date,
/// `DATETIME`
Datetime,
/// `HOUR`
Hour,
/// `HOURS` (plural form)
Hours,
/// `MINUTE`
Minute,
/// `MINUTES` (plural form)
Minutes,
/// `SECOND`
Second,
/// `SECONDS` (plural form)
Seconds,
/// `CENTURY`
Century,
/// `DECADE`
Decade,
/// `DOW` (day of week short form)
Dow,
/// `DOY` (day of year short form)
Doy,
/// `EPOCH`
Epoch,
/// `ISODOW`
Isodow,
IsoWeek,
/// `ISOYEAR`
Isoyear,
/// `ISOWEEK`
IsoWeek,
/// `JULIAN`
Julian,
/// `MICROSECOND`
Microsecond,
/// `MICROSECONDS` (plural form)
Microseconds,
/// `MILLENIUM` (alternate spelling)
Millenium,
/// `MILLENNIUM` (alternate spelling)
Millennium,
/// `MILLISECOND`
Millisecond,
/// `MILLISECONDS` (plural form)
Milliseconds,
/// `NANOSECOND`
Nanosecond,
/// `NANOSECONDS` (plural form)
Nanoseconds,
/// `QUARTER`
Quarter,
/// `TIME`
Time,
/// `TIMEZONE`
Timezone,
/// `TIMEZONE_ABBR`
TimezoneAbbr,
/// `TIMEZONE_HOUR`
TimezoneHour,
/// `TIMEZONE_MINUTE`
TimezoneMinute,
/// `TIMEZONE_REGION`
TimezoneRegion,
/// `NODATETIME` indicates no date/time part
NoDateTime,
/// Arbitrary abbreviation or custom date-time part.
///
@ -523,14 +575,18 @@ impl fmt::Display for EscapeQuotedString<'_> {
}
}
/// Return a helper which formats `string` for inclusion inside a quoted
/// literal that uses `quote` as the delimiter.
pub fn escape_quoted_string(string: &str, quote: char) -> EscapeQuotedString<'_> {
EscapeQuotedString { string, quote }
}
/// Convenience wrapper for escaping strings for single-quoted literals (`'`).
pub fn escape_single_quote_string(s: &str) -> EscapeQuotedString<'_> {
escape_quoted_string(s, '\'')
}
/// Convenience wrapper for escaping strings for double-quoted literals (`").`
pub fn escape_double_quote_string(s: &str) -> EscapeQuotedString<'_> {
escape_quoted_string(s, '\"')
}
@ -565,6 +621,8 @@ impl fmt::Display for EscapeEscapedStringLiteral<'_> {
}
}
/// Return a helper which escapes characters for string literals that use
/// PostgreSQL-style escaped string literals (e.g. `E'...')`.
pub fn escape_escaped_string(s: &str) -> EscapeEscapedStringLiteral<'_> {
EscapeEscapedStringLiteral(s)
}
@ -600,16 +658,24 @@ impl fmt::Display for EscapeUnicodeStringLiteral<'_> {
}
}
/// Return a helper which escapes non-ASCII characters using `\XXXX` or
/// `\+XXXXXX` Unicode escape formats (used for `U&'...'` style literals).
pub fn escape_unicode_string(s: &str) -> EscapeUnicodeStringLiteral<'_> {
EscapeUnicodeStringLiteral(s)
}
/// The side on which `TRIM` should be applied.
///
/// Corresponds to `TRIM(BOTH|LEADING|TRAILING)` SQL syntax.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum TrimWhereField {
/// `BOTH` (trim from both ends)
Both,
/// `LEADING` (trim from start)
Leading,
/// `TRAILING` (trim from end)
Trailing,
}

View file

@ -17,7 +17,7 @@
use crate::dialect::Dialect;
// A [`Dialect`] for [ClickHouse](https://clickhouse.com/).
/// A [`Dialect`] for [ClickHouse](https://clickhouse.com/).
#[derive(Debug)]
pub struct ClickHouseDialect {}

View file

@ -881,10 +881,14 @@ pub trait Dialect: Debug + Any {
false
}
/// Returns true if the dialect supports `EXPLAIN` statements with utility options
/// e.g. `EXPLAIN (ANALYZE TRUE, BUFFERS TRUE) SELECT * FROM tbl;`
fn supports_explain_with_utility_options(&self) -> bool {
false
}
/// Returns true if the dialect supports `ASC` and `DESC` in column definitions
/// e.g. `CREATE TABLE t (a INT ASC, b INT DESC);`
fn supports_asc_desc_in_column_definition(&self) -> bool {
false
}
@ -1113,6 +1117,13 @@ pub trait Dialect: Debug + Any {
false
}
/// Returns true if the dialect supports space-separated column options
/// in a `CREATE TABLE` statement. For example:
/// ```sql
/// CREATE TABLE tbl (
/// col INT NOT NULL DEFAULT 0
/// );
/// ```
fn supports_space_separated_column_options(&self) -> bool {
false
}
@ -1218,31 +1229,50 @@ pub trait Dialect: Debug + Any {
}
}
/// This represents the operators for which precedence must be defined
/// Operators for which precedence must be defined.
///
/// higher number -> higher precedence
/// Higher number -> higher precedence.
/// See expression parsing for how these values are used.
#[derive(Debug, Clone, Copy)]
pub enum Precedence {
/// Member access operator `.` (highest precedence).
Period,
/// Postgres style type cast `::`.
DoubleColon,
/// Timezone operator (e.g. `AT TIME ZONE`).
AtTz,
/// Multiplication / Division / Modulo operators (`*`, `/`, `%`).
MulDivModOp,
/// Addition / Subtraction (`+`, `-`).
PlusMinus,
/// Bitwise `XOR` operator (`^`).
Xor,
/// Bitwise `AND` operator (`&`).
Ampersand,
/// Bitwise `CARET` (^) for some dialects.
Caret,
/// Bitwise `OR` / pipe operator (`|`).
Pipe,
/// `BETWEEN` operator.
Between,
/// Equality operator (`=`).
Eq,
/// Pattern matching (`LIKE`).
Like,
/// `IS` operator (e.g. `IS NULL`).
Is,
/// Other Postgres-specific operators.
PgOther,
/// Unary `NOT`.
UnaryNot,
/// Logical `AND`.
And,
/// Logical `OR` (lowest precedence).
Or,
}
impl dyn Dialect {
/// Returns true if `self` is the concrete dialect `T`.
#[inline]
pub fn is<T: Dialect>(&self) -> bool {
// borrowed from `Any` implementation

View file

@ -37,6 +37,7 @@ use sqlparser_derive::{Visit, VisitMut};
/// expands to `pub const SELECT = "SELECT";`
macro_rules! kw_def {
($ident:ident = $string_keyword:expr) => {
#[doc = concat!("The `", $string_keyword, "` SQL keyword.")]
pub const $ident: &'static str = $string_keyword;
};
($ident:ident) => {
@ -54,16 +55,23 @@ macro_rules! define_keywords {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
#[allow(non_camel_case_types)]
/// An enumeration of SQL keywords recognized by the parser.
pub enum Keyword {
/// Represents no keyword.
NoKeyword,
$($ident),*
$(
#[doc = concat!("The `", stringify!($ident), "` SQL keyword.")]
$ident
),*
}
/// Array of all `Keyword` enum values in declaration order.
pub const ALL_KEYWORDS_INDEX: &[Keyword] = &[
$(Keyword::$ident),*
];
$(kw_def!($ident $(= $string_keyword)?);)*
/// Array of all SQL keywords as string constants.
pub const ALL_KEYWORDS: &[&str] = &[
$($ident),*
];
@ -1247,9 +1255,9 @@ pub const RESERVED_FOR_COLUMN_ALIAS: &[Keyword] = &[
Keyword::END,
];
// Global list of reserved keywords allowed after FROM.
// Parser should call Dialect::get_reserved_keyword_after_from
// to allow for each dialect to customize the list.
/// Global list of reserved keywords allowed after FROM.
/// Parser should call Dialect::get_reserved_keyword_after_from
/// to allow for each dialect to customize the list.
pub const RESERVED_FOR_TABLE_FACTOR: &[Keyword] = &[
Keyword::INTO,
Keyword::LIMIT,

View file

@ -154,6 +154,7 @@
// would bloat the API and hide intent. Extra memory is a worthwhile tradeoff.
#![allow(clippy::large_enum_variant)]
#![forbid(clippy::unreachable)]
#![forbid(missing_docs)]
// Allow proc-macros to find this crate
extern crate self as sqlparser;
@ -167,6 +168,7 @@ extern crate pretty_assertions;
pub mod ast;
#[macro_use]
/// Submodules for SQL dialects.
pub mod dialect;
mod display_utils;
pub mod keywords;

View file

@ -30,6 +30,7 @@ use crate::{
};
impl Parser<'_> {
/// Parse `ALTER ROLE` statement
pub fn parse_alter_role(&mut self) -> Result<Statement, ParserError> {
if dialect_of!(self is PostgreSqlDialect) {
return self.parse_pg_alter_role();

View file

@ -39,6 +39,7 @@ impl Parser<'_> {
Ok(Box::new(SetExpr::Merge(self.parse_merge(merge_token)?)))
}
/// Parse a `MERGE` statement
pub fn parse_merge(&mut self, merge_token: TokenWithSpan) -> Result<Statement, ParserError> {
let into = self.parse_keyword(Keyword::INTO);

File diff suppressed because it is too large Load diff

View file

@ -401,10 +401,17 @@ impl fmt::Display for Token {
}
impl Token {
/// Create a `Token::Word` from an unquoted `keyword`.
///
/// The lookup is case-insensitive; unknown values become `Keyword::NoKeyword`.
pub fn make_keyword(keyword: &str) -> Self {
Token::make_word(keyword, None)
}
/// Create a `Token::Word` from `word` with an optional `quote_style`.
///
/// When `quote_style` is `None`, the parser attempts a case-insensitive keyword
/// lookup and sets the `Word::keyword` accordingly.
pub fn make_word(word: &str, quote_style: Option<char>) -> Self {
let word_uppercase = word.to_uppercase();
Token::Word(Word {
@ -460,14 +467,27 @@ impl Word {
}
}
/// Represents whitespace in the input: spaces, newlines, tabs and comments.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum Whitespace {
/// A single space character.
Space,
/// A newline character.
Newline,
/// A tab character.
Tab,
SingleLineComment { comment: String, prefix: String },
/// A single-line comment (e.g. `-- comment` or `# comment`).
/// The `comment` field contains the text, and `prefix` contains the comment prefix.
SingleLineComment {
/// The content of the comment (without the prefix).
comment: String,
/// The prefix used for the comment (for example `--` or `#`).
prefix: String,
},
/// A multi-line comment (without the `/* ... */` delimiters).
MultiLineComment(String),
}
@ -569,7 +589,9 @@ impl From<(u64, u64)> for Location {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct Span {
/// Start `Location` (inclusive).
pub start: Location,
/// End `Location` (inclusive).
pub end: Location,
}
@ -691,8 +713,11 @@ pub type TokenWithLocation = TokenWithSpan;
#[derive(Debug, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// A `Token` together with its `Span` (location in the source).
pub struct TokenWithSpan {
/// The token value.
pub token: Token,
/// The span covering the token in the input.
pub span: Span,
}
@ -736,10 +761,12 @@ impl fmt::Display for TokenWithSpan {
}
}
/// Tokenizer error
/// An error reported by the tokenizer, with a human-readable `message` and a `location`.
#[derive(Debug, PartialEq, Eq)]
pub struct TokenizerError {
/// A descriptive error message.
pub message: String,
/// The `Location` where the error was detected.
pub location: Location,
}
@ -754,8 +781,8 @@ impl std::error::Error for TokenizerError {}
struct State<'a> {
peekable: Peekable<Chars<'a>>,
pub line: u64,
pub col: u64,
line: u64,
col: u64,
}
impl State<'_> {
@ -780,6 +807,7 @@ impl State<'_> {
self.peekable.peek()
}
/// Return the current `Location` (line and column)
pub fn location(&self) -> Location {
Location {
line: self.line,