package browse
import (
"context"
"fmt"
"io"
"github.com/dolthub/dolt/go/libraries/doltcore/doltdb"
"github.com/dolthub/dolt/go/libraries/doltcore/doltdb/durable"
"github.com/dolthub/dolt/go/libraries/doltcore/schema"
"github.com/dolthub/dolt/go/store/val"
)
// Cell placeholders. Rendering must never panic and never emit non-printable
// bytes; exotic or out-of-band values degrade to one of these.
const (
placeholderNull = "NULL"
placeholderBinary = "<binary>"
placeholderUnreadable = "<unreadable>"
)
// ColumnInfo describes one column of a table schema.
type ColumnInfo struct {
Name string
Type string
PrimaryKey bool
Nullable bool
}
// TableInfo is a table name, its schema, and its row count at a ref.
type TableInfo struct {
Name string
Columns []ColumnInfo
RowCount uint64
}
// RowPage is a paginated slice of a table's rows rendered to strings. Columns
// lists the column names in the same order as each row's cells. For keyed
// tables columns are primary-key columns first, then the rest.
type RowPage struct {
Columns []string
Rows [][]string
Offset int
Total int
}
// Tables lists the tables in the committed root at ref (a branch name or
// commit hash), each with its schema and row count.
func (db *DB) Tables(ctx context.Context, refStr string) ([]TableInfo, error) {
root, err := db.resolveRoot(ctx, refStr)
if err != nil {
return nil, err
}
names, err := root.GetTableNames(ctx, doltdb.DefaultSchemaName, false)
if err != nil {
return nil, fmt.Errorf("browse: list tables at %q: %w", refStr, err)
}
infos := make([]TableInfo, 0, len(names))
for _, name := range names {
tbl, ok, err := root.GetTable(ctx, doltdb.TableName{Name: name})
if err != nil {
return nil, fmt.Errorf("browse: get table %q: %w", name, err)
}
if !ok {
// Listed by GetTableNames but not resolvable: inconsistent root.
return nil, fmt.Errorf("browse: table %q listed but missing", name)
}
sch, err := tbl.GetSchema(ctx)
if err != nil {
return nil, fmt.Errorf("browse: schema of %q: %w", name, err)
}
idx, err := tbl.GetRowData(ctx)
if err != nil {
return nil, fmt.Errorf("browse: row data of %q: %w", name, err)
}
count, err := idx.Count()
if err != nil {
return nil, fmt.Errorf("browse: row count of %q: %w", name, err)
}
infos = append(infos, TableInfo{
Name: name,
Columns: columnInfos(sch),
RowCount: count,
})
}
return infos, nil
}
// columnInfos renders a schema's columns in natural table order.
func columnInfos(sch schema.Schema) []ColumnInfo {
cols := sch.GetAllCols().GetColumns()
out := make([]ColumnInfo, len(cols))
for i, c := range cols {
typeStr := ""
if c.TypeInfo != nil {
if sqlType := c.TypeInfo.ToSqlType(); sqlType != nil {
typeStr = sqlType.String()
} else {
typeStr = c.TypeInfo.String()
}
}
out[i] = ColumnInfo{
Name: c.Name,
Type: typeStr,
PrimaryKey: c.IsPartOfPK,
Nullable: c.IsNullable(),
}
}
return out
}
// cellRef locates a column's value within a prolly row: either in the key
// tuple or the value tuple, at the given field index.
type cellRef struct {
fromKey bool
idx int
}
// Rows returns a page of rows from table at ref, starting at offset (0-based)
// and returning at most limit rows. The page is read directly from the prolly
// map via an ordinal range, so it is O(limit) regardless of offset.
func (db *DB) Rows(ctx context.Context, refStr, table string, offset, limit int) (*RowPage, error) {
if offset < 0 {
return nil, fmt.Errorf("browse: offset must be non-negative, got %d", offset)
}
if limit <= 0 {
return nil, fmt.Errorf("browse: limit must be positive, got %d", limit)
}
root, err := db.resolveRoot(ctx, refStr)
if err != nil {
return nil, err
}
tbl, ok, err := root.GetTable(ctx, doltdb.TableName{Name: table})
if err != nil {
return nil, fmt.Errorf("browse: get table %q: %w", table, err)
}
if !ok {
return nil, fmt.Errorf("%w: %s", ErrTableNotFound, table)
}
sch, err := tbl.GetSchema(ctx)
if err != nil {
return nil, fmt.Errorf("browse: schema of %q: %w", table, err)
}
idx, err := tbl.GetRowData(ctx)
if err != nil {
return nil, fmt.Errorf("browse: row data of %q: %w", table, err)
}
total, err := idx.Count()
if err != nil {
return nil, fmt.Errorf("browse: row count of %q: %w", table, err)
}
colNames, refs := rowLayout(sch)
page := &RowPage{
Columns: colNames,
Rows: [][]string{},
Offset: offset,
Total: int(total),
}
start := uint64(offset)
if start >= total {
// Past the end (also covers the empty-table case): no rows.
return page, nil
}
stop := start + uint64(limit)
if stop > total {
stop = total
}
m, err := durable.ProllyMapFromIndex(idx)
if err != nil {
return nil, fmt.Errorf("browse: prolly map of %q: %w", table, err)
}
keyDesc, valDesc := m.Descriptors()
iter, err := m.IterOrdinalRange(ctx, start, stop)
if err != nil {
return nil, fmt.Errorf("browse: iterate rows of %q: %w", table, err)
}
for {
key, value, err := iter.Next(ctx)
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("browse: read row of %q: %w", table, err)
}
row := make([]string, len(refs))
for i, r := range refs {
if r.fromKey {
row[i] = renderCell(ctx, keyDesc, r.idx, key)
} else {
row[i] = renderCell(ctx, valDesc, r.idx, value)
}
}
page.Rows = append(page.Rows, row)
}
return page, nil
}
// rowLayout maps schema columns to their position in the prolly key/value
// tuples and produces the display column order.
//
// - Keyed tables: primary-key columns (in key order) map to the key tuple,
// the remaining columns (in stored order) to the value tuple.
// - Keyless tables: every column is in the value tuple; field 0 is the
// hidden cardinality, so column i lives at value index i+1, and there is
// no meaningful key.
func rowLayout(sch schema.Schema) ([]string, []cellRef) {
if schema.IsKeyless(sch) {
cols := sch.GetNonPKCols().GetColumns()
names := make([]string, len(cols))
refs := make([]cellRef, len(cols))
for i, c := range cols {
names[i] = c.Name
refs[i] = cellRef{fromKey: false, idx: i + 1}
}
return names, refs
}
pkCols := sch.GetPKCols().GetColumns()
nonPKCols := sch.GetNonPKCols().GetColumns()
names := make([]string, 0, len(pkCols)+len(nonPKCols))
refs := make([]cellRef, 0, len(pkCols)+len(nonPKCols))
for i, c := range pkCols {
names = append(names, c.Name)
refs = append(refs, cellRef{fromKey: true, idx: i})
}
for i, c := range nonPKCols {
names = append(names, c.Name)
refs = append(refs, cellRef{fromKey: false, idx: i})
}
return names, refs
}
// renderCell renders one tuple field to a display string. It never panics
// (recovering into a placeholder) and maps binary / out-of-band encodings to
// "<binary>" so a row preview never dumps opaque bytes.
func renderCell(ctx context.Context, td *val.TupleDesc, i int, tup val.Tuple) (out string) {
defer func() {
if r := recover(); r != nil {
out = placeholderUnreadable
}
}()
if i < 0 || i >= td.Count() {
// Column not present in this tuple (e.g. a virtual/dropped column that
// isn't materialized): degrade rather than index out of range.
return placeholderUnreadable
}
if td.IsNull(i, tup) {
return placeholderNull
}
switch td.Types[i].Enc {
case val.ByteStringEnc, val.Hash128Enc, val.CellEnc,
val.BytesAddrEnc, val.StringAddrEnc, val.JSONAddrEnc,
val.GeomAddrEnc, val.CommitAddrEnc,
val.BytesAdaptiveEnc, val.GeomAdaptiveEnc:
return placeholderBinary
}
return td.FormatValue(ctx, i, td.GetField(i, tup))
}