You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_decoding.c 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /*-------------------------------------------------------------------------
  2. *
  3. * test_decoding.c
  4. * example logical decoding output plugin
  5. *
  6. * Copyright (c) 2012-2019, PostgreSQL Global Development Group
  7. *
  8. * IDENTIFICATION
  9. * contrib/test_decoding/test_decoding.c
  10. *
  11. *-------------------------------------------------------------------------
  12. */
  13. #include "postgres.h"
  14. #include "catalog/pg_type.h"
  15. #include "replication/logical.h"
  16. #include "replication/origin.h"
  17. #include "utils/builtins.h"
  18. #include "utils/lsyscache.h"
  19. #include "utils/memutils.h"
  20. #include "utils/rel.h"
  21. PG_MODULE_MAGIC;
  22. /* These must be available to pg_dlsym() */
  23. extern void _PG_init(void);
  24. extern void _PG_output_plugin_init(OutputPluginCallbacks *cb);
  25. typedef struct
  26. {
  27. MemoryContext context;
  28. bool include_xids;
  29. bool include_timestamp;
  30. bool skip_empty_xacts;
  31. bool xact_wrote_changes;
  32. bool only_local;
  33. } TestDecodingData;
  34. static void pg_decode_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt,
  35. bool is_init);
  36. static void pg_decode_shutdown(LogicalDecodingContext *ctx);
  37. static void pg_decode_begin_txn(LogicalDecodingContext *ctx,
  38. ReorderBufferTXN *txn);
  39. static void pg_output_begin(LogicalDecodingContext *ctx,
  40. TestDecodingData *data,
  41. ReorderBufferTXN *txn,
  42. bool last_write);
  43. static void pg_decode_commit_txn(LogicalDecodingContext *ctx,
  44. ReorderBufferTXN *txn, XLogRecPtr commit_lsn);
  45. static void pg_decode_change(LogicalDecodingContext *ctx,
  46. ReorderBufferTXN *txn, Relation rel,
  47. ReorderBufferChange *change);
  48. static void pg_decode_truncate(LogicalDecodingContext *ctx,
  49. ReorderBufferTXN *txn,
  50. int nrelations, Relation relations[],
  51. ReorderBufferChange *change);
  52. static bool pg_decode_filter(LogicalDecodingContext *ctx,
  53. RepOriginId origin_id);
  54. static void pg_decode_message(LogicalDecodingContext *ctx,
  55. ReorderBufferTXN *txn, XLogRecPtr message_lsn,
  56. bool transactional, const char *prefix,
  57. Size sz, const char *message);
  58. void
  59. _PG_init(void)
  60. {
  61. /* other plugins can perform things here */
  62. }
  63. /* specify output plugin callbacks */
  64. void
  65. _PG_output_plugin_init(OutputPluginCallbacks *cb)
  66. {
  67. AssertVariableIsOfType(&_PG_output_plugin_init, LogicalOutputPluginInit);
  68. cb->startup_cb = pg_decode_startup;
  69. cb->begin_cb = pg_decode_begin_txn;
  70. cb->change_cb = pg_decode_change;
  71. cb->truncate_cb = pg_decode_truncate;
  72. cb->commit_cb = pg_decode_commit_txn;
  73. cb->filter_by_origin_cb = pg_decode_filter;
  74. cb->shutdown_cb = pg_decode_shutdown;
  75. cb->message_cb = pg_decode_message;
  76. }
  77. /* initialize this plugin */
  78. static void
  79. pg_decode_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt,
  80. bool is_init)
  81. {
  82. ListCell *option;
  83. TestDecodingData *data;
  84. data = palloc0(sizeof(TestDecodingData));
  85. data->context = AllocSetContextCreate(ctx->context,
  86. "text conversion context",
  87. ALLOCSET_DEFAULT_SIZES);
  88. data->include_xids = true;
  89. data->include_timestamp = false;
  90. data->skip_empty_xacts = false;
  91. data->only_local = false;
  92. ctx->output_plugin_private = data;
  93. opt->output_type = OUTPUT_PLUGIN_TEXTUAL_OUTPUT;
  94. opt->receive_rewrites = false;
  95. foreach(option, ctx->output_plugin_options)
  96. {
  97. DefElem *elem = lfirst(option);
  98. Assert(elem->arg == NULL || IsA(elem->arg, String));
  99. if (strcmp(elem->defname, "include-xids") == 0)
  100. {
  101. /* if option does not provide a value, it means its value is true */
  102. if (elem->arg == NULL)
  103. data->include_xids = true;
  104. else if (!parse_bool(strVal(elem->arg), &data->include_xids))
  105. ereport(ERROR,
  106. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  107. errmsg("could not parse value \"%s\" for parameter \"%s\"",
  108. strVal(elem->arg), elem->defname)));
  109. }
  110. else if (strcmp(elem->defname, "include-timestamp") == 0)
  111. {
  112. if (elem->arg == NULL)
  113. data->include_timestamp = true;
  114. else if (!parse_bool(strVal(elem->arg), &data->include_timestamp))
  115. ereport(ERROR,
  116. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  117. errmsg("could not parse value \"%s\" for parameter \"%s\"",
  118. strVal(elem->arg), elem->defname)));
  119. }
  120. else if (strcmp(elem->defname, "force-binary") == 0)
  121. {
  122. bool force_binary;
  123. if (elem->arg == NULL)
  124. continue;
  125. else if (!parse_bool(strVal(elem->arg), &force_binary))
  126. ereport(ERROR,
  127. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  128. errmsg("could not parse value \"%s\" for parameter \"%s\"",
  129. strVal(elem->arg), elem->defname)));
  130. if (force_binary)
  131. opt->output_type = OUTPUT_PLUGIN_BINARY_OUTPUT;
  132. }
  133. else if (strcmp(elem->defname, "skip-empty-xacts") == 0)
  134. {
  135. if (elem->arg == NULL)
  136. data->skip_empty_xacts = true;
  137. else if (!parse_bool(strVal(elem->arg), &data->skip_empty_xacts))
  138. ereport(ERROR,
  139. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  140. errmsg("could not parse value \"%s\" for parameter \"%s\"",
  141. strVal(elem->arg), elem->defname)));
  142. }
  143. else if (strcmp(elem->defname, "only-local") == 0)
  144. {
  145. if (elem->arg == NULL)
  146. data->only_local = true;
  147. else if (!parse_bool(strVal(elem->arg), &data->only_local))
  148. ereport(ERROR,
  149. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  150. errmsg("could not parse value \"%s\" for parameter \"%s\"",
  151. strVal(elem->arg), elem->defname)));
  152. }
  153. else if (strcmp(elem->defname, "include-rewrites") == 0)
  154. {
  155. if (elem->arg == NULL)
  156. continue;
  157. else if (!parse_bool(strVal(elem->arg), &opt->receive_rewrites))
  158. ereport(ERROR,
  159. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  160. errmsg("could not parse value \"%s\" for parameter \"%s\"",
  161. strVal(elem->arg), elem->defname)));
  162. }
  163. else
  164. {
  165. ereport(ERROR,
  166. (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
  167. errmsg("option \"%s\" = \"%s\" is unknown",
  168. elem->defname,
  169. elem->arg ? strVal(elem->arg) : "(null)")));
  170. }
  171. }
  172. }
  173. /* cleanup this plugin's resources */
  174. static void
  175. pg_decode_shutdown(LogicalDecodingContext *ctx)
  176. {
  177. TestDecodingData *data = ctx->output_plugin_private;
  178. /* cleanup our own resources via memory context reset */
  179. MemoryContextDelete(data->context);
  180. }
  181. /* BEGIN callback */
  182. static void
  183. pg_decode_begin_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn)
  184. {
  185. TestDecodingData *data = ctx->output_plugin_private;
  186. data->xact_wrote_changes = false;
  187. if (data->skip_empty_xacts)
  188. return;
  189. pg_output_begin(ctx, data, txn, true);
  190. }
  191. static void
  192. pg_output_begin(LogicalDecodingContext *ctx, TestDecodingData *data, ReorderBufferTXN *txn, bool last_write)
  193. {
  194. OutputPluginPrepareWrite(ctx, last_write);
  195. if (data->include_xids)
  196. appendStringInfo(ctx->out, "BEGIN %u", txn->xid);
  197. else
  198. appendStringInfoString(ctx->out, "BEGIN");
  199. OutputPluginWrite(ctx, last_write);
  200. }
  201. /* COMMIT callback */
  202. static void
  203. pg_decode_commit_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
  204. XLogRecPtr commit_lsn)
  205. {
  206. TestDecodingData *data = ctx->output_plugin_private;
  207. if (data->skip_empty_xacts && !data->xact_wrote_changes)
  208. return;
  209. OutputPluginPrepareWrite(ctx, true);
  210. if (data->include_xids)
  211. appendStringInfo(ctx->out, "COMMIT %u", txn->xid);
  212. else
  213. appendStringInfoString(ctx->out, "COMMIT");
  214. if (data->include_timestamp)
  215. appendStringInfo(ctx->out, " (at %s)",
  216. timestamptz_to_str(txn->commit_time));
  217. OutputPluginWrite(ctx, true);
  218. }
  219. static bool
  220. pg_decode_filter(LogicalDecodingContext *ctx,
  221. RepOriginId origin_id)
  222. {
  223. TestDecodingData *data = ctx->output_plugin_private;
  224. if (data->only_local && origin_id != InvalidRepOriginId)
  225. return true;
  226. return false;
  227. }
  228. /*
  229. * Print literal `outputstr' already represented as string of type `typid'
  230. * into stringbuf `s'.
  231. *
  232. * Some builtin types aren't quoted, the rest is quoted. Escaping is done as
  233. * if standard_conforming_strings were enabled.
  234. */
  235. static void
  236. print_literal(StringInfo s, Oid typid, char *outputstr)
  237. {
  238. const char *valptr;
  239. switch (typid)
  240. {
  241. case INT2OID:
  242. case INT4OID:
  243. case INT8OID:
  244. case OIDOID:
  245. case FLOAT4OID:
  246. case FLOAT8OID:
  247. case NUMERICOID:
  248. /* NB: We don't care about Inf, NaN et al. */
  249. appendStringInfoString(s, outputstr);
  250. break;
  251. case BITOID:
  252. case VARBITOID:
  253. appendStringInfo(s, "B'%s'", outputstr);
  254. break;
  255. case BOOLOID:
  256. if (strcmp(outputstr, "t") == 0)
  257. appendStringInfoString(s, "true");
  258. else
  259. appendStringInfoString(s, "false");
  260. break;
  261. default:
  262. appendStringInfoChar(s, '\'');
  263. for (valptr = outputstr; *valptr; valptr++)
  264. {
  265. char ch = *valptr;
  266. if (SQL_STR_DOUBLE(ch, false))
  267. appendStringInfoChar(s, ch);
  268. appendStringInfoChar(s, ch);
  269. }
  270. appendStringInfoChar(s, '\'');
  271. break;
  272. }
  273. }
  274. /* print the tuple 'tuple' into the StringInfo s */
  275. static void
  276. tuple_to_stringinfo(StringInfo s, TupleDesc tupdesc, HeapTuple tuple, bool skip_nulls)
  277. {
  278. int natt;
  279. /* print all columns individually */
  280. for (natt = 0; natt < tupdesc->natts; natt++)
  281. {
  282. Form_pg_attribute attr; /* the attribute itself */
  283. Oid typid; /* type of current attribute */
  284. Oid typoutput; /* output function */
  285. bool typisvarlena;
  286. Datum origval; /* possibly toasted Datum */
  287. bool isnull; /* column is null? */
  288. attr = TupleDescAttr(tupdesc, natt);
  289. /*
  290. * don't print dropped columns, we can't be sure everything is
  291. * available for them
  292. */
  293. if (attr->attisdropped)
  294. continue;
  295. /*
  296. * Don't print system columns, oid will already have been printed if
  297. * present.
  298. */
  299. if (attr->attnum < 0)
  300. continue;
  301. typid = attr->atttypid;
  302. /* get Datum from tuple */
  303. origval = heap_getattr(tuple, natt + 1, tupdesc, &isnull);
  304. if (isnull && skip_nulls)
  305. continue;
  306. /* print attribute name */
  307. appendStringInfoChar(s, ' ');
  308. appendStringInfoString(s, quote_identifier(NameStr(attr->attname)));
  309. /* print attribute type */
  310. appendStringInfoChar(s, '[');
  311. appendStringInfoString(s, format_type_be(typid));
  312. appendStringInfoChar(s, ']');
  313. /* query output function */
  314. getTypeOutputInfo(typid,
  315. &typoutput, &typisvarlena);
  316. /* print separator */
  317. appendStringInfoChar(s, ':');
  318. /* print data */
  319. if (isnull)
  320. appendStringInfoString(s, "null");
  321. else if (typisvarlena && VARATT_IS_EXTERNAL_ONDISK(origval))
  322. appendStringInfoString(s, "unchanged-toast-datum");
  323. else if (!typisvarlena)
  324. print_literal(s, typid,
  325. OidOutputFunctionCall(typoutput, origval));
  326. else
  327. {
  328. Datum val; /* definitely detoasted Datum */
  329. val = PointerGetDatum(PG_DETOAST_DATUM(origval));
  330. print_literal(s, typid, OidOutputFunctionCall(typoutput, val));
  331. }
  332. }
  333. }
  334. /*
  335. * callback for individual changed tuples
  336. */
  337. static void
  338. pg_decode_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
  339. Relation relation, ReorderBufferChange *change)
  340. {
  341. TestDecodingData *data;
  342. Form_pg_class class_form;
  343. TupleDesc tupdesc;
  344. MemoryContext old;
  345. data = ctx->output_plugin_private;
  346. /* output BEGIN if we haven't yet */
  347. if (data->skip_empty_xacts && !data->xact_wrote_changes)
  348. {
  349. pg_output_begin(ctx, data, txn, false);
  350. }
  351. data->xact_wrote_changes = true;
  352. class_form = RelationGetForm(relation);
  353. tupdesc = RelationGetDescr(relation);
  354. /* Avoid leaking memory by using and resetting our own context */
  355. old = MemoryContextSwitchTo(data->context);
  356. OutputPluginPrepareWrite(ctx, true);
  357. appendStringInfoString(ctx->out, "table ");
  358. appendStringInfoString(ctx->out,
  359. quote_qualified_identifier(
  360. get_namespace_name(
  361. get_rel_namespace(RelationGetRelid(relation))),
  362. class_form->relrewrite ?
  363. get_rel_name(class_form->relrewrite) :
  364. NameStr(class_form->relname)));
  365. appendStringInfoChar(ctx->out, ':');
  366. switch (change->action)
  367. {
  368. case REORDER_BUFFER_CHANGE_INSERT:
  369. appendStringInfoString(ctx->out, " INSERT:");
  370. if (change->data.tp.newtuple == NULL)
  371. appendStringInfoString(ctx->out, " (no-tuple-data)");
  372. else
  373. tuple_to_stringinfo(ctx->out, tupdesc,
  374. &change->data.tp.newtuple->tuple,
  375. false);
  376. break;
  377. case REORDER_BUFFER_CHANGE_UPDATE:
  378. appendStringInfoString(ctx->out, " UPDATE:");
  379. if (change->data.tp.oldtuple != NULL)
  380. {
  381. appendStringInfoString(ctx->out, " old-key:");
  382. tuple_to_stringinfo(ctx->out, tupdesc,
  383. &change->data.tp.oldtuple->tuple,
  384. true);
  385. appendStringInfoString(ctx->out, " new-tuple:");
  386. }
  387. if (change->data.tp.newtuple == NULL)
  388. appendStringInfoString(ctx->out, " (no-tuple-data)");
  389. else
  390. tuple_to_stringinfo(ctx->out, tupdesc,
  391. &change->data.tp.newtuple->tuple,
  392. false);
  393. break;
  394. case REORDER_BUFFER_CHANGE_DELETE:
  395. appendStringInfoString(ctx->out, " DELETE:");
  396. /* if there was no PK, we only know that a delete happened */
  397. if (change->data.tp.oldtuple == NULL)
  398. appendStringInfoString(ctx->out, " (no-tuple-data)");
  399. /* In DELETE, only the replica identity is present; display that */
  400. else
  401. tuple_to_stringinfo(ctx->out, tupdesc,
  402. &change->data.tp.oldtuple->tuple,
  403. true);
  404. break;
  405. default:
  406. Assert(false);
  407. }
  408. MemoryContextSwitchTo(old);
  409. MemoryContextReset(data->context);
  410. OutputPluginWrite(ctx, true);
  411. }
  412. static void
  413. pg_decode_truncate(LogicalDecodingContext *ctx, ReorderBufferTXN *txn,
  414. int nrelations, Relation relations[], ReorderBufferChange *change)
  415. {
  416. TestDecodingData *data;
  417. MemoryContext old;
  418. int i;
  419. data = ctx->output_plugin_private;
  420. /* output BEGIN if we haven't yet */
  421. if (data->skip_empty_xacts && !data->xact_wrote_changes)
  422. {
  423. pg_output_begin(ctx, data, txn, false);
  424. }
  425. data->xact_wrote_changes = true;
  426. /* Avoid leaking memory by using and resetting our own context */
  427. old = MemoryContextSwitchTo(data->context);
  428. OutputPluginPrepareWrite(ctx, true);
  429. appendStringInfoString(ctx->out, "table ");
  430. for (i = 0; i < nrelations; i++)
  431. {
  432. if (i > 0)
  433. appendStringInfoString(ctx->out, ", ");
  434. appendStringInfoString(ctx->out,
  435. quote_qualified_identifier(get_namespace_name(relations[i]->rd_rel->relnamespace),
  436. NameStr(relations[i]->rd_rel->relname)));
  437. }
  438. appendStringInfoString(ctx->out, ": TRUNCATE:");
  439. if (change->data.truncate.restart_seqs
  440. || change->data.truncate.cascade)
  441. {
  442. if (change->data.truncate.restart_seqs)
  443. appendStringInfo(ctx->out, " restart_seqs");
  444. if (change->data.truncate.cascade)
  445. appendStringInfo(ctx->out, " cascade");
  446. }
  447. else
  448. appendStringInfoString(ctx->out, " (no-flags)");
  449. MemoryContextSwitchTo(old);
  450. MemoryContextReset(data->context);
  451. OutputPluginWrite(ctx, true);
  452. }
  453. static void
  454. pg_decode_message(LogicalDecodingContext *ctx,
  455. ReorderBufferTXN *txn, XLogRecPtr lsn, bool transactional,
  456. const char *prefix, Size sz, const char *message)
  457. {
  458. OutputPluginPrepareWrite(ctx, true);
  459. appendStringInfo(ctx->out, "message: transactional: %d prefix: %s, sz: %zu content:",
  460. transactional, prefix, sz);
  461. appendBinaryStringInfo(ctx->out, message, sz);
  462. OutputPluginWrite(ctx, true);
  463. }