From e0240eec67a6a88d3daa2caa2bf48b45880a697b Mon Sep 17 00:00:00 2001
From: Sutou Kouhei <kou@clear-code.com>
Date: Tue, 18 Mar 2025 19:09:09 +0900
Subject: [PATCH v38 8/9] Use copy handlers for built-in formats

This adds copy handlers for text, csv and binary. We can simplify
Copy{To,From}GetRoutine() by this. We'll be able to remove
CopyFormatOptions::{binary,csv_mode} when we add more callbacks to
Copy{To,From}Routine and move format specific routines to
Copy{To,From}Routine::*.
---
 src/backend/commands/copy.c              | 48 ++++++++++++++++++------
 src/backend/commands/copyfrom.c          | 48 +++++++++++-------------
 src/backend/commands/copyto.c            | 48 +++++++++++-------------
 src/include/catalog/pg_proc.dat          | 11 ++++++
 src/include/commands/copyfrom_internal.h |  6 ++-
 src/include/commands/copyto_internal.h   |  6 ++-
 6 files changed, 102 insertions(+), 65 deletions(-)

diff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c
index b4417bb6819..24bd2547e3b 100644
--- a/src/backend/commands/copy.c
+++ b/src/backend/commands/copy.c
@@ -22,7 +22,9 @@
 #include "access/table.h"
 #include "access/xact.h"
 #include "catalog/pg_authid.h"
-#include "commands/copy.h"
+#include "commands/copyapi.h"
+#include "commands/copyto_internal.h"
+#include "commands/copyfrom_internal.h"
 #include "commands/defrem.h"
 #include "executor/executor.h"
 #include "mb/pg_wchar.h"
@@ -500,24 +502,15 @@ ProcessCopyOptionFormat(ParseState *pstate,
 
 	opts_out->csv_mode = false;
 	opts_out->binary = false;
-	/* built-in formats */
-	if (strcmp(format, "text") == 0)
-	{
-		/* "csv_mode == false && binary == false" means "text" */
-		return;
-	}
-	else if (strcmp(format, "csv") == 0)
+	if (strcmp(format, "csv") == 0)
 	{
 		opts_out->csv_mode = true;
-		return;
 	}
 	else if (strcmp(format, "binary") == 0)
 	{
 		opts_out->binary = true;
-		return;
 	}
 
-	/* custom format */
 	funcargtypes[0] = INTERNALOID;
 	handlerOid = LookupFuncName(list_make1(makeString(format)), 1,
 								funcargtypes, true);
@@ -1067,3 +1060,36 @@ CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
 
 	return attnums;
 }
+
+Datum
+copy_text_handler(PG_FUNCTION_ARGS)
+{
+	bool		is_from = PG_GETARG_BOOL(0);
+
+	if (is_from)
+		PG_RETURN_POINTER(&CopyFromRoutineText);
+	else
+		PG_RETURN_POINTER(&CopyToRoutineText);
+}
+
+Datum
+copy_csv_handler(PG_FUNCTION_ARGS)
+{
+	bool		is_from = PG_GETARG_BOOL(0);
+
+	if (is_from)
+		PG_RETURN_POINTER(&CopyFromRoutineCSV);
+	else
+		PG_RETURN_POINTER(&CopyToRoutineCSV);
+}
+
+Datum
+copy_binary_handler(PG_FUNCTION_ARGS)
+{
+	bool		is_from = PG_GETARG_BOOL(0);
+
+	if (is_from)
+		PG_RETURN_POINTER(&CopyFromRoutineBinary);
+	else
+		PG_RETURN_POINTER(&CopyToRoutineBinary);
+}
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 76662e04260..2677f2ac1bc 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -45,6 +45,7 @@
 #include "rewrite/rewriteHandler.h"
 #include "storage/fd.h"
 #include "tcop/tcopprot.h"
+#include "utils/fmgroids.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 #include "utils/portal.h"
@@ -128,7 +129,7 @@ static void CopyFromBinaryEnd(CopyFromState cstate);
  */
 
 /* text format */
-static const CopyFromRoutine CopyFromRoutineText = {
+const CopyFromRoutine CopyFromRoutineText = {
 	.type = T_CopyFromRoutine,
 	.CopyFromInFunc = CopyFromTextLikeInFunc,
 	.CopyFromStart = CopyFromTextLikeStart,
@@ -137,7 +138,7 @@ static const CopyFromRoutine CopyFromRoutineText = {
 };
 
 /* CSV format */
-static const CopyFromRoutine CopyFromRoutineCSV = {
+const CopyFromRoutine CopyFromRoutineCSV = {
 	.type = T_CopyFromRoutine,
 	.CopyFromInFunc = CopyFromTextLikeInFunc,
 	.CopyFromStart = CopyFromTextLikeStart,
@@ -146,7 +147,7 @@ static const CopyFromRoutine CopyFromRoutineCSV = {
 };
 
 /* binary format */
-static const CopyFromRoutine CopyFromRoutineBinary = {
+const CopyFromRoutine CopyFromRoutineBinary = {
 	.type = T_CopyFromRoutine,
 	.CopyFromInFunc = CopyFromBinaryInFunc,
 	.CopyFromStart = CopyFromBinaryStart,
@@ -158,30 +159,25 @@ static const CopyFromRoutine CopyFromRoutineBinary = {
 static const CopyFromRoutine *
 CopyFromGetRoutine(const CopyFormatOptions *opts)
 {
-	if (OidIsValid(opts->handler))
-	{
-		Datum		datum;
-		Node	   *routine;
+	Oid			handler = opts->handler;
+	Datum		datum;
+	Node	   *routine;
 
-		datum = OidFunctionCall1(opts->handler, BoolGetDatum(true));
-		routine = (Node *) DatumGetPointer(datum);
-		if (routine == NULL || !IsA(routine, CopyFromRoutine))
-			ereport(
-					ERROR,
-					(errcode(
-							 ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("COPY handler function "
-							"%u did not return "
-							"CopyFromRoutine struct",
-							opts->handler)));
-		return castNode(CopyFromRoutine, routine);
-	}
-	else if (opts->csv_mode)
-		return &CopyFromRoutineCSV;
-	else if (opts->binary)
-		return &CopyFromRoutineBinary;
-	else
-		return &CopyFromRoutineText;
+	if (!OidIsValid(handler))
+		handler = F_TEXT_INTERNAL;
+
+	datum = OidFunctionCall1(handler, BoolGetDatum(true));
+	routine = (Node *) DatumGetPointer(datum);
+	if (routine == NULL || !IsA(routine, CopyFromRoutine))
+		ereport(
+				ERROR,
+				(errcode(
+						 ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("COPY handler function "
+						"%u did not return "
+						"CopyFromRoutine struct",
+						opts->handler)));
+	return castNode(CopyFromRoutine, routine);
 }
 
 /* Implementation of the start callback for text and CSV formats */
diff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c
index f5ed3efbace..757d24736e3 100644
--- a/src/backend/commands/copyto.c
+++ b/src/backend/commands/copyto.c
@@ -32,6 +32,7 @@
 #include "pgstat.h"
 #include "storage/fd.h"
 #include "tcop/tcopprot.h"
+#include "utils/fmgroids.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 #include "utils/rel.h"
@@ -89,7 +90,7 @@ static void CopySendInt16(CopyToState cstate, int16 val);
  */
 
 /* text format */
-static const CopyToRoutine CopyToRoutineText = {
+const CopyToRoutine CopyToRoutineText = {
 	.type = T_CopyToRoutine,
 	.CopyToStart = CopyToTextLikeStart,
 	.CopyToOutFunc = CopyToTextLikeOutFunc,
@@ -98,7 +99,7 @@ static const CopyToRoutine CopyToRoutineText = {
 };
 
 /* CSV format */
-static const CopyToRoutine CopyToRoutineCSV = {
+const CopyToRoutine CopyToRoutineCSV = {
 	.type = T_CopyToRoutine,
 	.CopyToStart = CopyToTextLikeStart,
 	.CopyToOutFunc = CopyToTextLikeOutFunc,
@@ -107,7 +108,7 @@ static const CopyToRoutine CopyToRoutineCSV = {
 };
 
 /* binary format */
-static const CopyToRoutine CopyToRoutineBinary = {
+const CopyToRoutine CopyToRoutineBinary = {
 	.type = T_CopyToRoutine,
 	.CopyToStart = CopyToBinaryStart,
 	.CopyToOutFunc = CopyToBinaryOutFunc,
@@ -119,30 +120,25 @@ static const CopyToRoutine CopyToRoutineBinary = {
 static const CopyToRoutine *
 CopyToGetRoutine(const CopyFormatOptions *opts)
 {
-	if (OidIsValid(opts->handler))
-	{
-		Datum		datum;
-		Node	   *routine;
+	Oid			handler = opts->handler;
+	Datum		datum;
+	Node	   *routine;
 
-		datum = OidFunctionCall1(opts->handler, BoolGetDatum(false));
-		routine = (Node *) DatumGetPointer(datum);
-		if (routine == NULL || !IsA(routine, CopyToRoutine))
-			ereport(
-					ERROR,
-					(errcode(
-							 ERRCODE_INVALID_PARAMETER_VALUE),
-					 errmsg("COPY handler function "
-							"%u did not return "
-							"CopyToRoutine struct",
-							opts->handler)));
-		return castNode(CopyToRoutine, routine);
-	}
-	else if (opts->csv_mode)
-		return &CopyToRoutineCSV;
-	else if (opts->binary)
-		return &CopyToRoutineBinary;
-	else
-		return &CopyToRoutineText;
+	if (!OidIsValid(handler))
+		handler = F_TEXT_INTERNAL;
+
+	datum = OidFunctionCall1(handler, BoolGetDatum(false));
+	routine = (Node *) DatumGetPointer(datum);
+	if (routine == NULL || !IsA(routine, CopyToRoutine))
+		ereport(
+				ERROR,
+				(errcode(
+						 ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("COPY handler function "
+						"%u did not return "
+						"CopyToRoutine struct",
+						opts->handler)));
+	return castNode(CopyToRoutine, routine);
 }
 
 /* Implementation of the start callback for text and CSV formats */
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 7c2a510fa3f..0737eb73c9a 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -12485,4 +12485,15 @@
   proargtypes => 'int4',
   prosrc => 'gist_stratnum_common' },
 
+# COPY handlers
+{ oid => '8100', descr => 'text COPY FORMAT handler',
+  proname => 'text', provolatile => 'i', prorettype => 'copy_handler',
+  proargtypes => 'internal', prosrc => 'copy_text_handler' },
+{ oid => '8101', descr => 'csv COPY FORMAT handler',
+  proname => 'csv', provolatile => 'i', prorettype => 'copy_handler',
+  proargtypes => 'internal', prosrc => 'copy_csv_handler' },
+{ oid => '8102', descr => 'binary COPY FORMAT handler',
+  proname => 'binary', provolatile => 'i', prorettype => 'copy_handler',
+  proargtypes => 'internal', prosrc => 'copy_binary_handler' },
+
 ]
diff --git a/src/include/commands/copyfrom_internal.h b/src/include/commands/copyfrom_internal.h
index af425cf5fd9..abeccf85c1c 100644
--- a/src/include/commands/copyfrom_internal.h
+++ b/src/include/commands/copyfrom_internal.h
@@ -14,7 +14,7 @@
 #ifndef COPYFROM_INTERNAL_H
 #define COPYFROM_INTERNAL_H
 
-#include "commands/copy.h"
+#include "commands/copyapi.h"
 #include "commands/trigger.h"
 #include "nodes/miscnodes.h"
 
@@ -197,4 +197,8 @@ extern bool CopyFromCSVOneRow(CopyFromState cstate, ExprContext *econtext,
 extern bool CopyFromBinaryOneRow(CopyFromState cstate, ExprContext *econtext,
 								 Datum *values, bool *nulls);
 
+extern PGDLLIMPORT const CopyFromRoutine CopyFromRoutineText;
+extern PGDLLIMPORT const CopyFromRoutine CopyFromRoutineCSV;
+extern PGDLLIMPORT const CopyFromRoutine CopyFromRoutineBinary;
+
 #endif							/* COPYFROM_INTERNAL_H */
diff --git a/src/include/commands/copyto_internal.h b/src/include/commands/copyto_internal.h
index ce1c33a4004..85412660f7f 100644
--- a/src/include/commands/copyto_internal.h
+++ b/src/include/commands/copyto_internal.h
@@ -14,7 +14,7 @@
 #ifndef COPYTO_INTERNAL_H
 #define COPYTO_INTERNAL_H
 
-#include "commands/copy.h"
+#include "commands/copyapi.h"
 #include "executor/execdesc.h"
 #include "executor/tuptable.h"
 #include "nodes/execnodes.h"
@@ -83,4 +83,8 @@ typedef struct CopyToStateData
 	void	   *opaque;			/* private space */
 } CopyToStateData;
 
+extern PGDLLIMPORT const CopyToRoutine CopyToRoutineText;
+extern PGDLLIMPORT const CopyToRoutine CopyToRoutineCSV;
+extern PGDLLIMPORT const CopyToRoutine CopyToRoutineBinary;
+
 #endif							/* COPYTO_INTERNAL_H */
-- 
2.47.2

