# Scans

> Scans, samples and measures run one task per collection their Collections names, from a start key, inclusive, towards an end key, exclusive, in a ScanDirection.

`import "github.com/unum-cloud/ustore"` 1.0.0-rc.1 · 084197c4

Scans, samples and measures run one task per collection their `Collections` names, from a start key, inclusive, towards an end key, exclusive, in a `ScanDirection`. `BlobsScan` lists up to the count it wants, `BlobsSample` draws keys at random, and `BlobsMeasure` bounds the keys and bytes a range holds without walking it; `DocsScan`, `PagesScan`, `StringsScan` and `GraphScanVertices` serve the other modalities. A start key of `Key{}` walks up from the first key, and `KeyUnknown` walks down from the last. A cursor walks one collection page by page, each pull resuming past the last key the one before it handed out, and a page shorter than wanted exhausts it for good. `ChangesCursorInit` opens a feed of the changes committed after a `CommitStamp`, oldest first, pinning that stamp as a snapshot does. A cursor keeps no executor: `cursor.NextPairs(..)` pulls on the calling goroutine, and `cursor.On(executor).NextPairs(..)` blocks on the executor named for that pull. A `DocsCursor` gathers the `Fields` of its config into typed columns, and its `Next` answers `DocsBatches`, one batch of keys and columns per executor task that found rows, none once the walk is exhausted.

```go
first, err := database.BlobsScan(people, 100, arena, nil)
measured, err := database.BlobsMeasure(people, arena, &ustore.MeasureConfig{StartKeys: []ustore.Key{ada}, EndKeys: []ustore.Key{kent}})
last, err := database.BlobsScan(people, 10, arena, &ustore.BlobsScanConfig{
	StartKeys: []ustore.Key{ustore.KeyUnknown}, Direction: ustore.ScanDescending,
})

cursor, err := database.On(executor).BlobsCursorInit(people, ustore.Key{}, nil)
defer cursor.Close()
for {
	page, err := cursor.On(executor).NextPairs(1024, arena)
	if err != nil || page.Len() < 1024 {
		break
	}
}

ages, err := database.DocsCursorInit(people, ustore.Key{}, &ustore.DocsCursorConfig{
	Fields: ustore.TapeOf("age"), ColumnsTypes: []ustore.DocsFieldType{ustore.DocsFieldTypeU64},
})
defer ages.Close()
batches, err := ages.On(executor).Next(1024, arena) // batches.Keys(i) and batches.Columns(i) per batch
```

### Progress and Cancellation

The configs of `Compact`, `Save`, `PagesImport` and the scans carry an optional `ProgressCallback`, called with the units finished and the units in all, never on two threads at once and never after the call is final. Answering false cancels the call, which fails with `StatusCancelled` and publishes nothing, a cancelled save removing what it wrote. A handler must not panic, since unwinding through the library’s C frames aborts the process.

```go
deadline := time.Now().Add(30 * time.Second)
beforeTheDeadline := func(finished, total uint64) bool { return time.Now().Before(deadline) }
err := snapshot.Save("/var/lib/people-copy", beforeTheDeadline)
if errors.Is(err, ustore.StatusCancelled) {
	fmt.Println("the copy was removed")
}
```

The `Predicate` field of a scan or cursor config admits or passes over the keys it lists, asked on the host, and its type tells the library what one call costs:

- `ustore.Predicate` answers one key at a time, asked before patterns or filters read any value.
- `ustore.BatchPredicate` answers a page of keys at once, asked about the keys patterns and filters kept, for handlers that pay per call.
- `ustore.CheapBatchPredicate` answers a page of keys at once, asked before patterns or filters read any value.

```go
odd := ustore.Predicate(func(key ustore.Key) bool { return key[15]%2 == 1 })
found, err := database.BlobsScan(people, 10, arena, &ustore.BlobsScanConfig{Predicate: odd})

moderated := ustore.BatchPredicate(func(keys []ustore.Key, admissions []ustore.Admission) {
	for position, allowed := range moderation.Check(keys) { // one round trip for the whole page
		if allowed {
			admissions[position] = ustore.Admit
		}
	}
})
found, err = database.BlobsScan(people, 10, arena, &ustore.BlobsScanConfig{Predicate: moderated})
```

Admissions start as `ustore.Reject`, and both slices live only until the handler returns.

## API

### Types

#### `Admission`

Admission is whether a predicate keeps a listed key or passes over it.

[db.go:465 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L465)

```go
type Admission int32
```

#### Values

| `Reject` | | Reject passes over the key. |
| - | - | - |
| `Admit` | | Admit keeps the key among the listed ones. |

#### `Admitter`

Admitter is the predicate a scan or a cursor asks about the keys it lists: a [Predicate](#Predicate), a [BatchPredicate](#BatchPredicate) or a [CheapBatchPredicate](#CheapBatchPredicate), whose type tells the library what one call costs.

[db.go:443 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L443)

```go
type Admitter interface {
    // contains filtered or unexported methods
}
```

#### `BatchPredicate`

BatchPredicate writes an Admission for every key into admissions, which start as Reject, for handlers that pay per call: it is asked once per page about every key patterns and filters kept.

[db.go:458 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L458)

```go
type BatchPredicate func(keys []Key, admissions []Admission)
```

Both slices live only until it returns. The executor's threads may ask it at once, so it must be safe to call from several goroutines concurrently, and it must not panic.

#### `BlobsCursorConfig`

BlobsCursorConfig carries the optional arguments of [DatabaseOn.BlobsCursorInit](https://www.unum.cloud/docs/ustore/go/batches-and-arenas.md#BlobsCursorInit).

[db.go:383 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L383)

```go
type BlobsCursorConfig struct {
    EndKey *Key
    Direction ScanDirection
    Patterns Patterns
    Predicate Admitter
}
```

#### Fields

| `EndKey` | `*Key` | EndKey is the key the walk stops before, or nil for no bound. |
| - | - | - |
| `Direction` | `ScanDirection` | Direction is which way the walk goes from its start. |
| `Patterns` | `Patterns` | Patterns keep the keys whose values match, compiled once. |
| `Predicate` | `Admitter` | Predicate admits or passes over the keys of every page. |

#### `CheapBatchPredicate`

CheapBatchPredicate is a [BatchPredicate](#BatchPredicate) asked once per page before patterns or filters read any value, so it narrows those reads.

[db.go:462 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L462)

```go
type CheapBatchPredicate func(keys []Key, admissions []Admission)
```

#### `DocsCursorConfig`

DocsCursorConfig carries the optional arguments of [DatabaseOn.DocsCursorInit](https://www.unum.cloud/docs/ustore/go/batches-and-arenas.md#DocsCursorInit).

[db.go:548 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L548)

```go
type DocsCursorConfig struct {
    EndKey *Key
    Direction ScanDirection
    Filter string
    Predicate Admitter
    Fields Tape
    ColumnsTypes []DocsFieldType
}
```

#### Fields

| `EndKey` | `*Key` | EndKey is the key the walk stops before, or nil for no bound. |
| - | - | - |
| `Direction` | `ScanDirection` | Direction is which way the walk goes from its start. |
| `Filter` | `string` | Filter is a JSONPath every document the walk hands out matches, compiled once. |
| `Predicate` | `Admitter` | Predicate admits or passes over the keys of every page. |
| `Fields` | `Tape` | Fields are the fields every pull gathers into the columns of its batches, the empty field being the whole document, or none for keys alone. |
| `ColumnsTypes` | `[]DocsFieldType` | ColumnsTypes holds the type every field converts into, one per field. |

#### `DocsScanConfig`

DocsScanConfig carries the optional arguments of [DatabaseOn.DocsScan](https://www.unum.cloud/docs/ustore/go/batches-and-arenas.md#DocsScan).

[db.go:473 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L473)

```go
type DocsScanConfig struct {
    StartKeys []Key
    EndKeys []Key
    Direction ScanDirection
    Filter string
    Predicate Admitter
    Mode ScanMode
    Progress ProgressCallback
}
```

#### Fields

| `StartKeys` | `[]Key` | StartKeys are the inclusive starts of the scans, one per task, or the first key in Direction when empty. |
| - | - | - |
| `EndKeys` | `[]Key` | EndKeys are the keys every scan stops before, one per task, or no bound when empty. |
| `Direction` | `ScanDirection` | Direction is which way every scan goes from its start. |
| `Filter` | `string` | Filter is a JSONPath, or a bare root filter such as ?@.age>30, every listed document matches. |
| `Predicate` | `Admitter` | Predicate admits or passes over the listed keys. |
| `Mode` | `ScanMode` | Mode is in what order the keys come. |
| `Progress` | `ProgressCallback` | Progress reports the scans finished, and may cancel the call. |

#### `Each`

Each names one collection per task of a batch.

[db.go:154 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L154)

```go
type Each []CollectionID
```

#### `MeasureConfig`

MeasureConfig carries the optional arguments of a measure.

[db.go:110 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L110)

```go
type MeasureConfig struct {
    StartKeys []Key
    EndKeys []Key
    Direction ScanDirection
}
```

#### Fields

| `StartKeys` | `[]Key` | StartKeys are the inclusive starts of the ranges, one per task, or the first key in Direction when empty. |
| - | - | - |
| `EndKeys` | `[]Key` | EndKeys are the keys every range stops before, one per task, or no bound when empty. |
| `Direction` | `ScanDirection` | Direction is which way every range goes from its start. |

#### `Measured`

Measured is the bounds on the entries and the space one range holds.

[db.go:134 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L134)

```go
type Measured struct {
    MinCardinality, MaxCardinality uint64
    MinValueBytes, MaxValueBytes   uint64
    MinSpaceUsage, MaxSpaceUsage   uint64
}
```

#### `PagesCursorConfig`

PagesCursorConfig carries the optional arguments of [DatabaseOn.PagesCursorInit](https://www.unum.cloud/docs/ustore/go/batches-and-arenas.md#PagesCursorInit).

[db.go:577 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L577)

```go
type PagesCursorConfig struct {
    EndKey *Key
    Direction ScanDirection
    Filter string
    Predicate Admitter
}
```

#### Fields

| `EndKey` | `*Key` | EndKey is the key the walk stops before, or nil for no bound. |
| - | - | - |
| `Direction` | `ScanDirection` | Direction is which way the walk goes from its start. |
| `Filter` | `string` | Filter is the expression every page the walk hands out matches, compiled once. |
| `Predicate` | `Admitter` | Predicate admits or passes over the keys of every page. |

#### `Patterns`

Patterns keeps the values or strings a scan or a walk lists to the ones matching, shared by every task of the call; the zero value matches everything.

[db.go:620 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L620)

```go
type Patterns struct {
    Patterns Tape
    Kind PatternKind
    Sensitivity CaseSensitivity
    Weights []float32
}
```

#### Fields

| `Patterns` | `Tape` | Patterns are the expressions or substrings to match. |
| - | - | - |
| `Kind` | `PatternKind` | Kind is what the patterns are matched as. |
| `Sensitivity` | `CaseSensitivity` | Sensitivity is whether matching folds case. |
| `Weights` | `[]float32` | Weights holds one weight per substring pattern, which turns on BM25 scores, or nothing. |

#### `Predicate`

Predicate admits one listed key into a scan or a walk, or passes over it, asked once per page before patterns or filters read any value.

[db.go:452 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L452)

```go
type Predicate func(key Key) bool
```

The executor's threads may ask it at once, so it must be safe to call from several goroutines concurrently, and it must not panic.

#### Enum `CaseSensitivity`

CaseSensitivity is whether patterns compare bytes as they are or after Unicode case folding.2

[types.go:257 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/types.go#L257)

```go
type CaseSensitivity int32
```

#### Values

| `Cased` | | Cased compares bytes as they are. |
| - | - | - |
| `Uncased` | | Uncased folds the case of both the patterns and the values. |

##### `CaseSensitivityFromName`

CaseSensitivityFromName reads a case sensitivity back from the spelling [CaseSensitivity.String](https://www.unum.cloud/docs/ustore/go/platform-notes.md#String) renders.

[types.go:273 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/types.go#L273)

```go
func CaseSensitivityFromName(name string) (CaseSensitivity, error)
```

##### `String`

String renders the case sensitivity as the library spells it.

[types.go:267 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/types.go#L267)

```go
func (sensitivity CaseSensitivity) String() string
```

#### Enum `ChangeKind`

ChangeKind is what one committed change did to its key.2

[db.go:392 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L392)

```go
type ChangeKind int32
```

#### Values

| `ChangeWrite` | | ChangeWrite wrote the whole value. |
| - | - | - |
| `ChangeRemoval` | | ChangeRemoval removed the key. |
| `ChangeChange` | | ChangeChange changed part of the value, as a document patch or a page edit does. |

##### `ChangeKindFromName`

ChangeKindFromName reads a change kind back from the spelling [ChangeKind.String](https://www.unum.cloud/docs/ustore/go/platform-notes.md#String) renders.

[db.go:409 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L409)

```go
func ChangeKindFromName(name string) (ChangeKind, error)
```

##### `String`

String renders the change kind as the library spells it.

[db.go:404 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L404)

```go
func (kind ChangeKind) String() string
```

#### Struct `Changes`

Changes is one pull of a feed, written into its arena and readable until the arena serves another call.5

[db.go:1858 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1858)

```go
type Changes struct {
    // contains filtered or unexported fields
}
```

##### `Key`

Key reports the key change index touched.

[db.go:1871 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1871)

```go
func (changes Changes) Key(index uint) Key
```

##### `Kind`

Kind reports what change index did to its key.

[db.go:1885 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1885)

```go
func (changes Changes) Kind(index uint) ChangeKind
```

##### `Len`

Len reports how many changes the pull yielded, zero at the newest commit.

[db.go:1868 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1868)

```go
func (changes Changes) Len() uint
```

##### `Stamp`

Stamp reports the commit change index landed at.

[db.go:1878 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1878)

```go
func (changes Changes) Stamp(index uint) CommitStamp
```

##### `Value`

Value views the bytes change index carries in the arena, empty for a removal and for a pull through [ChangesCursor.NextKeys](https://www.unum.cloud/docs/ustore/go/batches-and-arenas.md#NextKeys).

[db.go:1893 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1893)

```go
func (changes Changes) Value(index uint) []byte
```

#### Struct `Measurement`

Measurement is the bounds a measure estimated, one per range, readable until the arena serves another call.2

[blobs.go:122 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/blobs.go#L122)

```go
type Measurement struct {
    // contains filtered or unexported fields
}
```

##### `Get`

Get reports the bounds of range index.

[blobs.go:144 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/blobs.go#L144)

```go
func (measurement Measurement) Get(index uint) Measured
```

##### `Len`

Len reports how many ranges the call measured.

[blobs.go:141 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/blobs.go#L141)

```go
func (measurement Measurement) Len() uint
```

#### Struct `Page`

Page is one pull of a walk, written into its arena and readable until the arena serves another call.3

[db.go:1780 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1780)

```go
type Page struct {
    // contains filtered or unexported fields
}
```

##### `Keys`

Keys views the keys of the page in the arena.

[db.go:1791 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1791)

```go
func (page Page) Keys() []Key
```

##### `Len`

Len reports how many keys the pull handed out; fewer than wanted exhausts the walk for good.

[db.go:1788 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1788)

```go
func (page Page) Len() uint
```

##### `Values`

Values views the values of the page in the arena, one per key, empty for a keys-only pull.

[db.go:1798 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L1798)

```go
func (page Page) Values() Strings
```

#### Enum `PatternKind`

PatternKind is what the strings of [Patterns](#Patterns) are matched as.2

[types.go:235 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/types.go#L235)

```go
type PatternKind int32
```

#### Values

| `PatternRegex` | | PatternRegex matches regular expressions, of which a value matches at least one somewhere. |
| - | - | - |
| `PatternSubstrings` | | PatternSubstrings matches literal substrings, found together through Aho-Corasick. |

##### `PatternKindFromName`

PatternKindFromName reads a pattern kind back from the spelling [PatternKind.String](https://www.unum.cloud/docs/ustore/go/platform-notes.md#String) renders.

[types.go:250 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/types.go#L250)

```go
func PatternKindFromName(name string) (PatternKind, error)
```

##### `String`

String renders the pattern kind as the library spells it.

[types.go:245 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/types.go#L245)

```go
func (kind PatternKind) String() string
```

#### Enum `ScanDirection`

ScanDirection is which way a scan, a walk or a measure goes from its start key.2

[db.go:286 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L286)

```go
type ScanDirection int32
```

#### Values

| `ScanAscending` | | ScanAscending walks up from the start key, the default. |
| - | - | - |
| `ScanDescending` | | ScanDescending walks down from the start key. |

##### `ScanDirectionFromName`

ScanDirectionFromName reads a direction back from the spelling [ScanDirection.String](https://www.unum.cloud/docs/ustore/go/platform-notes.md#String) renders.

[db.go:301 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L301)

```go
func ScanDirectionFromName(name string) (ScanDirection, error)
```

##### `String`

String renders the direction as the library spells it.

[db.go:296 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L296)

```go
func (direction ScanDirection) String() string
```

#### Enum `ScanMode`

ScanMode is in what order a scan hands its keys over.2

[db.go:264 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L264)

```go
type ScanMode int32
```

#### Values

| `ScanOrdered` | | ScanOrdered hands keys over in their order. |
| - | - | - |
| `ScanUnordered` | | ScanUnordered hands keys over in any order, as fast as the engine finds them. |

##### `ScanModeFromName`

ScanModeFromName reads a scan mode back from the spelling [ScanMode.String](https://www.unum.cloud/docs/ustore/go/platform-notes.md#String) renders.

[db.go:279 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L279)

```go
func ScanModeFromName(name string) (ScanMode, error)
```

##### `String`

String renders the scan mode as the library spells it.

[db.go:274 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/db.go#L274)

```go
func (mode ScanMode) String() string
```

#### Struct `Scanned`

Scanned is what a batch of scans or samples wrote into its arena, keys scan after scan, readable until the arena serves another call.3

[blobs.go:79 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/blobs.go#L79)

```go
type Scanned struct {
    // contains filtered or unexported fields
}
```

##### `Keys`

Keys views the keys scan task found in the arena.

[blobs.go:91 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/blobs.go#L91)

```go
func (scanned Scanned) Keys(task uint) []Key
```

##### `Len`

Len reports how many scans or samples the call ran.

[blobs.go:88 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/blobs.go#L88)

```go
func (scanned Scanned) Len() uint
```

##### `Scores`

Scores views the BM25 score of every key scan task found, and nothing unless the patterns carried weights.

[blobs.go:99 ↗](https://github.com/unum-cloud/UStore/blob/084197c470a8c329d83051d880c71e7972b9e1b2/blobs.go#L99)

```go
func (scanned Scanned) Scores(task uint) []float32
```
