Skip to content

support load local - #7493

Merged
mergify[bot] merged 14 commits into
matrixorigin:mainfrom
mooleetzi:load-local
Jan 13, 2023
Merged

mergify[bot] merged 14 commits into
matrixorigin:mainfrom
mooleetzi:load-local

Conversation

@mooleetzi

@mooleetzi mooleetzi commented Jan 6, 2023 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #6665

What this PR does / why we need it:

doc https://github.com/matrixorigin/docs/pull/96

# Conflicts:
#	pkg/frontend/mysql_cmd_executor.go
#	pkg/sql/colexec/external/external.go
#	pkg/sql/compile/compile.go
#	pkg/sql/parsers/tree/update.go
#	pkg/vm/process/types.go
@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Jan 6, 2023
@mergify mergify Bot added the kind/feature label Jan 6, 2023
@ouyuanning

Copy link
Copy Markdown
Contributor

better to have some bvt test. if supported in mo-tester.

@mooleetzi

Copy link
Copy Markdown
Contributor Author

better to have some bvt test. if supported in mo-tester.

I'd like to, but mo-tester dose not support.

@mooleetzi
mooleetzi requested a review from aressu1985 as a code owner January 6, 2023 11:22
@mooleetzi
mooleetzi requested a review from a user January 6, 2023 11:22
# Conflicts:
#	pkg/sql/colexec/external/external.go
# Conflicts:
#	pkg/frontend/mysql_cmd_executor.go
# Conflicts:
#	pkg/frontend/mysql_cmd_executor.go
#	pkg/vm/process/types.go
@mergify
mergify Bot merged commit 0ecddc6 into matrixorigin:main Jan 13, 2023
fengttt added a commit that referenced this pull request Aug 27, 2026
…ssage / __mo_error_text (#27517) (#27609)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [x] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #27517

## What this PR does / why we need it:

A scan of an external table fails the whole statement on the first
record it cannot parse. One bad line in a million-line file means no
result at all, and no way to find out which line it was without reading
the file by hand.

This adds an **error mode**: a bad record becomes a *row* instead of a
*failure*. It is switched on by asking for it — by selecting one of two
columns the query would otherwise not mention.

### The columns

Three hidden columns exist on every text-backed external table
(`EXTERNAL`, `KAFKA`, `DATASTREAM`, foreign). They do not appear in
`select *`, `desc`, or `show create table`, and their names are reserved
so a user table cannot declare them.

| Column | Type | Meaning |
|---|---|---|
| `__mo_file_line` | `bigint` | the physical line the record starts on
(`NULL` for Kafka, which has no lines) |
| `__mo_error_message` | `varchar` | why the record failed, `NULL` if it
parsed |
| `__mo_error_text` | `varchar` | the record as written in the source,
`NULL` if it parsed |

```sql
create external table t (a int, s varchar(20))
  infile{'filepath'='/data/rows.csv'};

-- unchanged: fails on the first bad record
select * from t;

-- reports them instead
select a, s, __mo_file_line, __mo_error_message, __mo_error_text from t;

-- the two halves of a load
insert into good    select a, s from t where __mo_error_message is null;
insert into rejects select __mo_file_line, __mo_error_message, __mo_error_text from t
                    where __mo_error_message is not null;
```

On a failed row every user column is `NULL` — including one that
happened to convert before the failure, because the record is not
trustworthy — while every column the scan *synthesizes* keeps its value:
`__mo_filepath`, `__mo_file_line`, and the Kafka metadata columns. Those
are what let a user find the record again.

### What switches it on

`__mo_error_message` and `__mo_error_text` turn tolerance on.
`__mo_file_line` deliberately does **not**: it is position metadata, and
per the issue a query that only wants line numbers must still fail on a
bad record. The decision is made once per scan in
`resolveExternalErrorMode`, from the attribute list the operator was
given — column pruning has already run, so a query that does not mention
the columns takes the historical path with no per-row test to pay for.
It is keyed on the reserved column ids, not the names.

**Pruning had to be taught one thing.** Whether a record failed is a
property of the record, not of the projection. With the user columns
pruned away nothing is converted, so nothing fails, and `select
__mo_error_message from t` — the query that asks which records failed —
answered "none". An external scan that keeps an error column now keeps
every record-backed column through pruning; the scan's own `ProjectList`
still projects only the referenced ones, so the cost falls only on
queries that asked.

### Where it is implemented

Two places produce the error columns, one per text format, shared by
every engine that reads text — which is all of them except Parquet and
Iceberg:

```
                    ┌──────────────── CsvReader.makeBatchRows ─────────────────┐
file / datastream ─►│ csvparser.Read ─► [JSONLINE: transJson2Lines] ─► getOneRowData │
foreign scan ──────►└──────────────────────────────────────────────────────────┘
kafka ────────────► KafkaReader.ReadBatch ─► parseOneMessage ─► getOneRowData
```

`getOneRowData` is the single conversion site: under tolerance it
snapshots every vector's length, and on failure rolls back and emits the
replacement row through `appendErrorRow`, which fills the synthesized
columns through the ordinary column path so they are typed as the
catalog declares them. Datastream and foreign scans need no code of
their own — they read through the same `CsvReader`.

Line numbers live in the parser: `lineNo` counts newline bytes,
`readRecord` snapshots it at the record's **first content byte**, and
`RecordLine()` returns it 1-based. So a CSV record with a quoted field
spanning lines 5-7 reports 5 and the next reports 8, and a record after
a blank line reports its own line.

### Three latent JSONLINE defects this uncovered

All predate this PR and are fixed here:

1. **The synthesized columns were matched against JSON object keys**, so
with the error columns projected *every* record — valid ones included —
failed with "the table column is larger than input data column".
2. **A malformed line was glued onto the next one.** A failed parse was
held over in `prevStr` to be completed by the following line, and
`bytejson` reports a bare word (`this is not json`) as an unexpected EOF
exactly as it reports a truncated object. Text is now held over only
when the parser ran off the end *and* the text opens the expected value;
anything else is a malformed record and says so. Text held over that the
file never completes is reported at EOF rather than dropped.
3. **The batch tail was trimmed by one row on every held-over record.**
That compensated for rows being written into pre-allocated slots, which
is how the reader worked in 2023 (#7493); rows are appended now, so the
trim silently discarded a complete row.

### Not covered

- **Parquet and Iceberg** decode typed columnar values, not text: there
is no line and no per-record text. Naming an error column on such a
table is refused at bind time (`column __mo_error_message not found`),
since those readers resolve columns against the file's own schema;
ordinary reads and `select *` are unaffected. The BVT pins this
boundary.
- **Constraint violations at the destination.** Error mode reports what
the *scan* could not parse; an `insert ... select` that violates a
primary key still fails the statement.
- **A record too damaged to delimit.** Tolerance is per record, and a
record is whatever the CSV parser delimits — an unbalanced quote
swallows the rest of the file into one record, reported as one failure.

Design notes: `docs/design/external_table_error_mode.md`.

## Tests

| Level | What it proves |
|---|---|
| `pkg/sql/util/csvparser` `TestRecordLine` | one record per line, a
multi-line quoted record reporting its first line, exactness across a
small read block, blank lines still counted |
| `pkg/sql/colexec/external` `error_mode_test.go` | the switch (error
columns tolerate, `__mo_file_line` alone does not, a lookalike user
column does not), a pruned scan failing exactly as before, and CSV /
JSONLINE / Kafka each reporting a bad record with its position, message
and source text while neighbouring records are unaffected |
| `pkg/sql/plan` `TestExternalScanTolerates` | the pruning rule is
driven by the two error columns only, keyed on column id |
| BVT `table/external_table_error_mode` | end to end: hidden from
`select *`/`desc`/`show create table`, the same bad record found
regardless of which user columns are projected, the good/rejects split
loaded into real tables, multi-line records, blank lines, an
unterminated object, the parquet boundary, and the reserved names
refused by DDL |

Local validation: `pkg/catalog`, `pkg/sql/colexec/external`,
`pkg/sql/util/csvparser` green; `pkg/sql/plan` green apart from
`TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp`,
which reproduces on a clean `origin/main` worktree (timezone-dependent,
unrelated). BVT: error-mode 45/45, `load_data` 1032/1032, `datastream`
111/111.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…ssage / __mo_error_text (matrixorigin#27517) (matrixorigin#27609)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [x] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27517

## What this PR does / why we need it:

A scan of an external table fails the whole statement on the first
record it cannot parse. One bad line in a million-line file means no
result at all, and no way to find out which line it was without reading
the file by hand.

This adds an **error mode**: a bad record becomes a *row* instead of a
*failure*. It is switched on by asking for it — by selecting one of two
columns the query would otherwise not mention.

### The columns

Three hidden columns exist on every text-backed external table
(`EXTERNAL`, `KAFKA`, `DATASTREAM`, foreign). They do not appear in
`select *`, `desc`, or `show create table`, and their names are reserved
so a user table cannot declare them.

| Column | Type | Meaning |
|---|---|---|
| `__mo_file_line` | `bigint` | the physical line the record starts on
(`NULL` for Kafka, which has no lines) |
| `__mo_error_message` | `varchar` | why the record failed, `NULL` if it
parsed |
| `__mo_error_text` | `varchar` | the record as written in the source,
`NULL` if it parsed |

```sql
create external table t (a int, s varchar(20))
  infile{'filepath'='/data/rows.csv'};

-- unchanged: fails on the first bad record
select * from t;

-- reports them instead
select a, s, __mo_file_line, __mo_error_message, __mo_error_text from t;

-- the two halves of a load
insert into good    select a, s from t where __mo_error_message is null;
insert into rejects select __mo_file_line, __mo_error_message, __mo_error_text from t
                    where __mo_error_message is not null;
```

On a failed row every user column is `NULL` — including one that
happened to convert before the failure, because the record is not
trustworthy — while every column the scan *synthesizes* keeps its value:
`__mo_filepath`, `__mo_file_line`, and the Kafka metadata columns. Those
are what let a user find the record again.

### What switches it on

`__mo_error_message` and `__mo_error_text` turn tolerance on.
`__mo_file_line` deliberately does **not**: it is position metadata, and
per the issue a query that only wants line numbers must still fail on a
bad record. The decision is made once per scan in
`resolveExternalErrorMode`, from the attribute list the operator was
given — column pruning has already run, so a query that does not mention
the columns takes the historical path with no per-row test to pay for.
It is keyed on the reserved column ids, not the names.

**Pruning had to be taught one thing.** Whether a record failed is a
property of the record, not of the projection. With the user columns
pruned away nothing is converted, so nothing fails, and `select
__mo_error_message from t` — the query that asks which records failed —
answered "none". An external scan that keeps an error column now keeps
every record-backed column through pruning; the scan's own `ProjectList`
still projects only the referenced ones, so the cost falls only on
queries that asked.

### Where it is implemented

Two places produce the error columns, one per text format, shared by
every engine that reads text — which is all of them except Parquet and
Iceberg:

```
                    ┌──────────────── CsvReader.makeBatchRows ─────────────────┐
file / datastream ─►│ csvparser.Read ─► [JSONLINE: transJson2Lines] ─► getOneRowData │
foreign scan ──────►└──────────────────────────────────────────────────────────┘
kafka ────────────► KafkaReader.ReadBatch ─► parseOneMessage ─► getOneRowData
```

`getOneRowData` is the single conversion site: under tolerance it
snapshots every vector's length, and on failure rolls back and emits the
replacement row through `appendErrorRow`, which fills the synthesized
columns through the ordinary column path so they are typed as the
catalog declares them. Datastream and foreign scans need no code of
their own — they read through the same `CsvReader`.

Line numbers live in the parser: `lineNo` counts newline bytes,
`readRecord` snapshots it at the record's **first content byte**, and
`RecordLine()` returns it 1-based. So a CSV record with a quoted field
spanning lines 5-7 reports 5 and the next reports 8, and a record after
a blank line reports its own line.

### Three latent JSONLINE defects this uncovered

All predate this PR and are fixed here:

1. **The synthesized columns were matched against JSON object keys**, so
with the error columns projected *every* record — valid ones included —
failed with "the table column is larger than input data column".
2. **A malformed line was glued onto the next one.** A failed parse was
held over in `prevStr` to be completed by the following line, and
`bytejson` reports a bare word (`this is not json`) as an unexpected EOF
exactly as it reports a truncated object. Text is now held over only
when the parser ran off the end *and* the text opens the expected value;
anything else is a malformed record and says so. Text held over that the
file never completes is reported at EOF rather than dropped.
3. **The batch tail was trimmed by one row on every held-over record.**
That compensated for rows being written into pre-allocated slots, which
is how the reader worked in 2023 (matrixorigin#7493); rows are appended now, so the
trim silently discarded a complete row.

### Not covered

- **Parquet and Iceberg** decode typed columnar values, not text: there
is no line and no per-record text. Naming an error column on such a
table is refused at bind time (`column __mo_error_message not found`),
since those readers resolve columns against the file's own schema;
ordinary reads and `select *` are unaffected. The BVT pins this
boundary.
- **Constraint violations at the destination.** Error mode reports what
the *scan* could not parse; an `insert ... select` that violates a
primary key still fails the statement.
- **A record too damaged to delimit.** Tolerance is per record, and a
record is whatever the CSV parser delimits — an unbalanced quote
swallows the rest of the file into one record, reported as one failure.

Design notes: `docs/design/external_table_error_mode.md`.

## Tests

| Level | What it proves |
|---|---|
| `pkg/sql/util/csvparser` `TestRecordLine` | one record per line, a
multi-line quoted record reporting its first line, exactness across a
small read block, blank lines still counted |
| `pkg/sql/colexec/external` `error_mode_test.go` | the switch (error
columns tolerate, `__mo_file_line` alone does not, a lookalike user
column does not), a pruned scan failing exactly as before, and CSV /
JSONLINE / Kafka each reporting a bad record with its position, message
and source text while neighbouring records are unaffected |
| `pkg/sql/plan` `TestExternalScanTolerates` | the pruning rule is
driven by the two error columns only, keyed on column id |
| BVT `table/external_table_error_mode` | end to end: hidden from
`select *`/`desc`/`show create table`, the same bad record found
regardless of which user columns are projected, the good/rejects split
loaded into real tables, multi-line records, blank lines, an
unterminated object, the parquet boundary, and the reserved names
refused by DDL |

Local validation: `pkg/catalog`, `pkg/sql/colexec/external`,
`pkg/sql/util/csvparser` green; `pkg/sql/plan` green apart from
`TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp`,
which reproduces on a clean `origin/main` worktree (timezone-dependent,
unrelated). BVT: error-mode 45/45, `load_data` 1032/1032, `datastream`
111/111.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…ssage / __mo_error_text (matrixorigin#27517) (matrixorigin#27609)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [x] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27517

## What this PR does / why we need it:

A scan of an external table fails the whole statement on the first
record it cannot parse. One bad line in a million-line file means no
result at all, and no way to find out which line it was without reading
the file by hand.

This adds an **error mode**: a bad record becomes a *row* instead of a
*failure*. It is switched on by asking for it — by selecting one of two
columns the query would otherwise not mention.

### The columns

Three hidden columns exist on every text-backed external table
(`EXTERNAL`, `KAFKA`, `DATASTREAM`, foreign). They do not appear in
`select *`, `desc`, or `show create table`, and their names are reserved
so a user table cannot declare them.

| Column | Type | Meaning |
|---|---|---|
| `__mo_file_line` | `bigint` | the physical line the record starts on
(`NULL` for Kafka, which has no lines) |
| `__mo_error_message` | `varchar` | why the record failed, `NULL` if it
parsed |
| `__mo_error_text` | `varchar` | the record as written in the source,
`NULL` if it parsed |

```sql
create external table t (a int, s varchar(20))
  infile{'filepath'='/data/rows.csv'};

-- unchanged: fails on the first bad record
select * from t;

-- reports them instead
select a, s, __mo_file_line, __mo_error_message, __mo_error_text from t;

-- the two halves of a load
insert into good    select a, s from t where __mo_error_message is null;
insert into rejects select __mo_file_line, __mo_error_message, __mo_error_text from t
                    where __mo_error_message is not null;
```

On a failed row every user column is `NULL` — including one that
happened to convert before the failure, because the record is not
trustworthy — while every column the scan *synthesizes* keeps its value:
`__mo_filepath`, `__mo_file_line`, and the Kafka metadata columns. Those
are what let a user find the record again.

### What switches it on

`__mo_error_message` and `__mo_error_text` turn tolerance on.
`__mo_file_line` deliberately does **not**: it is position metadata, and
per the issue a query that only wants line numbers must still fail on a
bad record. The decision is made once per scan in
`resolveExternalErrorMode`, from the attribute list the operator was
given — column pruning has already run, so a query that does not mention
the columns takes the historical path with no per-row test to pay for.
It is keyed on the reserved column ids, not the names.

**Pruning had to be taught one thing.** Whether a record failed is a
property of the record, not of the projection. With the user columns
pruned away nothing is converted, so nothing fails, and `select
__mo_error_message from t` — the query that asks which records failed —
answered "none". An external scan that keeps an error column now keeps
every record-backed column through pruning; the scan's own `ProjectList`
still projects only the referenced ones, so the cost falls only on
queries that asked.

### Where it is implemented

Two places produce the error columns, one per text format, shared by
every engine that reads text — which is all of them except Parquet and
Iceberg:

```
                    ┌──────────────── CsvReader.makeBatchRows ─────────────────┐
file / datastream ─►│ csvparser.Read ─► [JSONLINE: transJson2Lines] ─► getOneRowData │
foreign scan ──────►└──────────────────────────────────────────────────────────┘
kafka ────────────► KafkaReader.ReadBatch ─► parseOneMessage ─► getOneRowData
```

`getOneRowData` is the single conversion site: under tolerance it
snapshots every vector's length, and on failure rolls back and emits the
replacement row through `appendErrorRow`, which fills the synthesized
columns through the ordinary column path so they are typed as the
catalog declares them. Datastream and foreign scans need no code of
their own — they read through the same `CsvReader`.

Line numbers live in the parser: `lineNo` counts newline bytes,
`readRecord` snapshots it at the record's **first content byte**, and
`RecordLine()` returns it 1-based. So a CSV record with a quoted field
spanning lines 5-7 reports 5 and the next reports 8, and a record after
a blank line reports its own line.

### Three latent JSONLINE defects this uncovered

All predate this PR and are fixed here:

1. **The synthesized columns were matched against JSON object keys**, so
with the error columns projected *every* record — valid ones included —
failed with "the table column is larger than input data column".
2. **A malformed line was glued onto the next one.** A failed parse was
held over in `prevStr` to be completed by the following line, and
`bytejson` reports a bare word (`this is not json`) as an unexpected EOF
exactly as it reports a truncated object. Text is now held over only
when the parser ran off the end *and* the text opens the expected value;
anything else is a malformed record and says so. Text held over that the
file never completes is reported at EOF rather than dropped.
3. **The batch tail was trimmed by one row on every held-over record.**
That compensated for rows being written into pre-allocated slots, which
is how the reader worked in 2023 (matrixorigin#7493); rows are appended now, so the
trim silently discarded a complete row.

### Not covered

- **Parquet and Iceberg** decode typed columnar values, not text: there
is no line and no per-record text. Naming an error column on such a
table is refused at bind time (`column __mo_error_message not found`),
since those readers resolve columns against the file's own schema;
ordinary reads and `select *` are unaffected. The BVT pins this
boundary.
- **Constraint violations at the destination.** Error mode reports what
the *scan* could not parse; an `insert ... select` that violates a
primary key still fails the statement.
- **A record too damaged to delimit.** Tolerance is per record, and a
record is whatever the CSV parser delimits — an unbalanced quote
swallows the rest of the file into one record, reported as one failure.

Design notes: `docs/design/external_table_error_mode.md`.

## Tests

| Level | What it proves |
|---|---|
| `pkg/sql/util/csvparser` `TestRecordLine` | one record per line, a
multi-line quoted record reporting its first line, exactness across a
small read block, blank lines still counted |
| `pkg/sql/colexec/external` `error_mode_test.go` | the switch (error
columns tolerate, `__mo_file_line` alone does not, a lookalike user
column does not), a pruned scan failing exactly as before, and CSV /
JSONLINE / Kafka each reporting a bad record with its position, message
and source text while neighbouring records are unaffected |
| `pkg/sql/plan` `TestExternalScanTolerates` | the pruning rule is
driven by the two error columns only, keyed on column id |
| BVT `table/external_table_error_mode` | end to end: hidden from
`select *`/`desc`/`show create table`, the same bad record found
regardless of which user columns are projected, the good/rejects split
loaded into real tables, multi-line records, blank lines, an
unterminated object, the parquet boundary, and the reserved names
refused by DDL |

Local validation: `pkg/catalog`, `pkg/sql/colexec/external`,
`pkg/sql/util/csvparser` green; `pkg/sql/plan` green apart from
`TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp`,
which reproduces on a clean `origin/main` worktree (timezone-dependent,
unrelated). BVT: error-mode 45/45, `load_data` 1032/1032, `datastream`
111/111.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…ssage / __mo_error_text (matrixorigin#27517) (matrixorigin#27609)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [x] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27517

## What this PR does / why we need it:

A scan of an external table fails the whole statement on the first
record it cannot parse. One bad line in a million-line file means no
result at all, and no way to find out which line it was without reading
the file by hand.

This adds an **error mode**: a bad record becomes a *row* instead of a
*failure*. It is switched on by asking for it — by selecting one of two
columns the query would otherwise not mention.

### The columns

Three hidden columns exist on every text-backed external table
(`EXTERNAL`, `KAFKA`, `DATASTREAM`, foreign). They do not appear in
`select *`, `desc`, or `show create table`, and their names are reserved
so a user table cannot declare them.

| Column | Type | Meaning |
|---|---|---|
| `__mo_file_line` | `bigint` | the physical line the record starts on
(`NULL` for Kafka, which has no lines) |
| `__mo_error_message` | `varchar` | why the record failed, `NULL` if it
parsed |
| `__mo_error_text` | `varchar` | the record as written in the source,
`NULL` if it parsed |

```sql
create external table t (a int, s varchar(20))
  infile{'filepath'='/data/rows.csv'};

-- unchanged: fails on the first bad record
select * from t;

-- reports them instead
select a, s, __mo_file_line, __mo_error_message, __mo_error_text from t;

-- the two halves of a load
insert into good    select a, s from t where __mo_error_message is null;
insert into rejects select __mo_file_line, __mo_error_message, __mo_error_text from t
                    where __mo_error_message is not null;
```

On a failed row every user column is `NULL` — including one that
happened to convert before the failure, because the record is not
trustworthy — while every column the scan *synthesizes* keeps its value:
`__mo_filepath`, `__mo_file_line`, and the Kafka metadata columns. Those
are what let a user find the record again.

### What switches it on

`__mo_error_message` and `__mo_error_text` turn tolerance on.
`__mo_file_line` deliberately does **not**: it is position metadata, and
per the issue a query that only wants line numbers must still fail on a
bad record. The decision is made once per scan in
`resolveExternalErrorMode`, from the attribute list the operator was
given — column pruning has already run, so a query that does not mention
the columns takes the historical path with no per-row test to pay for.
It is keyed on the reserved column ids, not the names.

**Pruning had to be taught one thing.** Whether a record failed is a
property of the record, not of the projection. With the user columns
pruned away nothing is converted, so nothing fails, and `select
__mo_error_message from t` — the query that asks which records failed —
answered "none". An external scan that keeps an error column now keeps
every record-backed column through pruning; the scan's own `ProjectList`
still projects only the referenced ones, so the cost falls only on
queries that asked.

### Where it is implemented

Two places produce the error columns, one per text format, shared by
every engine that reads text — which is all of them except Parquet and
Iceberg:

```
                    ┌──────────────── CsvReader.makeBatchRows ─────────────────┐
file / datastream ─►│ csvparser.Read ─► [JSONLINE: transJson2Lines] ─► getOneRowData │
foreign scan ──────►└──────────────────────────────────────────────────────────┘
kafka ────────────► KafkaReader.ReadBatch ─► parseOneMessage ─► getOneRowData
```

`getOneRowData` is the single conversion site: under tolerance it
snapshots every vector's length, and on failure rolls back and emits the
replacement row through `appendErrorRow`, which fills the synthesized
columns through the ordinary column path so they are typed as the
catalog declares them. Datastream and foreign scans need no code of
their own — they read through the same `CsvReader`.

Line numbers live in the parser: `lineNo` counts newline bytes,
`readRecord` snapshots it at the record's **first content byte**, and
`RecordLine()` returns it 1-based. So a CSV record with a quoted field
spanning lines 5-7 reports 5 and the next reports 8, and a record after
a blank line reports its own line.

### Three latent JSONLINE defects this uncovered

All predate this PR and are fixed here:

1. **The synthesized columns were matched against JSON object keys**, so
with the error columns projected *every* record — valid ones included —
failed with "the table column is larger than input data column".
2. **A malformed line was glued onto the next one.** A failed parse was
held over in `prevStr` to be completed by the following line, and
`bytejson` reports a bare word (`this is not json`) as an unexpected EOF
exactly as it reports a truncated object. Text is now held over only
when the parser ran off the end *and* the text opens the expected value;
anything else is a malformed record and says so. Text held over that the
file never completes is reported at EOF rather than dropped.
3. **The batch tail was trimmed by one row on every held-over record.**
That compensated for rows being written into pre-allocated slots, which
is how the reader worked in 2023 (matrixorigin#7493); rows are appended now, so the
trim silently discarded a complete row.

### Not covered

- **Parquet and Iceberg** decode typed columnar values, not text: there
is no line and no per-record text. Naming an error column on such a
table is refused at bind time (`column __mo_error_message not found`),
since those readers resolve columns against the file's own schema;
ordinary reads and `select *` are unaffected. The BVT pins this
boundary.
- **Constraint violations at the destination.** Error mode reports what
the *scan* could not parse; an `insert ... select` that violates a
primary key still fails the statement.
- **A record too damaged to delimit.** Tolerance is per record, and a
record is whatever the CSV parser delimits — an unbalanced quote
swallows the rest of the file into one record, reported as one failure.

Design notes: `docs/design/external_table_error_mode.md`.

## Tests

| Level | What it proves |
|---|---|
| `pkg/sql/util/csvparser` `TestRecordLine` | one record per line, a
multi-line quoted record reporting its first line, exactness across a
small read block, blank lines still counted |
| `pkg/sql/colexec/external` `error_mode_test.go` | the switch (error
columns tolerate, `__mo_file_line` alone does not, a lookalike user
column does not), a pruned scan failing exactly as before, and CSV /
JSONLINE / Kafka each reporting a bad record with its position, message
and source text while neighbouring records are unaffected |
| `pkg/sql/plan` `TestExternalScanTolerates` | the pruning rule is
driven by the two error columns only, keyed on column id |
| BVT `table/external_table_error_mode` | end to end: hidden from
`select *`/`desc`/`show create table`, the same bad record found
regardless of which user columns are projected, the good/rejects split
loaded into real tables, multi-line records, blank lines, an
unterminated object, the parquet boundary, and the reserved names
refused by DDL |

Local validation: `pkg/catalog`, `pkg/sql/colexec/external`,
`pkg/sql/util/csvparser` green; `pkg/sql/plan` green apart from
`TestBuildCreateOrReplaceViewRejectsRecursiveDefinition/future_AS_OF_timestamp`,
which reproduces on a clean `origin/main` worktree (timezone-dependent,
unrelated). BVT: error-mode 45/45, `load_data` 1032/1032, `datastream`
111/111.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants