jianguotian commented on code in PR #66: URL: https://github.com/apache/paimon-mosaic/pull/66#discussion_r3491836614
########## cli/src/main.rs: ########## @@ -0,0 +1,789 @@ +// 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 filter; +mod fmt; +mod input; +mod jsonout; + +use std::path::{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, + /// Comma-separated columns to show (default: all). + #[arg(short, long)] + columns: Option<String>, + #[arg(long)] + json: bool, + }, + /// Print all rows as a table (use -n to limit). + Cat { + file: PathBuf, + /// Limit to N rows (default: all). + #[arg(short = 'n', long)] + num: Option<usize>, + /// 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 (default 10). + Head { + file: PathBuf, + #[arg(short = 'n', long, default_value_t = 10)] + num: usize, + #[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, + /// Comma-separated columns to show (default: all). + #[arg(short, long)] + columns: Option<String>, + #[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>, + /// Overwrite the output file if it already exists. + #[arg(long)] + overwrite: bool, + }, +} + +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, + columns, + json, + } => pages(&file, columns, json), + Cmd::Cat { + file, + num, + columns, + r#where, + json, + } => cat(&file, num.unwrap_or(usize::MAX), columns, r#where, json), + Cmd::Head { + file, + num, + columns, + r#where, + json, + } => cat(&file, num, columns, r#where, json), + Cmd::Count { file, json } => count(&file, json), + Cmd::Footer { file, json } => footer(&file, json), + Cmd::ColumnSize { + file, + columns, + json, + } => column_size(&file, columns, json), + Cmd::Dictionary { file, column, json } => dictionary(&file, &column, json), + Cmd::Buckets { file, json } => buckets(&file, json), + Cmd::Convert { + input, + out, + stats, + overwrite, + } => convert(&input, &out, stats, overwrite), + }; + match res { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +fn open(file: &Path) -> 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 +} + +/// Split a comma list into trimmed, non-empty names (e.g. `-c a, b,` -> [a, b]). +fn parse_comma_list(l: &str) -> Vec<String> { + l.split(',') + .map(str::trim) + .filter(|x| !x.is_empty()) + .map(String::from) + .collect() +} + +/// Parse a `-c a,b` list into a name set, or `None` for "all columns". +fn col_filter( + columns: &Option<String>, + s: &paimon_mosaic_core::schema::MosaicSchema, +) -> std::io::Result<Option<std::collections::HashSet<String>>> { + let Some(l) = columns else { return Ok(None) }; + let set: std::collections::HashSet<String> = parse_comma_list(l).into_iter().collect(); + if let Some(bad) = set + .iter() + .find(|n| !s.columns.iter().any(|c| &c.name == *n)) + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("column '{bad}' not found in schema"), + )); + } + Ok(Some(set)) +} + +/// True when `name` is selected by a `-c` set (`None` = all columns). +fn selected(want: &Option<std::collections::HashSet<String>>, name: &str) -> bool { + want.as_ref().is_none_or(|w| w.contains(name)) +} + +/// 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: &Path, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let s = reader.schema(); + let cols = original_order(s); + if json { + let fields = cols + .iter() + .map(|&i| { + let c = &s.columns[i]; + jsonout::SchemaField { + name: c.name.clone(), + ty: format!("{:?}", c.data_type), + nullable: c.nullable, + bucket: c.bucket_id as u32, + } + }) + .collect(); + println!( + "{}", + jsonout::line(&jsonout::Schema { + columns: s.columns.len(), + buckets: s.num_buckets, + fields, + }) + ); + 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 {}]", + fmt::safe(&c.name), + c.data_type, + null, + c.bucket_id + ); + } + Ok(()) +} + +fn meta(file: &Path, 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)) + .sum::<std::io::Result<usize>>()?; + if json { + let mut row_groups = Vec::new(); + for rg in 0..nrg { + let stats = reader + .row_group_stats(rg)? + .iter() + .map(|x| { + let (min, max) = match (&x.min, &x.max) { + (Some(lo), Some(hi)) => { + (Some(fmt::render_json(lo)), Some(fmt::render_json(hi))) + } + _ => (None, None), + }; + jsonout::Stat { + column: s.columns[x.column_index].name.clone(), + nulls: x.null_count, + min, + max, + } + }) + .collect(); + row_groups.push(jsonout::MetaRg { + rows: reader.row_group_num_rows(rg)?, + stats, + }); + } + println!( + "{}", + jsonout::line(&jsonout::Meta { + rows: total, + columns: s.columns.len(), + buckets: s.num_buckets, + row_groups, + }) + ); + 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={} {}", + fmt::safe(&s.columns[st.column_index].name), + st.null_count, + mm + ); + } + } + Ok(()) +} + +fn pages(file: &Path, columns: Option<String>, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let s = reader.schema(); + let want = col_filter(&columns, s)?; + let nrg = reader.num_row_groups(); + if json { + let mut row_groups = Vec::new(); + for rg in 0..nrg { + let pgs = reader + .page_infos(rg)? + .iter() + .filter(|p| selected(&want, &s.columns[p.column_index].name)) + .map(|p| jsonout::Page { + column: s.columns[p.column_index].name.clone(), + bucket: p.bucket, + encoding: fmt::encoding_name(p.encoding), + slot_size: p.slot_size, + }) + .collect(); + row_groups.push(pgs); + } + println!("{}", jsonout::line(&jsonout::Pages { row_groups })); + 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]; + if !selected(&want, &c.name) { + continue; + } + println!( + " {}: bucket {} encoding={} slot={}B", + fmt::safe(&c.name), + p.bucket, + fmt::encoding_name(p.encoding), + p.slot_size + ); + } + } + Ok(()) +} + +fn count(file: &Path, 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)) + .sum::<std::io::Result<usize>>()?; + if json { + println!("{}", jsonout::line(&jsonout::Count { rows: n })); + } else { + println!("{}", n); + } + Ok(()) +} + +fn convert( + input: &Path, + out: &Path, + stats: Option<String>, + overwrite: bool, +) -> std::io::Result<()> { + if out.exists() && !overwrite { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!("{} exists (use --overwrite to replace)", out.display()), + )); + } + use arrow::error::ArrowError; + use paimon_mosaic_core::writer::{MosaicWriter, WriterOptions}; + 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>>>; + // Schema inference and the data reader each need their own pass over the + // file (inference consumes a reader), so open it twice via one helper. + let open = + || -> std::io::Result<_> { Ok(std::io::BufReader::new(std::fs::File::open(input)?)) }; + let (schema, reader): (arrow::datatypes::Schema, Batches) = if is_json { + let (schema, _) = + arrow::json::reader::infer_json_schema(&mut open()?, None).map_err(bad)?; + let rd = arrow::json::ReaderBuilder::new(std::sync::Arc::new(schema.clone())) + .build(open()?) + .map_err(bad)?; + (schema, Box::new(rd)) + } else { + let (schema, _) = arrow::csv::reader::Format::default() + .with_header(true) + .infer_schema(open()?, None) + .map_err(bad)?; + let rd = arrow::csv::ReaderBuilder::new(std::sync::Arc::new(schema.clone())) + .with_header(true) + .build(open()?) + .map_err(bad)?; + (schema, Box::new(rd)) + }; + let opts = WriterOptions { + stats_columns: stats.map(|s| parse_comma_list(&s)).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 = paimon_mosaic_core::writer::FileSink::create(&tmp)?; + 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)?; + let plural = |n: usize, w: &str| { + if n == 1 { + format!("1 {w}") + } else { + format!("{n} {w}s") + } + }; + println!( + "wrote {} ({}, {})", + out.display(), + plural(rows, "row"), + plural(schema.fields().len(), "column") + ); + Ok(()) +} + +fn cat( + file: &Path, + num: usize, + columns: Option<String>, + filter: Option<String>, + json: bool, +) -> std::io::Result<()> { + let mut reader = open(file)?; + let pred = filter + .as_deref() + .map(filter::parse_where) + .transpose() + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?; + // The display columns; the filter column is read even if projected out, then + // dropped before printing, so `--where` works on a hidden column. + let mut display: Vec<String> = Vec::new(); + if let Some(list) = &columns { + display = parse_comma_list(list); + let mut read: Vec<&str> = display.iter().map(String::as_str).collect(); + if let Some(p) = &pred { + if !read.contains(&p.column.as_str()) { + read.push(&p.column); + } + } + reader.project(&read)?; + } + // 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(); Review Comment: Fixed: unbounded text `cat` now streams per row group, while bounded output still buffers for table width. ########## cli/src/main.rs: ########## @@ -0,0 +1,789 @@ +// 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 filter; +mod fmt; +mod input; +mod jsonout; + +use std::path::{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, + /// Comma-separated columns to show (default: all). + #[arg(short, long)] + columns: Option<String>, + #[arg(long)] + json: bool, + }, + /// Print all rows as a table (use -n to limit). + Cat { + file: PathBuf, + /// Limit to N rows (default: all). + #[arg(short = 'n', long)] + num: Option<usize>, + /// 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 (default 10). + Head { + file: PathBuf, + #[arg(short = 'n', long, default_value_t = 10)] + num: usize, + #[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, + /// Comma-separated columns to show (default: all). + #[arg(short, long)] + columns: Option<String>, + #[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>, + /// Overwrite the output file if it already exists. + #[arg(long)] + overwrite: bool, + }, +} + +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, + columns, + json, + } => pages(&file, columns, json), + Cmd::Cat { + file, + num, + columns, + r#where, + json, + } => cat(&file, num.unwrap_or(usize::MAX), columns, r#where, json), + Cmd::Head { + file, + num, + columns, + r#where, + json, + } => cat(&file, num, columns, r#where, json), + Cmd::Count { file, json } => count(&file, json), + Cmd::Footer { file, json } => footer(&file, json), + Cmd::ColumnSize { + file, + columns, + json, + } => column_size(&file, columns, json), + Cmd::Dictionary { file, column, json } => dictionary(&file, &column, json), + Cmd::Buckets { file, json } => buckets(&file, json), + Cmd::Convert { + input, + out, + stats, + overwrite, + } => convert(&input, &out, stats, overwrite), + }; + match res { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +fn open(file: &Path) -> 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 +} + +/// Split a comma list into trimmed, non-empty names (e.g. `-c a, b,` -> [a, b]). +fn parse_comma_list(l: &str) -> Vec<String> { + l.split(',') + .map(str::trim) + .filter(|x| !x.is_empty()) + .map(String::from) + .collect() +} + +/// Parse a `-c a,b` list into a name set, or `None` for "all columns". +fn col_filter( + columns: &Option<String>, + s: &paimon_mosaic_core::schema::MosaicSchema, +) -> std::io::Result<Option<std::collections::HashSet<String>>> { + let Some(l) = columns else { return Ok(None) }; + let set: std::collections::HashSet<String> = parse_comma_list(l).into_iter().collect(); + if let Some(bad) = set + .iter() + .find(|n| !s.columns.iter().any(|c| &c.name == *n)) + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("column '{bad}' not found in schema"), + )); + } + Ok(Some(set)) +} + +/// True when `name` is selected by a `-c` set (`None` = all columns). +fn selected(want: &Option<std::collections::HashSet<String>>, name: &str) -> bool { + want.as_ref().is_none_or(|w| w.contains(name)) +} + +/// 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: &Path, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let s = reader.schema(); + let cols = original_order(s); + if json { + let fields = cols + .iter() + .map(|&i| { + let c = &s.columns[i]; + jsonout::SchemaField { + name: c.name.clone(), + ty: format!("{:?}", c.data_type), + nullable: c.nullable, + bucket: c.bucket_id as u32, + } + }) + .collect(); + println!( + "{}", + jsonout::line(&jsonout::Schema { + columns: s.columns.len(), + buckets: s.num_buckets, + fields, + }) + ); + 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 {}]", + fmt::safe(&c.name), + c.data_type, + null, + c.bucket_id + ); + } + Ok(()) +} + +fn meta(file: &Path, 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)) + .sum::<std::io::Result<usize>>()?; + if json { + let mut row_groups = Vec::new(); + for rg in 0..nrg { + let stats = reader + .row_group_stats(rg)? + .iter() + .map(|x| { + let (min, max) = match (&x.min, &x.max) { + (Some(lo), Some(hi)) => { + (Some(fmt::render_json(lo)), Some(fmt::render_json(hi))) + } + _ => (None, None), + }; + jsonout::Stat { + column: s.columns[x.column_index].name.clone(), + nulls: x.null_count, + min, + max, + } + }) + .collect(); + row_groups.push(jsonout::MetaRg { + rows: reader.row_group_num_rows(rg)?, + stats, + }); + } + println!( + "{}", + jsonout::line(&jsonout::Meta { + rows: total, + columns: s.columns.len(), + buckets: s.num_buckets, + row_groups, + }) + ); + 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={} {}", + fmt::safe(&s.columns[st.column_index].name), + st.null_count, + mm + ); + } + } + Ok(()) +} + +fn pages(file: &Path, columns: Option<String>, json: bool) -> std::io::Result<()> { + let reader = open(file)?; + let s = reader.schema(); + let want = col_filter(&columns, s)?; + let nrg = reader.num_row_groups(); + if json { + let mut row_groups = Vec::new(); + for rg in 0..nrg { + let pgs = reader Review Comment: Fixed: `pages -c` now uses `page_infos_projected`, so unrelated columns are not inspected. ########## core/src/reader.rs: ########## @@ -447,6 +535,226 @@ impl<I: InputFile> MosaicReader<I> { &self.input } + /// Footer compression code (`spec::COMPRESSION_*`). + pub fn compression(&self) -> u8 { + self.compression + } + + /// Per-bucket layout for a row group: kind, on-disk size and member columns + /// (global indices). The bucket is Mosaic's defining structure — exposed for + /// the `buckets` command. + pub fn bucket_infos(&self, rg_index: usize) -> io::Result<Vec<BucketInfo>> { + if rg_index >= self.row_group_metas.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "row group index out of range", + )); + } + let meta = &self.row_group_metas[rg_index]; + Ok((0..self.num_buckets) + .map(|b| { + let (kind, size, uncompressed) = match meta.bucket_layouts[b] { + BucketLayout::Empty => (BucketKind::Empty, 0, 0), + BucketLayout::Monolithic { + compressed_size, + uncompressed_size, + } => (BucketKind::Monolithic, compressed_size, uncompressed_size), + BucketLayout::Paged { total_size } => (BucketKind::Paged, total_size, 0), + }; + BucketInfo { + bucket: b, + kind, + size, + uncompressed, + columns: self.schema.bucket_to_global[b].clone(), + } + }) + .collect()) + } + + /// Dictionary entries for one column in one row group, or `None` if that + /// column is not dict-encoded there. Used by the `dictionary` command. + pub fn dictionary(&self, rg_index: usize, col: usize) -> io::Result<Option<Vec<Value>>> { + let rg = self.row_group_reader_projected(rg_index, &[col])?; + Ok(rg.take_dictionary(col)) + } + + /// Per-column physical layout for a row group: bucket, encoding and on-disk + /// slot size. Reads and decompresses each non-empty bucket; used by tooling + /// (the `pages` command). Columns are reported in global (name-sorted) order. + pub fn page_infos(&self, rg_index: usize) -> io::Result<Vec<PageInfo>> { + if rg_index >= self.row_group_metas.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "row group index out of range", + )); + } + let meta = &self.row_group_metas[rg_index]; + let mut out = Vec::with_capacity(self.schema.columns.len()); + for b in 0..self.num_buckets { + let globals = &self.schema.bucket_to_global[b]; + match meta.bucket_layouts[b] { + BucketLayout::Empty => { + for &gi in globals { + out.push(PageInfo { + column_index: gi, + bucket: b, + encoding: Encoding::AllNull, + slot_size: 0, + }); + } + } + BucketLayout::Monolithic { + compressed_size, + uncompressed_size, + } => { + let buf = read_range(&self.input, meta.bucket_offsets[b], compressed_size)?; + let data = match self.compression { + COMPRESSION_NONE => buf, + COMPRESSION_ZSTD => decompress_zstd(&buf, uncompressed_size)?, + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "unsupported compression", + )) + } + }; + let col_types: Vec<DataType> = globals + .iter() + .map(|&gi| self.schema.columns[gi].data_type.clone()) + .collect(); + let reader = BucketReader::new(col_types, data, meta.num_rows)?; + for (local, &gi) in globals.iter().enumerate() { + out.push(PageInfo { + column_index: gi, + bucket: b, + encoding: Encoding::from_code(reader.encodings()[local]), + slot_size: 0, + }); + } + } + BucketLayout::Paged { total_size } => { + // Physical layout: optional child header + one slot per + // physical column (primaries first, then ARRAY children). + let (dir_size, sizes, _) = + self.paged_dir(b, meta.bucket_offsets[b], total_size)?; + let mut foff = meta.bucket_offsets[b] + dir_size as u64; + for (local, &gi) in globals.iter().enumerate() { + let enc = if sizes[local] == 0 { + ENCODING_ALL_NULL + } else { + let slot = read_range(&self.input, foff, sizes[local])?; + let ct = self.schema.columns[gi].data_type.clone(); + Self::parse_column_slot(&slot, &ct, meta.num_rows)?.encoding() + }; + out.push(PageInfo { + column_index: gi, + bucket: b, + encoding: Encoding::from_code(enc), + slot_size: sizes[local], Review Comment: Fixed: `PageInfo.slot_size` now includes ARRAY/LIST child slots, with a paged-array test assertion. ########## cli/src/fmt.rs: ########## @@ -0,0 +1,327 @@ +// 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) => safe(&String::from_utf8_lossy(b)), + 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) + } + } +} + +/// Render a stats min/max [`Value`] for JSON: same as [`render_value`] but +/// without the human-only unit suffixes (`(epoch-day)`, `(ms)`, `ms+ns`), so +/// the value stays machine-parseable. Bytes/decimal keep hex; nanos collapse to +/// a single nanosecond count. +pub fn render_json(v: &Value) -> String { + match v { + Value::Date(x) | Value::Time(x) => x.to_string(), + Value::TimestampMillis(x) | Value::TimestampMicros(x) => x.to_string(), + Value::TimestampNanos { + millis, + nanos_of_milli, + } => (*millis as i128 * 1_000_000 + *nanos_of_milli as i128).to_string(), + _ => render_value(v), Review Comment: Fixed: JSON string values and bucket column names now stay lossless; only text output uses `safe()`. ########## cli/src/main.rs: ########## @@ -0,0 +1,823 @@ +// 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 filter; +mod fmt; +mod input; +mod jsonout; + +use std::path::{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, + /// Comma-separated columns to show (default: all). + #[arg(short, long)] + columns: Option<String>, + #[arg(long)] + json: bool, + }, + /// Print rows as a table (default: first 10; use --all to scan all). Review Comment: Fixed: `cat` is unbounded by default again, and memory usage is handled by streaming output. -- 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]
