jk-shah commented on code in PR #40166:
URL: https://github.com/apache/beam/pull/40166#discussion_r4646360341


##########
sdks/go/pkg/beam/io/postgresio/write.go:
##########
@@ -0,0 +1,1631 @@
+// 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.
+
+package postgresio
+
+import (
+       "context"
+       "database/sql"
+       "encoding/json"
+       "errors"
+       "fmt"
+       "hash/fnv"
+       "math/rand"
+       "reflect"
+       "strings"
+       "time"
+       "unicode"
+
+       "github.com/apache/beam/sdks/v2/go/pkg/beam"
+       "github.com/apache/beam/sdks/v2/go/pkg/beam/log"
+       "github.com/lib/pq"
+)
+
+var (
+       sinkWrittenRows     = beam.NewCounter("postgresio", "sink_written_rows")
+       sinkFailedRows      = beam.NewCounter("postgresio", "sink_failed_rows")
+       sinkDeadlockRetries = beam.NewCounter("postgresio", 
"sink_deadlock_retries")
+)
+
+func init() {
+       beam.RegisterDoFn(&writeFn{})
+       beam.RegisterCoder(
+               reflect.TypeOf((*FailedRow)(nil)).Elem(),
+               encodeFailedRow,
+               decodeFailedRow,
+       )
+}
+
+func encodeFailedRow(in FailedRow) ([]byte, error) {
+       return json.Marshal(in)
+}
+
+func decodeFailedRow(in []byte) (FailedRow, error) {
+       var out FailedRow
+       err := json.Unmarshal(in, &out)
+       return out, err
+}
+
+// FailedRow captures a rejected record with sanitized diagnostic error 
information
+// for routing to a Dead-Letter Queue (DLQ).
+type FailedRow struct {
+       Row          any    `json:"row"`
+       ErrorMessage string `json:"error_message"`
+       SqlState     string `json:"sql_state"`
+}
+
+// WriteResult encapsulates the output PCollections produced by the Write 
transform:
+// SuccessfulRows contains all committed records; FailedRows contains 
dead-letter records.
+type WriteResult struct {
+       SuccessfulRows beam.PCollection
+       FailedRows     beam.PCollection
+}
+
+// Write writes elements from an input PCollection to a target PostgreSQL 
table using
+// parameterized array upserts, in-memory deduplication, and deadlock 
mitigation sorting.
+func Write(s beam.Scope, table string, opts WriteOptions, col 
beam.PCollection) WriteResult {
+       s = s.Scope("postgresio.Write")
+
+       // The write path pins search_path to pg_catalog,pg_temp on every pooled
+       // connection to close CVE-2018-1058, so an unqualified name cannot 
resolve
+       // to a user table. Rejecting it here turns a runtime "relation does not
+       // exist" surfacing from a distributed worker into a pipeline 
construction
+       // error that names the fix.
+       if !strings.Contains(table, ".") {
+               panic(fmt.Sprintf("postgresio.Write: table name %q must be 
schema-qualified, for example %q. "+
+                       "Every connection in the write pool pins search_path to 
pg_catalog,pg_temp to close "+
+                       "CVE-2018-1058, so an unqualified name does not resolve 
to a user table.",
+                       table, "public."+table))
+       }
+
+       sanitizedTable, err := SanitizeTableIdentifier(table)
+       if err != nil {
+               panic(fmt.Sprintf("postgresio.Write: invalid table name %q: 
%v", table, err))
+       }
+
+       // Upsert and MERGE both resolve conflicts through the primary key. 
With no
+       // key, the upsert degrades to ON CONFLICT DO NOTHING and MERGE has no 
join
+       // condition, so conflicting rows are dropped -- the exact opposite of 
what
+       // both modes promise. Nothing downstream can detect this: the pipeline
+       // reports success and the rows are simply absent.
+       if (opts.WriteMode == WriteModeUpsert || opts.WriteMode == 
WriteModeMerge) && len(opts.PrimaryKeyCols) == 0 {
+               panic(fmt.Sprintf("postgresio.Write: write mode %v requires 
primary key columns (PrimaryKeyCols); "+
+                       "without them conflicting rows are silently discarded 
rather than merged. "+
+                       "Set PrimaryKeyCols, or use WriteModeInsert if plain 
inserts are intended.", opts.WriteMode))
+       }
+
+       if opts.WriteMode == WriteModeUpdate && len(opts.PrimaryKeyCols) == 0 {
+               panic("postgresio.Write: WriteModeUpdate requires primary key 
columns (PrimaryKeyCols)")
+       }
+
+       // Connection identity is checked here rather than left to the worker. A
+       // missing host or database otherwise fails inside Setup on a 
distributed
+       // runner, long after submission, as a libpq connection error that names
+       // neither the option that was left empty nor the transform that needed 
it.
+       if opts.Host == "" {
+               panic("postgresio.Write: Host must be set. For a Unix domain 
socket, set Host to the " +
+                       "socket directory, for example \"/var/run/postgresql\"; 
libpq's compiled-in default is " +
+                       "not assumed because it differs between distributions 
and container images")
+       }
+       if opts.Database == "" {
+               panic("postgresio.Write: Database must be set. libpq would 
otherwise default it to the " +
+                       "username, which is rarely the intended target")
+       }
+
+       // validateSSLMode already guards the CDC and option-builder paths. 
Applying
+       // it to the effective value here closes the gap for callers that build
+       // WriteOptions as a struct literal and bypass NewWriteOptions, so a 
typo
+       // such as "verify_full" is rejected at construction instead of at 
connect
+       // time on every worker.
+       effectiveSSLMode := opts.SSLMode
+       if effectiveSSLMode == "" {
+               effectiveSSLMode = DefaultSSLMode
+       }
+       if err := validateSSLMode(effectiveSSLMode); err != nil {
+               panic(fmt.Sprintf("postgresio.Write: %v", err))
+       }
+
+       // MERGE is only expressible through the staged COPY path, and PgBouncer
+       // compatibility forces the parameterized path because transaction 
pooling
+       // cannot keep a session-scoped staging table alive between flushes. The
+       // two cannot both be satisfied, so the conflict is reported here rather
+       // than as a first-flush failure on every worker.
+       if opts.WriteMode == WriteModeMerge && opts.UsePgBouncer {
+               panic("postgresio.Write: WriteModeMerge cannot be combined with 
PgBouncer compatibility. " +
+                       "MERGE is issued through the staged COPY path, which 
reuses a session-scoped staging table, " +
+                       "and transaction pooling cannot guarantee that table is 
present on the connection a later " +
+                       "flush lands on. Connect directly to PostgreSQL, or use 
a session-pooling PgBouncer mode.")
+       }
+
+       // Checked here as well as in WithReplicationOriginName, because the
+       // cross-language SchemaTransform assigns the field directly and never
+       // passes through the option.
+       if opts.ReplicationOriginName != "" && 
!originNameRegex.MatchString(opts.ReplicationOriginName) {
+               panic(fmt.Sprintf("postgresio.Write: invalid replication origin 
name %q (must match %s)",
+                       opts.ReplicationOriginName, originNameRegex.String()))
+       }
+
+       // A replication origin is selected on the session. Under transaction
+       // pooling a later statement can be routed to a server connection that
+       // never selected it, so some writes would go out unstamped and a
+       // bidirectional peer would replay exactly those back -- intermittently,
+       // which is worse than not working at all.
+       if opts.ReplicationOriginName != "" && opts.UsePgBouncer {
+               panic("postgresio.Write: WithReplicationOriginName cannot be 
combined with PgBouncer " +
+                       "compatibility. Selecting a replication origin is 
session state, and transaction pooling " +
+                       "cannot guarantee a later statement runs on a 
connection that selected it, so writes would " +
+                       "be stamped intermittently. Connect directly to 
PostgreSQL, or use a session-pooling " +
+                       "PgBouncer mode.")
+       }
+
+       // Recorded here, in the submitting process, because this is the last 
point
+       // at which the closure is observable. Setup runs on the worker, where a
+       // dropped DialFunc and an unconfigured one are otherwise 
indistinguishable.
+       opts.RequiresDialFunc = opts.DialFunc != nil
+
+       // UpdateFields only reaches SQL through the two SET clauses: the 
upsert's
+       // ON CONFLICT DO UPDATE and the update's UPDATE ... SET. Insert has no 
SET
+       // clause, and MERGE builds its own from the primary key and the 
operation
+       // column, so under either mode the option is read by nothing. 
Accepting it
+       // silently would let a pipeline that intends to restrict which columns 
are
+       // overwritten run as though it had said nothing at all.
+       if len(opts.UpdateFields) > 0 &&
+               opts.WriteMode != WriteModeUpsert && opts.WriteMode != 
WriteModeUpdate {
+               panic(fmt.Sprintf("postgresio.Write: UpdateFields is only 
honored by WriteModeUpsert and "+
+                       "WriteModeUpdate, but write mode is %v, which would 
ignore it. Remove WithUpdateFields, "+
+                       "or select a write mode that has a SET clause to 
restrict.", opts.WriteMode))
+       }
+
+       elemType := col.Type().Type()
+
+       // Checked against the element type rather than the live table because 
the
+       // table is not reachable from the submitting process. Every column the
+       // writer can emit is derived from this type, so a name that is not in 
it
+       // cannot be written whatever the table looks like.
+       if err := validateUpdateFields(opts.UpdateFields, 
structColumns(elemType)); err != nil {
+               panic(fmt.Sprintf("postgresio.Write: %v", err))
+       }
+
+       fn := &writeFn{
+               Table:          sanitizedTable,
+               Options:        opts,
+               Type:           beam.EncodedType{T: elemType},
+               PrimaryKeyCols: opts.PrimaryKeyCols,
+       }
+
+       success, failed := beam.ParDo2(s, fn, col)
+
+       return WriteResult{
+               SuccessfulRows: success,
+               FailedRows:     failed,
+       }
+}
+
+// buildWriteDSN renders the libpq keyword/value connection string for the 
sink.
+//
+// search_path is pinned in the DSN rather than issued as a later SET so that
+// every connection the pool opens is isolated from CVE-2018-1058, including
+// connections created when a pool member is recycled mid-bundle. Its value is
+// a compile-time literal rather than configuration, so it is left unquoted.
+//
+// Every value that can originate from configuration is quoted, because an
+// unquoted value ends at the first space and libpq reads the remainder as
+// further keywords. Quoting keeps a credential that legitimately contains a
+// space intact, and stops any configured value from introducing a keyword the
+// caller never set.
+//
+// Keyword order is load-bearing as a second layer of defence. libpq lets a
+// later duplicate keyword win, so the two settings that carry the security
+// properties, sslmode and the pinned search_path, are emitted last and cannot
+// be displaced by anything injected from an earlier value. If a custom
+// sslrootcert is supplied, it is emitted before sslmode so sslmode still
+// governs transport security.
+func buildWriteDSN(host string, port int, database, username, password, 
sslMode, sslRootCert string) string {
+       var rootCertClause string
+       if strings.TrimSpace(sslRootCert) != "" {
+               rootCertClause = fmt.Sprintf(" sslrootcert=%s", 
quoteDSNValue(sslRootCert))
+       }
+       return fmt.Sprintf("host=%s port=%d dbname=%s user=%s password=%s%s 
sslmode=%s search_path=pg_catalog,pg_temp",
+               quoteDSNValue(host), port, quoteDSNValue(database),
+               quoteDSNValue(username), quoteDSNValue(password), 
rootCertClause, quoteDSNValue(sslMode))
+}
+
+type writeFn struct {
+       Table          string           `json:"table"`
+       Options        WriteOptions     `json:"options"`
+       Type           beam.EncodedType `json:"type"`
+       PrimaryKeyCols []string         `json:"primary_key_cols"`
+
+       db        *sql.DB
+       compactor *BatchCompactor
+       columns   []string
+       colTypes  map[string]string
+       workerID  string
+}
+
+func (fn *writeFn) Setup(ctx context.Context) error {
+       fn.workerID = fmt.Sprintf("%016x", rand.Uint64())
+
+       if fn.Options.WriteMode == WriteModeUpdate && len(fn.PrimaryKeyCols) == 
0 {
+               return fmt.Errorf("postgresio: WriteModeUpdate requires primary 
key columns (PrimaryKeyCols)")
+       }
+
+       // A configured dialer that arrives nil was dropped crossing the
+       // serialization boundary.
+       if fn.Options.RequiresDialFunc && fn.Options.DialFunc == nil {
+               return errDialFuncLost()
+       }
+
+       sslMode := fn.Options.SSLMode
+       if sslMode == "" {
+               sslMode = DefaultSSLMode
+       }
+       if err := validateSSLMode(sslMode); err != nil {
+               return fmt.Errorf("postgresio: invalid sslmode: %w", err)
+       }
+       password := fn.Options.ResolvePassword()
+       dsn := buildWriteDSN(fn.Options.Host, fn.Options.Port, 
fn.Options.Database,
+               fn.Options.Username, password, sslMode, fn.Options.SSLRootCert)
+
+       connector := &pqConnector{
+               dialFunc:          fn.Options.DialFunc,
+               dsn:               dsn,
+               initSQL:           fn.Options.ConnectionInitSQL,
+               replicationOrigin: fn.Options.ReplicationOriginName,
+       }
+       db := sql.OpenDB(connector)
+
+       // Clamp worker pool connections to prevent connection storms across 
distributed workers
+       maxConns := fn.Options.MaxConnections
+       if maxConns <= 0 {
+               maxConns = 2
+       }
+       db.SetMaxOpenConns(maxConns)
+       db.SetMaxIdleConns(maxConns)
+       db.SetConnMaxLifetime(30 * time.Minute)
+
+       fn.applyPgBouncerCompatibility(ctx)
+
+       fn.db = db
+       fn.compactor = NewBatchCompactor(fn.Options.BatchSize, 
fn.Options.MaxBatchBytes, fn.Options.FlushInterval)
+       fn.inspectColumns(fn.Type.T)
+
+       // Write already rejects this at construction. Repeating it here covers 
a
+       // writeFn assembled directly, and costs one pass over a slice that is
+       // almost always empty. Failing in Setup still beats failing at flush: 
the
+       // batch that would carry the bad identifier has not been accumulated 
yet.
+       if err := validateUpdateFields(fn.Options.UpdateFields, fn.columns); 
err != nil {
+               return fmt.Errorf("postgresio: %w", err)
+       }
+
+       if err := fn.inspectColumnTypes(ctx); err != nil {
+               return err
+       }
+
+       return nil
+}
+
+// applyPgBouncerCompatibility adjusts the write path so it holds no session
+// state, which is the only way it can survive transaction pooling.
+//
+// PgBouncer in transaction pooling mode hands each transaction whichever
+// server connection is free, so nothing that lives in a session survives
+// between them.
+//
+// The staged-COPY path depends on exactly that: it creates a temporary staging
+// table once and reuses it across flushes, deliberately, to keep per-batch DDL
+// out of the catalogs. Under transaction pooling a later flush can arrive on a
+// connection where that table was never created, so the method is downgraded
+// to the parameterized path. This is what the option is for; it previously set
+// a field nothing read.
+func (fn *writeFn) applyPgBouncerCompatibility(ctx context.Context) {
+       if !fn.Options.UsePgBouncer {
+               return
+       }
+       if fn.Options.WriteMethod == WriteMethodStagedCopy {
+               log.Warnf(ctx, "postgresio: PgBouncer compatibility is enabled, 
so the staged COPY write method "+
+                       "has been downgraded to the parameterized UNNEST path. 
Staged COPY reuses a session-scoped "+
+                       "staging table, which transaction pooling cannot 
guarantee is present on the connection a "+
+                       "later flush lands on.")
+               fn.Options.WriteMethod = WriteMethodUnnest
+       }
+       if fn.Options.ConnectionInitSQL != "" {
+               log.Warnf(ctx, "postgresio: ConnectionInitSQL is set alongside 
PgBouncer compatibility. It runs "+
+                       "when a pooled connection is opened, but transaction 
pooling may route a later statement to "+
+                       "a different server connection that never ran it, so 
session-level settings apply "+
+                       "inconsistently. Prefer values that can be set as 
connection parameters.")
+       }
+}
+
+// columnTagKeys are the struct tags consulted for a column name, in priority
+// order. db is checked first because it names a database column specifically,
+// where json also governs unrelated HTTP encoding.
+var columnTagKeys = []string{"db", "beam", "json"}
+
+// columnNameFromTag returns the column name a struct tag declares, whether the
+// field is explicitly excluded, and whether the tag named anything at all.
+//
+// Tag values carry options after a comma -- `json:"customer_id,omitempty"` is
+// the common one. The whole value used to be taken as the column name, which
+// produced a column literally named `customer_id,omitempty`; 
SanitizeIdentifier
+// then rejected it with an error that pointed at the sanitizer rather than at
+// the tag.
+//
+// A name of "-" means the field is not a column. That is the standard
+// convention for these tags and previously produced a column named "-".
+func columnNameFromTag(tag string) (name string, excluded bool, ok bool) {
+       if tag == "" {
+               return "", false, false
+       }
+       name, _, _ = strings.Cut(tag, ",")
+       switch name {
+       case "":
+               // An options-only tag such as `json:",omitempty"` names 
nothing; fall
+               // through to the next tag or to the field name.
+               return "", false, false
+       case "-":
+               return "", true, true
+       }
+       return name, false, true
+}
+
+// fieldTagNames returns the set of column names a field's tags declare.
+//
+// resolveColumn matches a column against a field by tag, and has to read those
+// tags exactly as inspectColumns did when it derived the column name. 
Comparing
+// the raw tag value instead meant a field tagged 
`json:"customer_id,omitempty"`
+// never matched the column `customer_id` that was derived from it, so the
+// value read as absent and the column was written NULL.
+func fieldTagNames(fld reflect.StructField) map[string]bool {
+       names := make(map[string]bool, len(columnTagKeys))
+       for _, key := range columnTagKeys {
+               if name, excluded, ok := columnNameFromTag(fld.Tag.Get(key)); 
ok && !excluded {
+                       names[name] = true
+               }
+       }
+       return names
+}
+
+// toSnakeCase converts a Go field name to the snake_case spelling PostgreSQL
+// columns conventionally use.
+//
+// Lowercasing alone mapped CustomerID to "customerid", which matches no real
+// column, so every untagged multi-word field silently produced a name the
+// server would reject. Consecutive capitals are treated as one acronym, so
+// CustomerID becomes customer_id rather than customer_i_d, and HTTPServer
+// becomes http_server.
+func toSnakeCase(name string) string {
+       runes := []rune(name)
+
+       var b strings.Builder
+       b.Grow(len(runes) + 4)
+
+       for i, r := range runes {
+               if !unicode.IsUpper(r) {
+                       b.WriteRune(r)
+                       continue
+               }
+               // A boundary exists where a lowercase run ends (userID -> 
user_id) or
+               // where an acronym run ends and a new word begins (HTTPServer 
->
+               // http_server).
+               endsLowerRun := i > 0 && (unicode.IsLower(runes[i-1]) || 
unicode.IsDigit(runes[i-1]))
+               startsNewWord := i > 0 && i+1 < len(runes) && 
unicode.IsLower(runes[i+1])
+               if endsLowerRun || startsNewWord {
+                       b.WriteByte('_')
+               }
+               b.WriteRune(unicode.ToLower(r))
+       }
+       return b.String()
+}
+
+func (fn *writeFn) inspectColumns(t reflect.Type) {
+       fn.columns = structColumns(t)
+}
+
+// structColumns derives the ordered list of PostgreSQL column names an element
+// type maps to, using the same tag precedence and snake_case fallback the
+// writer uses when it builds SQL.
+//
+// It is package level rather than a writeFn method so that Write can resolve
+// the columns in the submitting process, before any writeFn exists, and reject
+// a configuration that names a column the element type does not carry.
+// A type that is not a struct yields no columns.
+func structColumns(t reflect.Type) []string {
+       if t == nil {
+               return nil
+       }
+       if t.Kind() == reflect.Ptr {
+               t = t.Elem()
+       }
+       if t.Kind() != reflect.Struct {
+               return nil
+       }
+
+       columns := make([]string, 0, t.NumField())
+       for i := 0; i < t.NumField(); i++ {
+               field := t.Field(i)
+               if !field.IsExported() {
+                       continue
+               }
+
+               var colName string
+               var excluded, tagged bool
+               for _, key := range columnTagKeys {
+                       colName, excluded, tagged = 
columnNameFromTag(field.Tag.Get(key))
+                       if tagged {
+                               break
+                       }
+               }
+               if excluded {
+                       continue
+               }
+               if !tagged {
+                       colName = toSnakeCase(field.Name)
+               }
+               columns = append(columns, colName)
+       }
+       return columns
+}
+
+// validateUpdateFields reports a configuration error when UpdateFields names a
+// column the element type does not carry.
+//
+// UpdateFields is matched against resolved column names exactly and
+// case-sensitively, unlike the primary key lookup in ExtractPrimaryKeys, which
+// falls back to a case-insensitive match. A name that resolves to nothing is
+// not inert: on the upsert path it is emitted verbatim into
+// ON CONFLICT DO UPDATE SET, so PostgreSQL rejects the whole batch at flush
+// time with `column "emial" of relation "orders" does not exist`, and on the
+// update path it is silently dropped from the SET clause, so the column the
+// caller meant to write is never written at all. Both surface long after
+// submission, on a worker, which is why this runs at construction.
+//
+// An empty columns slice means the element type is not a struct, so there is
+// nothing to check against.
+func validateUpdateFields(updateFields, columns []string) error {
+       if len(updateFields) == 0 || len(columns) == 0 {
+               return nil
+       }
+
+       known := make(map[string]string, len(columns)) // lowercase -> canonical
+       exact := make(map[string]bool, len(columns))
+       for _, col := range columns {
+               exact[col] = true
+               lower := strings.ToLower(col)
+               if _, seen := known[lower]; !seen {
+                       known[lower] = col
+               }
+       }
+
+       for _, f := range updateFields {
+               if exact[f] {
+                       continue
+               }
+               if canonical, ok := known[strings.ToLower(f)]; ok {
+                       return fmt.Errorf("update field %q does not match any 
column of the input type; "+
+                               "matching is exact and case-sensitive, and the 
type declares %q. "+
+                               "Known columns: %s", f, canonical, 
strings.Join(columns, ", "))
+               }
+               return fmt.Errorf("update field %q does not match any column of 
the input type. "+
+                       "Column names come from the db, beam, or json struct 
tag, or from the snake_case "+
+                       "form of the field name. Known columns: %s", f, 
strings.Join(columns, ", "))
+       }
+       return nil
+}
+
+func (fn *writeFn) inspectColumnTypes(ctx context.Context) error {
+       rows, err := fn.db.QueryContext(ctx, fmt.Sprintf("SELECT * FROM %s 
LIMIT 0", fn.Table))
+       if err != nil {
+               return fmt.Errorf("postgresio: failed to query target table 
types: %w", err)
+       }
+       defer rows.Close()
+
+       ctypes, err := rows.ColumnTypes()
+       if err != nil {
+               return fmt.Errorf("postgresio: failed to read column types: 
%w", err)
+       }
+
+       fn.colTypes = make(map[string]string)
+       for _, ct := range ctypes {
+               fn.colTypes[ct.Name()] = ct.DatabaseTypeName()
+       }
+       return nil
+}
+
+func (fn *writeFn) StartBundle(ctx context.Context, emitSuccess func(beam.X), 
emitFailed func(FailedRow)) error {
+       fn.compactor = NewBatchCompactor(fn.Options.BatchSize, 
fn.Options.MaxBatchBytes, fn.Options.FlushInterval)
+       return nil
+}
+
+func (fn *writeFn) ProcessElement(ctx context.Context, elem beam.X, 
emitSuccess func(beam.X), emitFailed func(FailedRow)) error {
+       entityKey, sortKey := ExtractPrimaryKeys(elem, fn.PrimaryKeyCols)
+       fn.compactor.Add(entityKey, sortKey, elem, estimateElementSize(elem))
+
+       if fn.compactor.ShouldFlush() {
+               return fn.flushBatch(ctx, emitSuccess, emitFailed)
+       }
+       return nil
+}
+
+func (fn *writeFn) FinishBundle(ctx context.Context, emitSuccess func(beam.X), 
emitFailed func(FailedRow)) error {
+       if fn.compactor.Len() > 0 {
+               return fn.flushBatch(ctx, emitSuccess, emitFailed)
+       }
+       return nil
+}
+
+func (fn *writeFn) Teardown() {
+       if fn.db != nil {
+               _ = fn.db.Close()
+       }
+}
+
+func (fn *writeFn) flushBatch(ctx context.Context, emitSuccess func(beam.X), 
emitFailed func(FailedRow)) error {
+       batch := fn.compactor.CompactAndSort()
+       if len(batch) == 0 {
+               return nil
+       }
+
+       // Rows in one batch may carry different column sets: a CDC UPDATE omits
+       // columns whose TOASTed values the server did not retransmit. A single
+       // statement can only name one column list, so the batch is grouped by 
the
+       // set of columns present and each group written separately.
+       parts, err := partitionBatchByUnchangedColumns(batch, fn.columns)
+       if err != nil {
+               // A row type naming a column that does not exist is a defect 
in that
+               // type, not a transient fault, so the bundle fails rather than
+               // draining every batch to the dead-letter output under a
+               // misconfiguration that will repeat.
+               fn.failBatch(ctx, batch, err)
+               return err
+       }
+
+       for _, part := range parts {
+               if err := fn.writePartition(ctx, part, emitSuccess, 
emitFailed); err != nil {
+                       return err
+               }
+       }
+       return nil
+}
+
+// failBatch logs an error and records metrics for a batch that cannot produce
+// a correct write. The caller returns an error to fail the bundle. It does not
+// emit to the dead-letter output because runner semantics discard bundle 
outputs
+// on error.
+//
+// This is deliberately distinct from the execution-failure path in
+// writePartition. A batch rejected here is rejected because the pipeline is
+// configured in a way that cannot ever produce a correct write, so retrying 
the
+// bundle against the same configuration would fail identically. Continuing
+// would drain every row of every batch into the dead-letter output while
+// reporting success, which hides a misconfiguration behind an apparently
+// healthy pipeline.
+func (fn *writeFn) failBatch(ctx context.Context, batch []any, err error) {
+       sinkFailedRows.Inc(ctx, int64(len(batch)))
+       msg := SanitizeErrorMessage(err)
+       log.Errorf(ctx, "postgresio: %s", msg)
+}
+
+func (fn *writeFn) writePartition(ctx context.Context, part writePartition, 
emitSuccess func(beam.X), emitFailed func(FailedRow)) error {
+       batch := part.Rows
+       if len(batch) == 0 {
+               return nil
+       }
+
+       // MERGE is expressible only by the staged-COPY path. The parameterized
+       // UNNEST path emits INSERT ... ON CONFLICT against the target, a 
statement
+       // with no DELETE arm, so a MERGE batch routed through it would apply 
the
+       // inserts and updates and silently discard every delete. A silently 
wrong
+       // result is worse than a failed bundle, so these cases fail loudly.
+       mergeMode := fn.Options.WriteMode == WriteModeMerge
+       if mergeMode {
+               var err error
+               switch {
+               case fn.Options.WriteMethod != WriteMethodStagedCopy:
+                       err = fmt.Errorf("postgresio: write mode MERGE requires 
the staged COPY write method; the parameterized UNNEST path cannot express 
deletes")
+               case !part.IsComplete():
+                       err = fmt.Errorf("postgresio: write mode MERGE cannot 
write partial rows (columns omitted: %s); the staging table is cloned from the 
target and carries every column",
+                               strings.Join(part.UnchangedColumns, ", "))
+               }
+               if err != nil {
+                       fn.failBatch(ctx, batch, err)
+                       return err
+               }
+       }
+
+       // High-Throughput Fast Path: Staged COPY Upsert (>100,000 rows/sec).
+       //
+       // Only a complete partition is eligible. The staging table is created 
LIKE
+       // the target, so it carries every column; streaming a partial row into 
it
+       // would materialize a zero value for the omitted columns and the merge
+       // would then write that over the stored value. Partial partitions fall
+       // through to the parameterized path, which can name an arbitrary column
+       // subset. This is a rare case, so the hot path is unaffected.
+       var copyErr error
+       if fn.Options.WriteMethod == WriteMethodStagedCopy && part.IsComplete() 
{
+               // Retried on its own rather than relying on the fallback. A 
deadlock
+               // here says nothing about the batch, and dropping to the slower
+               // parameterized path -- or, under MERGE, to the dead-letter 
queue,
+               // which has no fallback at all -- discards a fast-path write 
that a
+               // replay would almost certainly land.
+               copyErr = retryOnDeadlock(ctx, func() { 
sinkDeadlockRetries.Inc(ctx, 1) },
+                       func(ctx context.Context) error { return 
fn.executeStagedCopy(ctx, batch) })
+               if copyErr == nil {
+                       sinkWrittenRows.Inc(ctx, int64(len(batch)))
+                       for _, item := range batch {
+                               emitSuccess(item)
+                       }
+                       return nil
+               }
+               if mergeMode {
+                       err := fmt.Errorf("postgresio: MERGE staged COPY 
failed: %w", copyErr)
+                       fn.failBatch(ctx, batch, err)
+                       return err
+               }
+               log.Warnf(ctx, "postgresio: staged COPY failed (%v), falling 
back to parameterized UNNEST", copyErr)
+       }
+
+       query, args, err := fn.buildUnnestQueryForColumns(batch, part.Columns)
+       if err != nil {
+               if copyErr != nil {
+                       err = fmt.Errorf("postgresio: parameterized UNNEST 
fallback build failed: %w (original COPY error: %v)", err, copyErr)
+               } else {
+                       err = fmt.Errorf("postgresio: parameterized UNNEST 
build failed: %w", err)
+               }
+               fn.failBatch(ctx, batch, err)
+               return err
+       }
+
+       // Autocommit. A replication origin, when configured, is selected once 
per
+       // connection by pqConnector, so every statement this path issues is
+       // already stamped with it and no explicit transaction is needed to 
carry
+       // the tag. That applies equally when this path is entered directly and
+       // when a staged COPY fails and falls through to it, so the fallback
+       // cannot write untagged rows that a bidirectional peer would replay 
back.
+       execBatch := func(ctx context.Context) error {
+               _, err := fn.db.ExecContext(ctx, query, args...)
+               return err
+       }
+
+       execErr := retryOnDeadlock(ctx, func() { sinkDeadlockRetries.Inc(ctx, 
1) }, execBatch)
+       if execErr == nil {
+               sinkWrittenRows.Inc(ctx, int64(len(batch)))
+               for _, item := range batch {
+                       emitSuccess(item)
+               }
+               return nil
+       }
+
+       sqlState := extractSqlState(execErr)
+       if copyErr != nil {
+               execErr = fmt.Errorf("postgresio: write batch fallback failed 
with sqlstate %s: %w (original COPY error: %v)", sqlState, execErr, copyErr)
+       }
+
+       // Permanent failure: route batch to Dead-Letter Queue (DLQ)
+       sinkFailedRows.Inc(ctx, int64(len(batch)))
+       sanitizedMsg := SanitizeErrorMessage(execErr)
+       log.Errorf(ctx, "postgresio: %s", sanitizedMsg)
+       for _, item := range batch {
+               emitFailed(FailedRow{
+                       Row:          item,
+                       ErrorMessage: sanitizedMsg,
+                       SqlState:     sqlState,
+               })
+       }
+       return nil
+}
+
+// deadlockMaxRetries bounds how many times a batch is replayed after
+// PostgreSQL breaks a deadlock cycle involving it.
+const deadlockMaxRetries = 5
+
+// deadlockBaseBackoff is the first wait in the full-jitter ladder. It is a
+// variable so tests can walk the whole ladder without waiting seconds for it;
+// nothing outside tests reassigns it.
+var deadlockBaseBackoff = 50 * time.Millisecond
+
+// retryOnDeadlock runs op, replaying it while PostgreSQL reports a detected
+// deadlock, with full-jitter exponential backoff.
+//
+// A deadlock is not a property of the data. PostgreSQL resolves a cycle by
+// aborting one participant, and the aborted statement normally succeeds once
+// the other side has committed, so this is the one SQLSTATE where an immediate
+// replay is both safe and likely to work. Every other error returns
+// immediately: retrying a constraint violation only delays the dead-letter
+// routing that is already correct for it.
+//
+// Jitter is full rather than fixed because the workers that deadlock with each
+// other are running identical code. A deterministic backoff would reschedule
+// them at the same instant and reproduce the same cycle.
+//
+// The wait honours ctx. A sleep that ignored cancellation would keep a worker
+// that is draining for shutdown alive for the remainder of the ladder, and
+// would outlive the bundle the work belongs to.
+func retryOnDeadlock(ctx context.Context, onRetry func(), op 
func(context.Context) error) error {
+       backoff := deadlockBaseBackoff
+
+       var err error
+       for attempt := 0; attempt <= deadlockMaxRetries; attempt++ {
+               if err = op(ctx); err == nil {
+                       return nil
+               }
+               if extractSqlState(err) != sqlStateDeadlockDetected || attempt 
== deadlockMaxRetries {
+                       return err
+               }
+               if onRetry != nil {
+                       onRetry()
+               }
+
+               select {
+               case <-ctx.Done():
+                       return fmt.Errorf("postgresio: abandoned deadlock 
retry: %w (last database error: %v)", ctx.Err(), err)
+               case <-time.After(backoff + 
time.Duration(rand.Int63n(int64(backoff)))):
+               }
+               backoff *= 2
+       }
+       return err
+}
+
+// buildCopyStatement returns a COPY ... FROM STDIN statement.
+//
+// This replaces the deprecated lib/pq copy-statement helper, which quoted the
+// table name itself. Because the caller has already quoted the identifier via
+// SanitizeTableIdentifier, that helper produced a doubly-quoted name such as
+// COPY """public"".""orders""", which PostgreSQL reads as a single table
+// literally named `"public"."orders"`.

Review Comment:
   Referring to `lib/pq`'s `pq.CopyIn`, which quotes the table name itself and 
would double-quote an identifier already quoted by `sanitizeTableIdentifier`. 
Rewrote the comment



-- 
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]

Reply via email to