mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-25 04:04:09 +00:00
feat: add per-column COMPRESSION option for SST columns (#9426)
* feat: add per-column COMPRESSION option for SST columns CREATE TABLE accepts COMPRESSION WITH (type = 'zstd', level = N, page_size = '<size>') on a column. The options are stored in the column metadata, carried through gRPC column options, shown by SHOW CREATE TABLE, and applied by the mito SST writer and bulk part encoder as parquet column properties. Unset fields keep the SST defaults. Nested types are rejected. A page size below the dictionary page limit also lowers the column's dictionary page limit: parquet sizes write batches by the dictionary budget and keeps that size after falling back to plain encoding, which would otherwise ignore the smaller data page limit. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix: validate column compression options before persistence Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix: reject compression overrides on metric logical tables Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
@@ -294,6 +294,13 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to set COMPRESSION option"))]
|
||||
SetCompressionOption {
|
||||
source: datatypes::error::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display(
|
||||
"Invalid partition number: {}, should be in range [2, 65536]",
|
||||
partition_num
|
||||
@@ -405,6 +412,7 @@ impl ErrorExt for Error {
|
||||
|
||||
PermissionDenied { .. } => StatusCode::PermissionDenied,
|
||||
SetFulltextOption { .. } | SetSkippingIndexOption { .. } => StatusCode::Unexpected,
|
||||
SetCompressionOption { source, .. } => source.status_code(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,8 +47,8 @@ use crate::error::{
|
||||
use crate::parser::{FLOW, ParserContext};
|
||||
use crate::parsers::tql_parser;
|
||||
use crate::parsers::utils::{
|
||||
self, parse_with_options, validate_column_fulltext_create_option,
|
||||
validate_column_skipping_index_create_option,
|
||||
self, parse_with_options, validate_column_compression_create_option,
|
||||
validate_column_fulltext_create_option, validate_column_skipping_index_create_option,
|
||||
};
|
||||
use crate::statements::create::{
|
||||
Column, ColumnExtensions, CreateDatabase, CreateExternalTable, CreateFlow, CreateTable,
|
||||
@@ -891,6 +891,7 @@ impl<'a> ParserContext<'a> {
|
||||
/// This function will handle:
|
||||
/// - Vector type
|
||||
/// - Indexes
|
||||
/// - SST compression options
|
||||
fn parse_column_extensions(
|
||||
parser: &mut Parser<'_>,
|
||||
column_name: &Ident,
|
||||
@@ -923,7 +924,7 @@ impl<'a> ParserContext<'a> {
|
||||
}
|
||||
|
||||
// parse index options in column definition
|
||||
let mut is_index_declared = false;
|
||||
let mut is_extension_declared = false;
|
||||
|
||||
// skipping index
|
||||
if let Token::Word(word) = parser.peek_token().token
|
||||
@@ -965,7 +966,7 @@ impl<'a> ParserContext<'a> {
|
||||
|
||||
let options = OptionMap::new(options);
|
||||
column_extensions.skipping_index_options = Some(options);
|
||||
is_index_declared |= true;
|
||||
is_extension_declared |= true;
|
||||
}
|
||||
|
||||
// fulltext index
|
||||
@@ -1016,7 +1017,7 @@ impl<'a> ParserContext<'a> {
|
||||
|
||||
let options = OptionMap::new(options);
|
||||
column_extensions.fulltext_index_options = Some(options);
|
||||
is_index_declared |= true;
|
||||
is_extension_declared |= true;
|
||||
}
|
||||
|
||||
// inverted index
|
||||
@@ -1058,10 +1059,54 @@ impl<'a> ParserContext<'a> {
|
||||
);
|
||||
|
||||
column_extensions.inverted_index_options = Some(OptionMap::default());
|
||||
is_index_declared |= true;
|
||||
is_extension_declared |= true;
|
||||
}
|
||||
|
||||
Ok(is_index_declared)
|
||||
// SST compression
|
||||
if parser.parse_keyword(Keyword::COMPRESSION) {
|
||||
ensure!(
|
||||
column_extensions.compression_options.is_none(),
|
||||
InvalidColumnOptionSnafu {
|
||||
name: column_name.to_string(),
|
||||
msg: "duplicated COMPRESSION option",
|
||||
}
|
||||
);
|
||||
|
||||
let options = parser
|
||||
.parse_options(Keyword::WITH)
|
||||
.context(error::SyntaxSnafu)?
|
||||
.into_iter()
|
||||
.map(parse_option_string)
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
ensure!(
|
||||
!options.is_empty(),
|
||||
InvalidColumnOptionSnafu {
|
||||
name: column_name.to_string(),
|
||||
msg: "expect WITH (...) after COMPRESSION keyword",
|
||||
}
|
||||
);
|
||||
for (key, value) in options.iter() {
|
||||
ensure!(
|
||||
value.as_string().is_some(),
|
||||
InvalidColumnOptionSnafu {
|
||||
name: column_name.to_string(),
|
||||
msg: format!("COMPRESSION option {key} requires a scalar value"),
|
||||
}
|
||||
);
|
||||
ensure!(
|
||||
validate_column_compression_create_option(key),
|
||||
InvalidColumnOptionSnafu {
|
||||
name: column_name.to_string(),
|
||||
msg: format!("invalid COMPRESSION option: {key}"),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
column_extensions.compression_options = Some(OptionMap::new(options));
|
||||
is_extension_declared |= true;
|
||||
}
|
||||
|
||||
Ok(is_extension_declared)
|
||||
}
|
||||
|
||||
fn parse_optional_table_constraint(&mut self) -> Result<Option<TableConstraint>> {
|
||||
@@ -3194,6 +3239,82 @@ CREATE TABLE log (
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_create_table_compression_options() {
|
||||
let parse = |sql: &str| {
|
||||
ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
|
||||
};
|
||||
|
||||
for value in ["[3]", "NULL", "['zstd']"] {
|
||||
for key in ["type", "level", "page_size"] {
|
||||
let sql = format!(
|
||||
"CREATE TABLE t (ts TIMESTAMP TIME INDEX, s STRING COMPRESSION WITH ({key}={value}))"
|
||||
);
|
||||
let err = parse(&sql).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("requires a scalar value"),
|
||||
"{sql}: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let sql = r"
|
||||
CREATE TABLE spans (
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
prompt STRING COMPRESSION WITH (type='zstd', level='3', page_size='8MiB') SKIPPING INDEX,
|
||||
reply STRING NULL COMPRESSION WITH (level='9'),
|
||||
)";
|
||||
let result = parse(sql).unwrap();
|
||||
let Statement::CreateTable(c) = &result[0] else {
|
||||
panic!("should be create_table statement");
|
||||
};
|
||||
let prompt = &c.columns[1];
|
||||
assert_eq!(
|
||||
vec!["level=3", "page_size=8MiB", "type=zstd"],
|
||||
prompt
|
||||
.extensions
|
||||
.compression_options
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.kv_pairs()
|
||||
.into_iter()
|
||||
.map(|kv| kv.replace(['\'', ' '], ""))
|
||||
.sorted()
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert!(prompt.extensions.skipping_index_options.is_some());
|
||||
// Display must produce SQL that parses back to the same column.
|
||||
let reparsed = parse(&format!(
|
||||
"CREATE TABLE t (ts TIMESTAMP TIME INDEX, {prompt})"
|
||||
))
|
||||
.unwrap();
|
||||
let Statement::CreateTable(r) = &reparsed[0] else {
|
||||
panic!("should be create_table statement");
|
||||
};
|
||||
assert_eq!(prompt.extensions, r.columns[1].extensions);
|
||||
|
||||
for (sql, err) in [
|
||||
(
|
||||
"CREATE TABLE t (ts TIMESTAMP TIME INDEX, s STRING COMPRESSION)",
|
||||
"expect WITH (...) after COMPRESSION keyword",
|
||||
),
|
||||
(
|
||||
"CREATE TABLE t (ts TIMESTAMP TIME INDEX, s STRING COMPRESSION WITH (codec='zstd'))",
|
||||
"invalid COMPRESSION option: codec",
|
||||
),
|
||||
(
|
||||
"CREATE TABLE t (ts TIMESTAMP TIME INDEX, s STRING COMPRESSION WITH (level='3') COMPRESSION WITH (level='5'))",
|
||||
"duplicated COMPRESSION option",
|
||||
),
|
||||
] {
|
||||
let result = parse(sql);
|
||||
assert!(
|
||||
result.as_ref().is_err_and(|e| e.to_string().contains(err)),
|
||||
"{sql}: {result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_create_view_with_columns() {
|
||||
let sql = "CREATE VIEW test () AS SELECT * FROM NUMBERS";
|
||||
|
||||
@@ -28,10 +28,12 @@ use datafusion_expr::{AggregateUDF, Expr, HigherOrderUDF, ScalarUDF, TableSource
|
||||
use datafusion_sql::planner::{ContextProvider, SqlToRel};
|
||||
use datatypes::arrow::datatypes::DataType;
|
||||
use datatypes::schema::{
|
||||
COLUMN_FULLTEXT_OPT_KEY_ANALYZER, COLUMN_FULLTEXT_OPT_KEY_BACKEND,
|
||||
COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE, COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE,
|
||||
COLUMN_FULLTEXT_OPT_KEY_GRANULARITY, COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE,
|
||||
COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY, COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE,
|
||||
COLUMN_COMPRESSION_OPT_KEY_LEVEL, COLUMN_COMPRESSION_OPT_KEY_PAGE_SIZE,
|
||||
COLUMN_COMPRESSION_OPT_KEY_TYPE, COLUMN_FULLTEXT_OPT_KEY_ANALYZER,
|
||||
COLUMN_FULLTEXT_OPT_KEY_BACKEND, COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE,
|
||||
COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE, COLUMN_FULLTEXT_OPT_KEY_GRANULARITY,
|
||||
COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE, COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY,
|
||||
COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE,
|
||||
};
|
||||
use snafu::{ResultExt, ensure};
|
||||
use sqlparser::dialect::Dialect;
|
||||
@@ -375,6 +377,15 @@ pub fn validate_column_skipping_index_create_option(key: &str) -> bool {
|
||||
.contains(&key)
|
||||
}
|
||||
|
||||
pub fn validate_column_compression_create_option(key: &str) -> bool {
|
||||
[
|
||||
COLUMN_COMPRESSION_OPT_KEY_TYPE,
|
||||
COLUMN_COMPRESSION_OPT_KEY_LEVEL,
|
||||
COLUMN_COMPRESSION_OPT_KEY_PAGE_SIZE,
|
||||
]
|
||||
.contains(&key)
|
||||
}
|
||||
|
||||
/// Convert an [`IntervalMonthDayNano`] to a [`Duration`].
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub fn convert_month_day_nano_to_duration(
|
||||
|
||||
@@ -58,8 +58,8 @@ use crate::ast::{
|
||||
};
|
||||
use crate::error::{
|
||||
self, ConvertToGrpcDataTypeSnafu, ConvertValueSnafu, Result,
|
||||
SerializeColumnDefaultConstraintSnafu, SetFulltextOptionSnafu, SetSkippingIndexOptionSnafu,
|
||||
SqlCommonSnafu,
|
||||
SerializeColumnDefaultConstraintSnafu, SetCompressionOptionSnafu, SetFulltextOptionSnafu,
|
||||
SetSkippingIndexOptionSnafu, SqlCommonSnafu,
|
||||
};
|
||||
use crate::statements::create::Column;
|
||||
pub use crate::statements::option_map::OptionMap;
|
||||
@@ -149,6 +149,12 @@ pub fn column_to_schema(
|
||||
.context(SetSkippingIndexOptionSnafu)?;
|
||||
}
|
||||
|
||||
if let Some(options) = column.extensions.build_compression_options()? {
|
||||
column_schema = column_schema
|
||||
.with_compression_options(options)
|
||||
.context(SetCompressionOptionSnafu)?;
|
||||
}
|
||||
|
||||
column_schema.set_inverted_index(column.extensions.inverted_index_options.is_some());
|
||||
|
||||
set_json2_extension(&mut column_schema, column)?;
|
||||
|
||||
@@ -18,7 +18,7 @@ use std::fmt::{Display, Formatter, Write};
|
||||
use common_catalog::consts::FILE_ENGINE;
|
||||
use datatypes::json::{JSON2_DEFAULT_MAX_AUTO_EXPANDED_PATHS, JsonSettings};
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{FulltextOptions, SkippingIndexOptions};
|
||||
use datatypes::schema::{CompressionOptions, FulltextOptions, SkippingIndexOptions};
|
||||
use itertools::Itertools;
|
||||
use serde::Serialize;
|
||||
use snafu::ResultExt;
|
||||
@@ -27,8 +27,8 @@ use sqlparser_derive::{Visit, VisitMut};
|
||||
|
||||
use crate::ast::{ColumnDef, Ident, ObjectName};
|
||||
use crate::error::{
|
||||
InvalidFlowQuerySnafu, InvalidSqlSnafu, Result, SetFulltextOptionSnafu,
|
||||
SetSkippingIndexOptionSnafu,
|
||||
InvalidFlowQuerySnafu, InvalidSqlSnafu, Result, SetCompressionOptionSnafu,
|
||||
SetFulltextOptionSnafu, SetSkippingIndexOptionSnafu,
|
||||
};
|
||||
use crate::statements::query::Query as GtQuery;
|
||||
use crate::statements::statement::Statement;
|
||||
@@ -160,6 +160,8 @@ pub struct ColumnExtensions {
|
||||
///
|
||||
/// Inverted index doesn't have options at present. There won't be any options in that map.
|
||||
pub inverted_index_options: Option<OptionMap>,
|
||||
/// SST compression options.
|
||||
pub compression_options: Option<OptionMap>,
|
||||
/// JSON2-specific column options.
|
||||
pub json2_options: Option<Json2Options>,
|
||||
}
|
||||
@@ -294,6 +296,11 @@ impl Column {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(compression_options) = &self.extensions.compression_options {
|
||||
let options = compression_options.kv_pairs();
|
||||
write!(f, " COMPRESSION WITH({})", format_list_comma!(options))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -319,6 +326,15 @@ impl ColumnExtensions {
|
||||
))
|
||||
}
|
||||
|
||||
pub fn build_compression_options(&self) -> Result<Option<CompressionOptions>> {
|
||||
let Some(options) = self.compression_options.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let options: HashMap<String, String> = options.clone().into_map();
|
||||
Ok(Some(options.try_into().context(SetCompressionOptionSnafu)?))
|
||||
}
|
||||
|
||||
pub fn build_json_settings(&self) -> Result<Option<JsonSettings>> {
|
||||
let Some(options) = &self.json2_options else {
|
||||
return Ok(None);
|
||||
|
||||
Reference in New Issue
Block a user