summaryrefslogtreecommitdiff
path: root/contrib/dbmirror/pending.c
blob: a9027dbe502c8ffc8ef67d2762ab0f8f02c04152 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/****************************************************************************
 * pending.c
 * $Id: pending.c,v 1.1 2002/06/23 21:58:08 momjian Exp $ 
 *
 * This file contains a trigger for Postgresql-7.x to record changes to tables
 * to a pending table for mirroring.
 * All tables that should be mirrored should have this trigger hooked up to it.
 *
 *   Written by Steven Singer ([email protected])
 *   (c) 2001-2002 Navtech Systems Support Inc.
 *   Released under the GNU Public License version 2. See COPYING.
 *
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *
 ***************************************************************************/
#include <executor/spi.h>
#include <commands/trigger.h>
#include <postgres.h>

enum FieldUsage  {PRIMARY=0,NONPRIMARY,ALL,NUM_FIELDUSAGE};

int storePending(char * cpTableName, HeapTuple  tBeforeTuple, 
		 HeapTuple tAfterTuple,
		  TupleDesc tTupdesc,
		 TriggerData * tpTrigdata,char cOp);

int storeKeyInfo(char * cpTableName, HeapTuple tTupleData, TupleDesc tTuplDesc,
		 TriggerData * tpTrigdata);
int storeData(char * cpTableName,HeapTuple tTupleData,TupleDesc tTupleDesc,
	      TriggerData * tpTrigData,int iIncludeKeyData);
     
int2vector * getPrimaryKey(Oid tblOid);

char * packageData(HeapTuple tTupleData, TupleDesc tTupleDecs,
		   TriggerData * tTrigData,
		   enum FieldUsage eKeyUsage );

#define BUFFER_SIZE 256
#define MAX_OID_LEN 10


extern Datum recordchange(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(recordchange);


/*****************************************************************************
 * The entry point for the trigger function.
 * The Trigger takes a single SQL 'text' argument indicating the name of the
 * table the trigger was applied to.  If this name is incorrect so will the
 * mirroring.
 ****************************************************************************/
Datum recordchange(PG_FUNCTION_ARGS) {
  TriggerData * trigdata; 
  TupleDesc tupdesc;
  HeapTuple beforeTuple=NULL;
  HeapTuple afterTuple=NULL;
  HeapTuple retTuple=NULL;
  char * tblname;
  char op;
  if(fcinfo->context!=NULL) {
    
    if(SPI_connect() < 0) {
      elog(NOTICE,"storePending could not connect to SPI");
      return -1;
    }
    trigdata = (TriggerData*)fcinfo->context;
    /* Extract the table name */
    tblname = SPI_getrelname(trigdata->tg_relation);
    tupdesc = trigdata->tg_relation->rd_att;
    if(TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) {
      retTuple = trigdata->tg_newtuple;
      beforeTuple = trigdata->tg_trigtuple;
      afterTuple = trigdata->tg_newtuple;
      op='u';

    }
    else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event)) {
      retTuple = trigdata->tg_trigtuple;
      afterTuple = trigdata->tg_trigtuple;
      op = 'i';
    }
    else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) {
      retTuple = trigdata->tg_trigtuple;
      beforeTuple = trigdata->tg_trigtuple;
      op = 'd';
    }

    if(storePending(tblname,beforeTuple,afterTuple,tupdesc,trigdata,op)) {
      /* An error occoured. Skip the operation. */
      elog(ERROR,"Operation could not be mirrored");
      return PointerGetDatum(NULL);
	 
    }
#if defined DEBUG_OUTPUT
    elog(NOTICE,"Returning on success");
#endif
    SPI_finish();
    return PointerGetDatum(retTuple);
  }
  else {
    /*
     * Not being called as a trigger.
     */
    return PointerGetDatum(NULL);
  }
}


/*****************************************************************************
 * Constructs and executes an SQL query to write a record of this tuple change
 * to the pending table. 
 *****************************************************************************/
int storePending(char * cpTableName, HeapTuple  tBeforeTuple, 
		 HeapTuple tAfterTuple,
		  TupleDesc tTupDesc,
		  TriggerData * tpTrigData,char cOp) {
  char * cpQueryBase = "INSERT INTO \"Pending\" (\"TableName\",\"Op\",\"XID\") VALUES ($1,$2,$3)";

  int iResult=0;
  HeapTuple tCurTuple; // Points the current tuple(before or after)
  Datum saPlanData[4];
  Oid taPlanArgTypes[3] = {NAMEOID,CHAROID,INT4OID};
  void * vpPlan;

  tCurTuple = tBeforeTuple ? tBeforeTuple : tAfterTuple;

  

  
  vpPlan = SPI_prepare(cpQueryBase,3,taPlanArgTypes);
  if(vpPlan==NULL) {
    elog(NOTICE,"Error creating plan");
  }
  //  SPI_saveplan(vpPlan);

  saPlanData[0] = PointerGetDatum(cpTableName);
  saPlanData[1] = CharGetDatum(cOp);
  saPlanData[2] = Int32GetDatum(GetCurrentTransactionId());
  
  
  iResult = SPI_execp(vpPlan,saPlanData,NULL,1);
  if(iResult < 0) {
    elog(NOTICE,"storedPending fired (%s) returned %d",cpQueryBase,iResult);
  }
  

#if defined DEBUG_OUTPUT
 elog(NOTICE,"row successfully stored in pending table");
#endif

  if(cOp=='d') {
    /**
     * This is a record of a delete operation.
     * Just store the key data.
     */
    iResult = storeKeyInfo(cpTableName,tBeforeTuple,tTupDesc,tpTrigData);
  }
  else if (cOp=='i') {
    /**
     * An Insert operation.
     * Store all data
     */
    iResult = storeData(cpTableName,tAfterTuple,tTupDesc,tpTrigData,TRUE);

  }
  else {
    /* op must be an update. */
    iResult = storeKeyInfo(cpTableName,tBeforeTuple,tTupDesc,tpTrigData);
    iResult = iResult ? iResult : storeData(cpTableName,tAfterTuple,tTupDesc,
					    tpTrigData,TRUE);
  }

#if defined DEBUG_OUTPUT
  elog(NOTICE,"DOne storing keyinfo");
#endif
 
  return iResult;

}

int storeKeyInfo(char * cpTableName, HeapTuple tTupleData, 
		 TupleDesc tTupleDesc,
		 TriggerData * tpTrigData) {
 
  Oid saPlanArgTypes[1] = {NAMEOID};
  char * insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'t',$1)";
  void * pplan;
  Datum saPlanData[1];
  char * cpKeyData;
  int iRetCode;

  pplan = SPI_prepare(insQuery,1,saPlanArgTypes);
    if(pplan==NULL) {
      elog(NOTICE,"Could not prepare INSERT plan");
      return -1;
    }
    
    //    pplan = SPI_saveplan(pplan);
    cpKeyData = packageData(tTupleData, tTupleDesc,tpTrigData,PRIMARY);
#if defined DEBUG_OUTPUT
    elog(NOTICE,cpKeyData);
#endif
    saPlanData[0] = PointerGetDatum(cpKeyData);
    
    iRetCode = SPI_execp(pplan,saPlanData,NULL,1);    

    if(cpKeyData!=NULL) {
      SPI_pfree(cpKeyData);
    }

    if(iRetCode != SPI_OK_INSERT ) {
      elog(NOTICE,"Error inserting row in pendingDelete");
      return -1;
    }
#if defined DEBUG_OUTPUT
    elog(NOTICE,"INSERT SUCCESFULL");
#endif

    return 0;
    
}




int2vector * getPrimaryKey(Oid tblOid) {
  char * queryBase;
  char * query;
  bool isNull;
  int2vector * resultKey;
  int2vector * tpResultKey;
  HeapTuple resTuple;
  Datum resDatum;
  int ret;
  queryBase = "SELECT indkey FROM pg_index WHERE indisprimary='t' AND indrelid=";
  query = SPI_palloc(strlen(queryBase) + MAX_OID_LEN+1);
  sprintf(query,"%s%d",queryBase,tblOid);
  ret = SPI_exec(query,1);
  if(ret != SPI_OK_SELECT || SPI_processed != 1 ) {
    elog(NOTICE,"Could not select primary index key");
    return NULL;
  }

  resTuple = SPI_tuptable->vals[0];
  resDatum = SPI_getbinval(resTuple,SPI_tuptable->tupdesc,1,&isNull);

  tpResultKey = (int2vector*) DatumGetPointer(resDatum);
  resultKey = SPI_palloc(sizeof(int2vector));
  memcpy(resultKey,tpResultKey,sizeof(int2vector));

  SPI_pfree(query);
  return resultKey;
}

/******************************************************************************
 * Stores a copy of the non-key data for the row.
 *****************************************************************************/
int storeData(char * cpTableName,HeapTuple tTupleData,TupleDesc tTupleDesc,
		     TriggerData * tpTrigData,int iIncludeKeyData) {

  Oid planArgTypes[1] = {NAMEOID};
  char * insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'f',$1)";
  void * pplan;
  Datum planData[1];
  char * cpKeyData;
  int iRetValue;

  pplan = SPI_prepare(insQuery,1,planArgTypes);
    if(pplan==NULL) {
      elog(NOTICE,"Could not prepare INSERT plan");
      return -1;
    }
    
    //    pplan = SPI_saveplan(pplan);
    if(iIncludeKeyData==0) {
      cpKeyData = packageData(tTupleData, tTupleDesc,tpTrigData,NONPRIMARY); 
    }
    else {
      cpKeyData = packageData(tTupleData,tTupleDesc,tpTrigData,ALL);
    }
    
    planData[0] = PointerGetDatum(cpKeyData);
    iRetValue = SPI_execp(pplan,planData,NULL,1);
    
    if(cpKeyData!=0) {
      SPI_pfree(cpKeyData);
    }

    if(iRetValue != SPI_OK_INSERT ) {
      elog(NOTICE,"Error inserting row in pendingDelete");
      return -1;
    }
#if defined DEBUG_OUTPUT
    elog(NOTICE,"INSERT SUCCESFULL");
#endif

    return 0;  
    
}

/**
 * Packages the data in tTupleData into a string of the format 
 * FieldName='value text'  where any quotes inside of value text
 * are escaped with a backslash and any backslashes in value text
 * are esacped by a second back slash.
 *
 * tTupleDesc should be a description of the tuple stored in 
 * tTupleData.  
 *
 * eFieldUsage specifies which fields to use.
 *  PRIMARY implies include only primary key fields.
 *  NONPRIMARY implies include only non-primary key fields.
 *  ALL implies include all fields.
 */
char * packageData(HeapTuple tTupleData, TupleDesc tTupleDesc,
		   TriggerData *  tpTrigData,
		   enum FieldUsage eKeyUsage ) {
  int iNumCols;
  int2vector * tpPKeys=NULL;
  int iColumnCounter;
  char * cpDataBlock;
  int iDataBlockSize;
  int  iUsedDataBlock;
  
  iNumCols = tTupleDesc->natts;

  if(eKeyUsage!=ALL) {
    tpPKeys = getPrimaryKey(tpTrigData->tg_relation->rd_id);
    if(tpPKeys==NULL) {
      return NULL;
    }
  }
#if defined DEBUG_OUTPUT
  if(tpPKeys!=NULL) {
    elog(NOTICE,"Have primary keys");
  }
#endif 
  cpDataBlock = SPI_palloc(BUFFER_SIZE);
  iDataBlockSize = BUFFER_SIZE;
  iUsedDataBlock = 0;                   /* To account for the null */

  for(iColumnCounter=1; iColumnCounter <=iNumCols; iColumnCounter++) {
    int iIsPrimaryKey;
    int iPrimaryKeyIndex;
    char * cpUnFormatedPtr;
    char * cpFormatedPtr;

    char * cpFieldName;
    char * cpFieldData;
    if(eKeyUsage!=ALL) {
      //Determine if this is a primary key or not.
      iIsPrimaryKey=0;
      for(iPrimaryKeyIndex=0; (*tpPKeys)[iPrimaryKeyIndex]!=0;
	  iPrimaryKeyIndex++) {
	if((*tpPKeys)[iPrimaryKeyIndex]==iColumnCounter) {	
	  iIsPrimaryKey=1;
	  break;
	}
      }
      if( iIsPrimaryKey ? (eKeyUsage!=PRIMARY) : (eKeyUsage!=NONPRIMARY)) {
	/**
	 * Don't use.
	 */
#if defined DEBUG_OUTPUT
	elog(NOTICE,"Skipping column");
#endif
	continue;
      }
    }                                   /* KeyUsage!=ALL */
    cpFieldName = DatumGetPointer(NameGetDatum(&tTupleDesc->attrs
					       [iColumnCounter-1]->attname));
#if defined DEBUG_OUTPUT
    elog(NOTICE,cpFieldName);
#endif
    while(iDataBlockSize - iUsedDataBlock < strlen(cpFieldName) +4) {
      cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize + BUFFER_SIZE);
      iDataBlockSize = iDataBlockSize + BUFFER_SIZE;      
    }
    sprintf(cpDataBlock+iUsedDataBlock,"\"%s\"=",cpFieldName);
    iUsedDataBlock = iUsedDataBlock + strlen(cpFieldName)+3;
    cpFieldData=SPI_getvalue(tTupleData,tTupleDesc,iColumnCounter);
    
    cpUnFormatedPtr = cpFieldData;
    cpFormatedPtr = cpDataBlock + iUsedDataBlock;
    if(cpFieldData!=NULL) {
      *cpFormatedPtr='\'';
      iUsedDataBlock++;
      cpFormatedPtr++;
    }
    else {
      *cpFormatedPtr=' ';
      iUsedDataBlock++;
      cpFormatedPtr++;
      continue;
      
    }
#if defined DEBUG_OUTPUT
    elog(NOTICE,cpFieldData);
    elog(NOTICE,"Starting format loop");
#endif
    while(*cpUnFormatedPtr!=0) {
      while(iDataBlockSize - iUsedDataBlock < 2) {
	cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize+BUFFER_SIZE);
	iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
	cpFormatedPtr = cpDataBlock + iUsedDataBlock;
      }
      if(*cpUnFormatedPtr=='\\' || *cpUnFormatedPtr=='\'') {
	*cpFormatedPtr='\\';
	cpFormatedPtr++;
	iUsedDataBlock++;
      }
      *cpFormatedPtr=*cpUnFormatedPtr;
      cpFormatedPtr++;
      cpUnFormatedPtr++;
      iUsedDataBlock++;
    }

    SPI_pfree(cpFieldData);

    while(iDataBlockSize - iUsedDataBlock < 3) {
      cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize+BUFFER_SIZE);
      iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
      cpFormatedPtr = cpDataBlock + iUsedDataBlock;
    }
    sprintf(cpFormatedPtr,"' ");
    iUsedDataBlock = iUsedDataBlock +2;
#if defined DEBUG_OUTPUT
    elog(NOTICE,cpDataBlock);
#endif
    
  }                                     /*  for iColumnCounter  */
  if(tpPKeys!=NULL) {
    SPI_pfree(tpPKeys);    
  }
#if defined DEBUG_OUTPUT
  elog(NOTICE,"Returning");
#endif
  memset(cpDataBlock + iUsedDataBlock,0,iDataBlockSize - iUsedDataBlock);

  return cpDataBlock;
  
}