jianguotian commented on code in PR #66: URL: https://github.com/apache/paimon-mosaic/pull/66#discussion_r3459885883
########## 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. Fixed, `cat --json` now goes through Arrow's JSON writer, so all reader types render as valid JSON. -- 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]
