JingsongLi commented on code in PR #66: URL: https://github.com/apache/paimon-mosaic/pull/66#discussion_r3457879093
########## cli/src/fmt.rs: ########## @@ -0,0 +1,321 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use arrow_array::{Array, RecordBatch}; +use paimon_mosaic_core::values::Value; + +/// Render a stats min/max [`Value`] to a short, human-readable string. +pub fn render_value(v: &Value) -> String { + match v { + Value::Null => "null".to_string(), + Value::Boolean(b) => b.to_string(), + Value::TinyInt(x) => x.to_string(), + Value::SmallInt(x) => x.to_string(), + Value::Integer(x) => x.to_string(), + Value::BigInt(x) => x.to_string(), + Value::Float(x) => x.to_string(), + Value::Double(x) => x.to_string(), + Value::Date(x) => format!("{} (epoch-day)", x), + Value::Time(x) => format!("{} (ms)", x), + Value::String(b) => String::from_utf8_lossy(b).into_owned(), + Value::Bytes(b) | Value::DecimalLarge(b) => format!("0x{}", hex(b)), + Value::DecimalCompact(x) => x.to_string(), + Value::TimestampMillis(x) => format!("{} (ms)", x), + Value::TimestampMicros(x) => format!("{} (us)", x), + Value::TimestampNanos { millis, nanos_of_milli } => { + format!("{}ms+{}ns", millis, nanos_of_milli) + } + } +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{:02x}", x)).collect() +} + +/// Human-readable encoding name for a `spec::ENCODING_*` id. +pub fn encoding_name(e: u8) -> &'static str { + use paimon_mosaic_core::spec::*; + match e { + ENCODING_PLAIN => "plain", + ENCODING_CONST => "const", + ENCODING_DICT => "dict", + ENCODING_ALL_NULL => "all_null", + _ => "?", + } +} + +/// Compression ratio suffix like `" (uncompressed 1024 B, 2.50x)"`, or empty +/// when the uncompressed size is unknown (paged buckets don't record it). +pub fn ratio(compressed: usize, uncompressed: usize) -> String { + if uncompressed == 0 || compressed == 0 { + return String::new(); + } + format!(" (uncompressed {} B, {:.2}x)", uncompressed, uncompressed as f64 / compressed as f64) +} + +/// Escape a string as a JSON string literal (quotes included). +pub fn json_str(s: &str) -> String { + let mut o = String::with_capacity(s.len() + 2); + o.push('"'); + for c in s.chars() { + match c { + '"' => o.push_str("\\\""), + '\\' => o.push_str("\\\\"), + '\n' => o.push_str("\\n"), + '\r' => o.push_str("\\r"), + '\t' => o.push_str("\\t"), + c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)), + c => o.push(c), + } + } + o.push('"'); + o +} + +/// Pretty-print a slice of record batches as an aligned ASCII table. +pub fn pretty_table(batches: &[RecordBatch], max_rows: usize) -> String { + let schema = batches[0].schema(); + let headers: Vec<String> = schema.fields().iter().map(|f| f.name().clone()).collect(); + let ncols = headers.len(); + + let mut rows: Vec<Vec<String>> = Vec::new(); + 'outer: for batch in batches { + for r in 0..batch.num_rows() { + if rows.len() >= max_rows { + break 'outer; + } + let mut row = Vec::with_capacity(ncols); + for c in 0..ncols { + row.push(cell(batch.column(c).as_ref(), r)); + } + rows.push(row); + } + } + + let mut widths: Vec<usize> = headers.iter().map(|h| h.chars().count()).collect(); + for row in &rows { + for (i, v) in row.iter().enumerate() { + widths[i] = widths[i].max(v.chars().count()); + } + } + + let sep = |out: &mut String| { + out.push('+'); + for w in &widths { + out.push_str(&"-".repeat(w + 2)); + out.push('+'); + } + out.push('\n'); + }; + let line = |out: &mut String, cells: &[String]| { + out.push('|'); + for (i, c) in cells.iter().enumerate() { + out.push_str(&format!(" {:<w$} |", c, w = widths[i])); + } + out.push('\n'); + }; + + let mut out = String::new(); + sep(&mut out); + line(&mut out, &headers); + sep(&mut out); + for row in &rows { + line(&mut out, row); + } + sep(&mut out); + out +} + +/// Render up to `max_rows` as newline-delimited JSON objects. +pub fn ndjson(batches: &[RecordBatch], max_rows: usize) -> String { + let schema = batches[0].schema(); + let names: Vec<String> = schema.fields().iter().map(|f| f.name().clone()).collect(); + let mut out = String::new(); + let mut got = 0usize; + 'outer: for batch in batches { + for r in 0..batch.num_rows() { + if got >= max_rows { + break 'outer; + } + out.push('{'); + for (c, name) in names.iter().enumerate() { + if c > 0 { + out.push(','); + } + out.push_str(&json_str(name)); + out.push(':'); + out.push_str(&cell_json(batch.column(c).as_ref(), r)); + } + out.push_str("}\n"); + got += 1; + } + } + out +} + +/// Render one Arrow cell as a JSON value (numbers bare, strings quoted, null). +fn cell_json(arr: &dyn Array, row: usize) -> String { + use arrow_schema::DataType::*; + if arr.is_null(row) { + return "null".to_string(); + } + use arrow_array::{Float32Array, Float64Array}; + match arr.data_type() { + Utf8 => json_str(&cell(arr, row)), + // NaN / Infinity are not valid JSON numbers — emit null. + Float32 if !arr.as_any().downcast_ref::<Float32Array>().unwrap().value(row).is_finite() => "null".into(), + Float64 if !arr.as_any().downcast_ref::<Float64Array>().unwrap().value(row).is_finite() => "null".into(), + // Date32 is an epoch-day integer; emit bare like other numerics. + _ => cell(arr, row), Review Comment: `cat --json` can emit invalid JSON for Mosaic types that are supported by the core reader but not rendered by `cell()`. For example Binary, Decimal, Time32, Timestamp, List, and Map currently fall through to `?`, and this branch writes that value unquoted, producing output like `"col":?`. Parquet/Arrow CLI paths use a real JSON serializer or type-aware value rendering; please either route this through Arrow JSON writing or cover all supported Mosaic types explicitly. ########## cli/src/fmt.rs: ########## @@ -0,0 +1,321 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use arrow_array::{Array, RecordBatch}; +use paimon_mosaic_core::values::Value; + +/// Render a stats min/max [`Value`] to a short, human-readable string. +pub fn render_value(v: &Value) -> String { + match v { + Value::Null => "null".to_string(), + Value::Boolean(b) => b.to_string(), + Value::TinyInt(x) => x.to_string(), + Value::SmallInt(x) => x.to_string(), + Value::Integer(x) => x.to_string(), + Value::BigInt(x) => x.to_string(), + Value::Float(x) => x.to_string(), + Value::Double(x) => x.to_string(), + Value::Date(x) => format!("{} (epoch-day)", x), + Value::Time(x) => format!("{} (ms)", x), + Value::String(b) => String::from_utf8_lossy(b).into_owned(), + Value::Bytes(b) | Value::DecimalLarge(b) => format!("0x{}", hex(b)), + Value::DecimalCompact(x) => x.to_string(), + Value::TimestampMillis(x) => format!("{} (ms)", x), + Value::TimestampMicros(x) => format!("{} (us)", x), + Value::TimestampNanos { millis, nanos_of_milli } => { + format!("{}ms+{}ns", millis, nanos_of_milli) + } + } +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{:02x}", x)).collect() +} + +/// Human-readable encoding name for a `spec::ENCODING_*` id. +pub fn encoding_name(e: u8) -> &'static str { + use paimon_mosaic_core::spec::*; + match e { + ENCODING_PLAIN => "plain", + ENCODING_CONST => "const", + ENCODING_DICT => "dict", + ENCODING_ALL_NULL => "all_null", + _ => "?", + } +} + +/// Compression ratio suffix like `" (uncompressed 1024 B, 2.50x)"`, or empty +/// when the uncompressed size is unknown (paged buckets don't record it). +pub fn ratio(compressed: usize, uncompressed: usize) -> String { + if uncompressed == 0 || compressed == 0 { + return String::new(); + } + format!(" (uncompressed {} B, {:.2}x)", uncompressed, uncompressed as f64 / compressed as f64) +} + +/// Escape a string as a JSON string literal (quotes included). +pub fn json_str(s: &str) -> String { + let mut o = String::with_capacity(s.len() + 2); + o.push('"'); + for c in s.chars() { + match c { + '"' => o.push_str("\\\""), + '\\' => o.push_str("\\\\"), + '\n' => o.push_str("\\n"), + '\r' => o.push_str("\\r"), + '\t' => o.push_str("\\t"), + c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)), + c => o.push(c), + } + } + o.push('"'); + o +} + +/// Pretty-print a slice of record batches as an aligned ASCII table. +pub fn pretty_table(batches: &[RecordBatch], max_rows: usize) -> String { + let schema = batches[0].schema(); + let headers: Vec<String> = schema.fields().iter().map(|f| f.name().clone()).collect(); + let ncols = headers.len(); + + let mut rows: Vec<Vec<String>> = Vec::new(); + 'outer: for batch in batches { + for r in 0..batch.num_rows() { + if rows.len() >= max_rows { + break 'outer; + } + let mut row = Vec::with_capacity(ncols); + for c in 0..ncols { + row.push(cell(batch.column(c).as_ref(), r)); + } + rows.push(row); + } + } + + let mut widths: Vec<usize> = headers.iter().map(|h| h.chars().count()).collect(); + for row in &rows { + for (i, v) in row.iter().enumerate() { + widths[i] = widths[i].max(v.chars().count()); + } + } + + let sep = |out: &mut String| { + out.push('+'); + for w in &widths { + out.push_str(&"-".repeat(w + 2)); + out.push('+'); + } + out.push('\n'); + }; + let line = |out: &mut String, cells: &[String]| { + out.push('|'); + for (i, c) in cells.iter().enumerate() { + out.push_str(&format!(" {:<w$} |", c, w = widths[i])); + } + out.push('\n'); + }; + + let mut out = String::new(); + sep(&mut out); + line(&mut out, &headers); + sep(&mut out); + for row in &rows { + line(&mut out, row); + } + sep(&mut out); + out +} + +/// Render up to `max_rows` as newline-delimited JSON objects. +pub fn ndjson(batches: &[RecordBatch], max_rows: usize) -> String { + let schema = batches[0].schema(); + let names: Vec<String> = schema.fields().iter().map(|f| f.name().clone()).collect(); + let mut out = String::new(); + let mut got = 0usize; + 'outer: for batch in batches { + for r in 0..batch.num_rows() { + if got >= max_rows { + break 'outer; + } + out.push('{'); + for (c, name) in names.iter().enumerate() { + if c > 0 { + out.push(','); + } + out.push_str(&json_str(name)); + out.push(':'); + out.push_str(&cell_json(batch.column(c).as_ref(), r)); + } + out.push_str("}\n"); + got += 1; + } + } + out +} + +/// Render one Arrow cell as a JSON value (numbers bare, strings quoted, null). +fn cell_json(arr: &dyn Array, row: usize) -> String { + use arrow_schema::DataType::*; + if arr.is_null(row) { + return "null".to_string(); + } + use arrow_array::{Float32Array, Float64Array}; + match arr.data_type() { + Utf8 => json_str(&cell(arr, row)), + // NaN / Infinity are not valid JSON numbers — emit null. + Float32 if !arr.as_any().downcast_ref::<Float32Array>().unwrap().value(row).is_finite() => "null".into(), + Float64 if !arr.as_any().downcast_ref::<Float64Array>().unwrap().value(row).is_finite() => "null".into(), + // Date32 is an epoch-day integer; emit bare like other numerics. + _ => cell(arr, row), + } +} + +/// Render one Arrow cell to a string by downcasting on the column type. +fn cell(arr: &dyn Array, row: usize) -> String { + use arrow_array::*; + use arrow_schema::DataType::*; + if arr.is_null(row) { + return "".to_string(); + } + macro_rules! d { + ($ty:ty) => { + arr.as_any().downcast_ref::<$ty>().unwrap().value(row).to_string() + }; + } + match arr.data_type() { + Boolean => d!(BooleanArray), + Int8 => d!(Int8Array), + Int16 => d!(Int16Array), + Int32 => d!(Int32Array), + Int64 => d!(Int64Array), + Float32 => d!(Float32Array), + Float64 => d!(Float64Array), + Date32 => d!(Date32Array), + Utf8 => arr.as_any().downcast_ref::<StringArray>().unwrap().value(row).to_string(), + _ => "?".to_string(), + } +} + +/// A single `column op value` filter. Ops: `=` `!=` `>` `>=` `<` `<=`. +pub struct Where { + pub column: String, + pub op: &'static str, + pub value: String, +} + +/// Parse one condition like `id>100` or `kind=a`. Longest operators first. +pub fn parse_where(s: &str) -> Result<Where, String> { + for op in [">=", "<=", "!=", "=", ">", "<"] { + if let Some(i) = s.find(op) { + let column = s[..i].trim().to_string(); + let value = s[i + op.len()..].trim().to_string(); + if column.is_empty() || value.is_empty() { + return Err(format!("bad --where: {s}")); + } + return Ok(Where { column, op, value }); + } + } + Err(format!("bad --where (need =, !=, >, >=, <, <=): {s}")) +} + +/// Keep rows where the condition holds. Numeric columns compare numerically; +/// others compare as strings (only `=`/`!=` meaningful). Nulls never match. +pub fn apply_where(batch: &RecordBatch, w: &Where) -> Result<RecordBatch, String> { + let col = batch.column_by_name(&w.column) + .ok_or_else(|| format!("--where: column '{}' not found", w.column))?; + if matches!(w.op, ">"|">="|"<"|"<=") { + use arrow_schema::DataType::*; + let numeric = matches!(col.data_type(), Int8|Int16|Int32|Int64|Float32|Float64|Date32); + if !numeric || w.value.parse::<f64>().is_err() { + return Err(format!("--where: '{}' needs a numeric column and value (got '{}' {} '{}')", w.op, w.column, w.op, w.value)); + } + } + let mask: Vec<bool> = (0..batch.num_rows()).map(|r| { + if col.is_null(r) { return false; } + let lhs = cell(col.as_ref(), r); + match (lhs.parse::<f64>(), w.value.parse::<f64>()) { Review Comment: This makes equality semantics depend on whether the rendered strings happen to parse as numbers. On a Utf8 column, `--where s=1` matches both `"1"` and `"01"` because both sides parse as `f64`. Since Parquet CLI does not define this filter behavior, Mosaic should make the semantics type-driven: exact string comparison for Utf8, numeric comparison only for numeric columns. ########## cli/README.md: ########## @@ -0,0 +1,102 @@ +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +# mosaic CLI + +A native command-line inspector for Mosaic files. It drives the read-only +`MosaicReader` API, so it needs no JVM and ships as a single binary. For C/C++ +or Java callers, embed the format via the `ffi` (`mosaic.h`) or `jni` crates +rather than shelling out to this tool. + +## Install + +```bash +cargo run -p paimon-mosaic-cli -- <command> <file> # run from source +cargo install --path cli # install `mosaic` +mosaic <command> <file> +``` + +## Commands + +Every command accepts `--json`. Review Comment: `convert` does not accept `--json`, so this statement is currently inaccurate. Please scope this to the inspection/query commands or add a JSON mode to `convert`. ########## cli/src/main.rs: ########## @@ -0,0 +1,479 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +mod fmt; +mod input; + +use std::path::PathBuf; +use std::process::ExitCode; + +use arrow_array::RecordBatch; +use clap::{Parser, Subcommand}; +use paimon_mosaic_core::reader::{MosaicReader, ReaderAccess}; + +use crate::input::FileInput; + +/// Mosaic file inspector — the cat/meta/schema/pages toolkit (cf. parquet-cli). +#[derive(Parser)] +#[command(name = "mosaic", version, about)] +struct Cli { + #[command(subcommand)] + cmd: Cmd, +} + +#[derive(Subcommand)] +enum Cmd { + /// Print the column names, types, nullability and bucket assignment. + Schema { + file: PathBuf, + #[arg(long)] + json: bool, + }, + /// Print row-group / bucket / stats metadata. + Meta { + file: PathBuf, + #[arg(long)] + json: bool, + }, + /// Print per-column encoding and slot size for each row group. + Pages { + file: PathBuf, + #[arg(long)] + json: bool, + }, + /// Print the first N rows as a table. + Cat { + file: PathBuf, + /// Number of rows to print. + #[arg(short = 'n', long, default_value_t = 10)] + num: usize, + /// Print all rows (overrides -n). + #[arg(long)] + all: bool, + /// Comma-separated columns to project. + #[arg(short, long)] + columns: Option<String>, + /// Row filter, e.g. `id>100` or `kind=a` (one condition). + #[arg(long)] + r#where: Option<String>, + #[arg(long)] + json: bool, + }, + /// Print the first N rows (alias of cat). + Head { + file: PathBuf, + #[arg(short = 'n', long, default_value_t = 10)] + num: usize, + #[arg(long)] + all: bool, + #[arg(short, long)] + columns: Option<String>, + #[arg(long)] + r#where: Option<String>, + #[arg(long)] + json: bool, + }, + /// Print the total row count. + Count { + file: PathBuf, + #[arg(long)] + json: bool, + }, + /// Print the file footer: version, buckets, compression, offsets. + Footer { + file: PathBuf, + #[arg(long)] + json: bool, + }, + /// Print on-disk bytes per column (summed over row groups). + ColumnSize { + file: PathBuf, + #[arg(long)] + json: bool, + }, + /// Print the dictionary of a dict-encoded column. + Dictionary { + file: PathBuf, + /// Column name to dump. + #[arg(short = 'c', long)] + column: String, + #[arg(long)] + json: bool, + }, + /// Print bucket layout per row group (Mosaic's column grouping). + Buckets { + file: PathBuf, + #[arg(long)] + json: bool, + }, + /// Import a CSV or JSON file into a new Mosaic file (schema inferred). + Convert { + /// Input: CSV (.csv, header row) or JSON lines (.json/.ndjson/.jsonl). + input: PathBuf, + /// Output .mosaic path. + #[arg(short, long)] + out: PathBuf, + /// Columns to build min/max stats for (comma-separated). + #[arg(long)] + stats: Option<String>, + }, +} + +fn main() -> ExitCode { + let cli = Cli::parse(); + let res = match cli.cmd { + Cmd::Schema { file, json } => schema(&file, json), + Cmd::Meta { file, json } => meta(&file, json), + Cmd::Pages { file, json } => pages(&file, json), + Cmd::Cat { file, num, all, columns, r#where, json } => cat(&file, if all { usize::MAX } else { num }, columns, r#where, json), + Cmd::Head { file, num, all, columns, r#where, json } => cat(&file, if all { usize::MAX } else { num }, columns, r#where, json), + Cmd::Count { file, json } => count(&file, json), + Cmd::Footer { file, json } => footer(&file, json), + Cmd::ColumnSize { file, json } => column_size(&file, json), + Cmd::Dictionary { file, column, json } => dictionary(&file, &column, json), + Cmd::Buckets { file, json } => buckets(&file, json), + Cmd::Convert { input, out, stats } => convert(&input, &out, stats), + }; + match res { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +fn open(file: &PathBuf) -> std::io::Result<MosaicReader<FileInput>> { + let input = FileInput::open(file)?; + let len = input.len(); + MosaicReader::new(input, len) +} + +/// Columns in original (write) order rather than the name-sorted layout. +fn original_order(s: &paimon_mosaic_core::schema::MosaicSchema) -> Vec<usize> { + let mut by_sorted = vec![0usize; s.columns.len()]; + for (orig, &sorted) in s.original_order.iter().enumerate() { + by_sorted[sorted] = orig; + } + let mut cols: Vec<usize> = (0..s.columns.len()).collect(); + cols.sort_by_key(|&i| by_sorted[i]); + cols +} + +/// Add `total` across `cols`, distributing the remainder so the parts sum exactly. +fn split_evenly(total: usize, cols: &[usize], acc: &mut [usize]) { + if cols.is_empty() { return; } + let share = total / cols.len(); + let mut rem = total % cols.len(); + for &c in cols { + acc[c] += share + if rem > 0 { rem -= 1; 1 } else { 0 }; + } +} + +fn schema(file: &PathBuf, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let s = reader.schema(); + let cols = original_order(s); + if json { + let items: Vec<String> = cols.iter().map(|&i| { + let c = &s.columns[i]; + format!("{{\"name\":{},\"type\":{},\"nullable\":{},\"bucket\":{}}}", + fmt::json_str(&c.name), fmt::json_str(&format!("{:?}", c.data_type)), c.nullable, c.bucket_id) + }).collect(); + println!("{{\"columns\":{},\"buckets\":{},\"fields\":[{}]}}", s.columns.len(), s.num_buckets, items.join(",")); + return Ok(()); + } + println!("{} columns, {} buckets", s.columns.len(), s.num_buckets); + for i in cols { + let c = &s.columns[i]; + let null = if c.nullable { "" } else { " not null" }; + println!(" {}: {:?}{} [bucket {}]", c.name, c.data_type, null, c.bucket_id); + } + Ok(()) +} + +fn meta(file: &PathBuf, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let s = reader.schema(); + let nrg = reader.num_row_groups(); + let total: usize = (0..nrg).map(|i| reader.row_group_num_rows(i).unwrap_or(0)).sum(); + if json { + let mut rgs = Vec::new(); + for rg in 0..nrg { + let st: Vec<String> = reader.row_group_stats(rg)?.iter().map(|x| { + let mm = match (&x.min, &x.max) { + (Some(lo), Some(hi)) => format!(",\"min\":{},\"max\":{}", fmt::json_str(&fmt::render_value(lo)), fmt::json_str(&fmt::render_value(hi))), + _ => String::new(), + }; + format!("{{\"column\":{},\"nulls\":{}{}}}", fmt::json_str(&s.columns[x.column_index].name), x.null_count, mm) + }).collect(); + rgs.push(format!("{{\"rows\":{},\"stats\":[{}]}}", reader.row_group_num_rows(rg)?, st.join(","))); + } + println!("{{\"rows\":{},\"columns\":{},\"buckets\":{},\"row_groups\":[{}]}}", total, s.columns.len(), s.num_buckets, rgs.join(",")); + return Ok(()); + } + println!("file: {} rows, {} columns, {} buckets, {} row groups", total, s.columns.len(), s.num_buckets, nrg); + for rg in 0..nrg { + println!("row group {rg}: {} rows", reader.row_group_num_rows(rg)?); + for st in reader.row_group_stats(rg)? { + let mm = match (&st.min, &st.max) { + (Some(lo), Some(hi)) => format!("min={} max={}", fmt::render_value(lo), fmt::render_value(hi)), + _ => "no min/max".to_string(), + }; + println!(" {}: nulls={} {}", s.columns[st.column_index].name, st.null_count, mm); + } + } + Ok(()) +} + +fn pages(file: &PathBuf, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let s = reader.schema(); + let nrg = reader.num_row_groups(); + if json { + let mut rgs = Vec::new(); + for rg in 0..nrg { + let items: Vec<String> = reader.page_infos(rg)?.iter().map(|p| { + format!("{{\"column\":{},\"bucket\":{},\"encoding\":{},\"slot_size\":{}}}", + fmt::json_str(&s.columns[p.column_index].name), p.bucket, fmt::json_str(fmt::encoding_name(p.encoding)), p.slot_size) + }).collect(); + rgs.push(format!("[{}]", items.join(","))); + } + println!("{{\"row_groups\":[{}]}}", rgs.join(",")); + return Ok(()); + } + for rg in 0..nrg { + println!("row group {rg}:"); + for p in reader.page_infos(rg)? { + let c = &s.columns[p.column_index]; + println!(" {}: bucket {} encoding={} slot={}B", c.name, p.bucket, fmt::encoding_name(p.encoding), p.slot_size); + } + } + Ok(()) +} + +fn count(file: &PathBuf, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let n: usize = (0..reader.num_row_groups()).map(|i| reader.row_group_num_rows(i).unwrap_or(0)).sum(); + if json { println!("{{\"rows\":{}}}", n); } else { println!("{}", n); } + Ok(()) +} + +/// Output sink writing a Mosaic file to disk, tracking its own position. +struct FileOut { f: std::fs::File, pos: u64 } +impl paimon_mosaic_core::writer::OutputFile for FileOut { + fn write(&mut self, d: &[u8]) -> std::io::Result<()> { + use std::io::Write; + self.pos += d.len() as u64; + self.f.write_all(d) + } + fn flush(&mut self) -> std::io::Result<()> { use std::io::Write; self.f.flush() } + fn pos(&self) -> u64 { self.pos } +} + +fn convert(input: &PathBuf, out: &PathBuf, stats: Option<String>) -> std::io::Result<()> { + use paimon_mosaic_core::writer::{MosaicWriter, WriterOptions}; + use arrow_schema::ArrowError; + let bad = |e: ArrowError| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()); + let is_json = matches!(input.extension().and_then(|e| e.to_str()), Some("json") | Some("ndjson") | Some("jsonl")); + // Infer schema, then build a batch iterator — CSV (header) or JSON (one object per line). + type Batches = Box<dyn Iterator<Item = Result<RecordBatch, ArrowError>>>; + let (schema, reader): (arrow_schema::Schema, Batches) = if is_json { + let mut r = std::io::BufReader::new(std::fs::File::open(input)?); + let (schema, _) = arrow_json::reader::infer_json_schema(&mut r, None).map_err(bad)?; + let rd = arrow_json::ReaderBuilder::new(std::sync::Arc::new(schema.clone())) + .build(std::io::BufReader::new(std::fs::File::open(input)?)).map_err(bad)?; + (schema, Box::new(rd)) + } else { + let (schema, _) = arrow_csv::reader::Format::default().with_header(true) + .infer_schema(std::io::BufReader::new(std::fs::File::open(input)?), None).map_err(bad)?; + let rd = arrow_csv::ReaderBuilder::new(std::sync::Arc::new(schema.clone())) + .with_header(true).build(std::io::BufReader::new(std::fs::File::open(input)?)).map_err(bad)?; + (schema, Box::new(rd)) + }; + let opts = WriterOptions { + stats_columns: stats.map(|s| s.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect()).unwrap_or_default(), + ..Default::default() + }; + // Write to a temp file and rename on success, so a mid-stream failure never + // leaves a truncated .mosaic in place. + let tmp = out.with_extension("mosaic.tmp"); + let mut rows = 0; + let res = (|| { + let sink = FileOut { f: std::fs::File::create(&tmp)?, pos: 0 }; + let mut w = MosaicWriter::new(sink, &schema, opts)?; + for batch in reader { + let batch = batch.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?; + rows += batch.num_rows(); + w.write_batch(&batch)?; + } + w.close() + })(); + if let Err(e) = res { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + std::fs::rename(&tmp, out)?; + println!("wrote {} ({} rows, {} columns)", out.display(), rows, schema.fields().len()); + Ok(()) +} + +fn cat(file: &PathBuf, num: usize, columns: Option<String>, filter: Option<String>, json: bool) -> std::io::Result<()> { + let mut reader = open(file)?; + if let Some(list) = &columns { + let names: Vec<&str> = list.split(',').map(|x| x.trim()).filter(|x| !x.is_empty()).collect(); + reader.project(&names)?; + } + let pred = filter.as_deref().map(fmt::parse_where).transpose() + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?; + // Column index of the filter target, for stats-based row-group skipping. + let pred_col = pred.as_ref().and_then(|p| reader.schema().columns.iter().position(|c| c.name == p.column)); + let mut batches: Vec<RecordBatch> = Vec::new(); + let mut got = 0usize; + for rg in 0..reader.num_row_groups() { + if got >= num { + break; + } + // Pushdown: skip a row group when its min/max prove no row can match. + if let (Some(p), Some(ci)) = (&pred, pred_col) { + if let Some(st) = reader.row_group_stats(rg)?.iter().find(|s| s.column_index == ci) { + if fmt::stats_exclude(p, &st.min, &st.max) { continue; } + } + } + let mut batch = reader.row_group_reader(rg)?.read_columns()?; + if let Some(p) = &pred { + batch = fmt::apply_where(&batch, p) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?; + } + got += batch.num_rows(); + batches.push(batch); + } + if batches.iter().all(|b| b.num_rows() == 0) { + if !json { + println!("(no rows)"); + } + } else if json { + print!("{}", fmt::ndjson(&batches, num)); + } else { + print!("{}", fmt::pretty_table(&batches, num)); + } + Ok(()) +} + +fn footer(file: &PathBuf, json: bool) -> std::io::Result<()> { + use paimon_mosaic_core::spec::{COMPRESSION_ZSTD, MAGIC, VERSION}; + let reader = open(file)?; + let s = reader.schema(); + let comp = if reader.compression() == COMPRESSION_ZSTD { "zstd" } else { "none" }; + let magic = std::str::from_utf8(&MAGIC).unwrap_or("MOSA"); + if json { + println!("{{\"magic\":{},\"version\":{},\"buckets\":{},\"row_groups\":{},\"compression\":{}}}", + fmt::json_str(magic), VERSION, s.num_buckets, reader.num_row_groups(), fmt::json_str(comp)); + } else { + println!("magic={} version={} buckets={} row_groups={} compression={}", + magic, VERSION, s.num_buckets, reader.num_row_groups(), comp); + } + Ok(()) +} + +fn column_size(file: &PathBuf, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let s = reader.schema(); + let mut bytes = vec![0usize; s.columns.len()]; + let mut raw = vec![0usize; s.columns.len()]; + for rg in 0..reader.num_row_groups() { + // On-disk bytes are tracked per bucket (works for both monolithic and + // paged layouts); split a bucket's size across its member columns. + for b in reader.bucket_infos(rg)? { + if b.columns.is_empty() { continue; } + split_evenly(b.size, &b.columns, &mut bytes); Review Comment: This differs materially from Parquet CLI `column-size`, which sums exact column-chunk sizes from metadata. Here the bucket size is split evenly across member columns, so the per-column bytes can be quite misleading; for paged buckets we should be able to use per-column slot sizes instead. If monolithic bucket attribution must remain approximate, please label it as approximate in the command output/docs rather than presenting it as exact per-column size. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
