~ubuntu-branches/ubuntu/lucid/postgresql-8.4/lucid-security

« back to all changes in this revision

Viewing changes to src/backend/commands/sequence.c

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2009-03-20 12:00:13 UTC
  • Revision ID: james.westby@ubuntu.com-20090320120013-hogj7egc5mjncc5g
Tags: upstream-8.4~0cvs20090328
ImportĀ upstreamĀ versionĀ 8.4~0cvs20090328

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*-------------------------------------------------------------------------
 
2
 *
 
3
 * sequence.c
 
4
 *        PostgreSQL sequences support code.
 
5
 *
 
6
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
 
7
 * Portions Copyright (c) 1994, Regents of the University of California
 
8
 *
 
9
 *
 
10
 * IDENTIFICATION
 
11
 *        $PostgreSQL$
 
12
 *
 
13
 *-------------------------------------------------------------------------
 
14
 */
 
15
#include "postgres.h"
 
16
 
 
17
#include "access/heapam.h"
 
18
#include "access/transam.h"
 
19
#include "access/xact.h"
 
20
#include "access/xlogutils.h"
 
21
#include "catalog/dependency.h"
 
22
#include "catalog/namespace.h"
 
23
#include "catalog/pg_type.h"
 
24
#include "commands/defrem.h"
 
25
#include "commands/sequence.h"
 
26
#include "commands/tablecmds.h"
 
27
#include "miscadmin.h"
 
28
#include "nodes/makefuncs.h"
 
29
#include "storage/bufmgr.h"
 
30
#include "storage/lmgr.h"
 
31
#include "storage/proc.h"
 
32
#include "utils/acl.h"
 
33
#include "utils/builtins.h"
 
34
#include "utils/lsyscache.h"
 
35
#include "utils/resowner.h"
 
36
#include "utils/syscache.h"
 
37
 
 
38
 
 
39
/*
 
40
 * We don't want to log each fetching of a value from a sequence,
 
41
 * so we pre-log a few fetches in advance. In the event of
 
42
 * crash we can lose as much as we pre-logged.
 
43
 */
 
44
#define SEQ_LOG_VALS    32
 
45
 
 
46
/*
 
47
 * The "special area" of a sequence's buffer page looks like this.
 
48
 */
 
49
#define SEQ_MAGIC         0x1717
 
50
 
 
51
typedef struct sequence_magic
 
52
{
 
53
        uint32          magic;
 
54
} sequence_magic;
 
55
 
 
56
/*
 
57
 * We store a SeqTable item for every sequence we have touched in the current
 
58
 * session.  This is needed to hold onto nextval/currval state.  (We can't
 
59
 * rely on the relcache, since it's only, well, a cache, and may decide to
 
60
 * discard entries.)
 
61
 *
 
62
 * XXX We use linear search to find pre-existing SeqTable entries.      This is
 
63
 * good when only a small number of sequences are touched in a session, but
 
64
 * would suck with many different sequences.  Perhaps use a hashtable someday.
 
65
 */
 
66
typedef struct SeqTableData
 
67
{
 
68
        struct SeqTableData *next;      /* link to next SeqTable object */
 
69
        Oid                     relid;                  /* pg_class OID of this sequence */
 
70
        LocalTransactionId lxid;        /* xact in which we last did a seq op */
 
71
        bool            last_valid;             /* do we have a valid "last" value? */
 
72
        int64           last;                   /* value last returned by nextval */
 
73
        int64           cached;                 /* last value already cached for nextval */
 
74
        /* if last != cached, we have not used up all the cached values */
 
75
        int64           increment;              /* copy of sequence's increment field */
 
76
        /* note that increment is zero until we first do read_info() */
 
77
} SeqTableData;
 
78
 
 
79
typedef SeqTableData *SeqTable;
 
80
 
 
81
static SeqTable seqtab = NULL;  /* Head of list of SeqTable items */
 
82
 
 
83
/*
 
84
 * last_used_seq is updated by nextval() to point to the last used
 
85
 * sequence.
 
86
 */
 
87
static SeqTableData *last_used_seq = NULL;
 
88
 
 
89
static int64 nextval_internal(Oid relid);
 
90
static Relation open_share_lock(SeqTable seq);
 
91
static void init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel);
 
92
static Form_pg_sequence read_info(SeqTable elm, Relation rel, Buffer *buf);
 
93
static void init_params(List *options, bool isInit,
 
94
                        Form_pg_sequence new, List **owned_by);
 
95
static void do_setval(Oid relid, int64 next, bool iscalled);
 
96
static void process_owned_by(Relation seqrel, List *owned_by);
 
97
 
 
98
 
 
99
/*
 
100
 * DefineSequence
 
101
 *                              Creates a new sequence relation
 
102
 */
 
103
void
 
104
DefineSequence(CreateSeqStmt *seq)
 
105
{
 
106
        FormData_pg_sequence new;
 
107
        List       *owned_by;
 
108
        CreateStmt *stmt = makeNode(CreateStmt);
 
109
        Oid                     seqoid;
 
110
        Relation        rel;
 
111
        Buffer          buf;
 
112
        Page            page;
 
113
        sequence_magic *sm;
 
114
        HeapTuple       tuple;
 
115
        TupleDesc       tupDesc;
 
116
        Datum           value[SEQ_COL_LASTCOL];
 
117
        bool            null[SEQ_COL_LASTCOL];
 
118
        int                     i;
 
119
        NameData        name;
 
120
 
 
121
        /* Check and set all option values */
 
122
        init_params(seq->options, true, &new, &owned_by);
 
123
 
 
124
        /*
 
125
         * Create relation (and fill value[] and null[] for the tuple)
 
126
         */
 
127
        stmt->tableElts = NIL;
 
128
        for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
 
129
        {
 
130
                ColumnDef  *coldef = makeNode(ColumnDef);
 
131
 
 
132
                coldef->inhcount = 0;
 
133
                coldef->is_local = true;
 
134
                coldef->is_not_null = true;
 
135
                coldef->raw_default = NULL;
 
136
                coldef->cooked_default = NULL;
 
137
                coldef->constraints = NIL;
 
138
 
 
139
                null[i - 1] = false;
 
140
 
 
141
                switch (i)
 
142
                {
 
143
                        case SEQ_COL_NAME:
 
144
                                coldef->typename = makeTypeNameFromOid(NAMEOID, -1);
 
145
                                coldef->colname = "sequence_name";
 
146
                                namestrcpy(&name, seq->sequence->relname);
 
147
                                value[i - 1] = NameGetDatum(&name);
 
148
                                break;
 
149
                        case SEQ_COL_LASTVAL:
 
150
                                coldef->typename = makeTypeNameFromOid(INT8OID, -1);
 
151
                                coldef->colname = "last_value";
 
152
                                value[i - 1] = Int64GetDatumFast(new.last_value);
 
153
                                break;
 
154
                        case SEQ_COL_STARTVAL:
 
155
                                coldef->typename = makeTypeNameFromOid(INT8OID, -1);
 
156
                                coldef->colname = "start_value";
 
157
                                value[i - 1] = Int64GetDatumFast(new.start_value);
 
158
                                break;
 
159
                        case SEQ_COL_INCBY:
 
160
                                coldef->typename = makeTypeNameFromOid(INT8OID, -1);
 
161
                                coldef->colname = "increment_by";
 
162
                                value[i - 1] = Int64GetDatumFast(new.increment_by);
 
163
                                break;
 
164
                        case SEQ_COL_MAXVALUE:
 
165
                                coldef->typename = makeTypeNameFromOid(INT8OID, -1);
 
166
                                coldef->colname = "max_value";
 
167
                                value[i - 1] = Int64GetDatumFast(new.max_value);
 
168
                                break;
 
169
                        case SEQ_COL_MINVALUE:
 
170
                                coldef->typename = makeTypeNameFromOid(INT8OID, -1);
 
171
                                coldef->colname = "min_value";
 
172
                                value[i - 1] = Int64GetDatumFast(new.min_value);
 
173
                                break;
 
174
                        case SEQ_COL_CACHE:
 
175
                                coldef->typename = makeTypeNameFromOid(INT8OID, -1);
 
176
                                coldef->colname = "cache_value";
 
177
                                value[i - 1] = Int64GetDatumFast(new.cache_value);
 
178
                                break;
 
179
                        case SEQ_COL_LOG:
 
180
                                coldef->typename = makeTypeNameFromOid(INT8OID, -1);
 
181
                                coldef->colname = "log_cnt";
 
182
                                value[i - 1] = Int64GetDatum((int64) 1);
 
183
                                break;
 
184
                        case SEQ_COL_CYCLE:
 
185
                                coldef->typename = makeTypeNameFromOid(BOOLOID, -1);
 
186
                                coldef->colname = "is_cycled";
 
187
                                value[i - 1] = BoolGetDatum(new.is_cycled);
 
188
                                break;
 
189
                        case SEQ_COL_CALLED:
 
190
                                coldef->typename = makeTypeNameFromOid(BOOLOID, -1);
 
191
                                coldef->colname = "is_called";
 
192
                                value[i - 1] = BoolGetDatum(false);
 
193
                                break;
 
194
                }
 
195
                stmt->tableElts = lappend(stmt->tableElts, coldef);
 
196
        }
 
197
 
 
198
        stmt->relation = seq->sequence;
 
199
        stmt->inhRelations = NIL;
 
200
        stmt->constraints = NIL;
 
201
        stmt->options = list_make1(reloptWithOids(false));
 
202
        stmt->oncommit = ONCOMMIT_NOOP;
 
203
        stmt->tablespacename = NULL;
 
204
 
 
205
        seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
 
206
 
 
207
        rel = heap_open(seqoid, AccessExclusiveLock);
 
208
        tupDesc = RelationGetDescr(rel);
 
209
 
 
210
        /* Initialize first page of relation with special magic number */
 
211
 
 
212
        buf = ReadBuffer(rel, P_NEW);
 
213
        Assert(BufferGetBlockNumber(buf) == 0);
 
214
 
 
215
        page = BufferGetPage(buf);
 
216
 
 
217
        PageInit(page, BufferGetPageSize(buf), sizeof(sequence_magic));
 
218
        sm = (sequence_magic *) PageGetSpecialPointer(page);
 
219
        sm->magic = SEQ_MAGIC;
 
220
 
 
221
        /* hack: ensure heap_insert will insert on the just-created page */
 
222
        rel->rd_targblock = 0;
 
223
 
 
224
        /* Now form & insert sequence tuple */
 
225
        tuple = heap_form_tuple(tupDesc, value, null);
 
226
        simple_heap_insert(rel, tuple);
 
227
 
 
228
        Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);
 
229
 
 
230
        /*
 
231
         * Two special hacks here:
 
232
         *
 
233
         * 1. Since VACUUM does not process sequences, we have to force the tuple
 
234
         * to have xmin = FrozenTransactionId now.      Otherwise it would become
 
235
         * invisible to SELECTs after 2G transactions.  It is okay to do this
 
236
         * because if the current transaction aborts, no other xact will ever
 
237
         * examine the sequence tuple anyway.
 
238
         *
 
239
         * 2. Even though heap_insert emitted a WAL log record, we have to emit an
 
240
         * XLOG_SEQ_LOG record too, since (a) the heap_insert record will not have
 
241
         * the right xmin, and (b) REDO of the heap_insert record would re-init
 
242
         * page and sequence magic number would be lost.  This means two log
 
243
         * records instead of one :-(
 
244
         */
 
245
        LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 
246
 
 
247
        START_CRIT_SECTION();
 
248
 
 
249
        {
 
250
                /*
 
251
                 * Note that the "tuple" structure is still just a local tuple record
 
252
                 * created by heap_form_tuple; its t_data pointer doesn't point at the
 
253
                 * disk buffer.  To scribble on the disk buffer we need to fetch the
 
254
                 * item pointer.  But do the same to the local tuple, since that will
 
255
                 * be the source for the WAL log record, below.
 
256
                 */
 
257
                ItemId          itemId;
 
258
                Item            item;
 
259
 
 
260
                itemId = PageGetItemId((Page) page, FirstOffsetNumber);
 
261
                item = PageGetItem((Page) page, itemId);
 
262
 
 
263
                HeapTupleHeaderSetXmin((HeapTupleHeader) item, FrozenTransactionId);
 
264
                ((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;
 
265
 
 
266
                HeapTupleHeaderSetXmin(tuple->t_data, FrozenTransactionId);
 
267
                tuple->t_data->t_infomask |= HEAP_XMIN_COMMITTED;
 
268
        }
 
269
 
 
270
        MarkBufferDirty(buf);
 
271
 
 
272
        /* XLOG stuff */
 
273
        if (!rel->rd_istemp)
 
274
        {
 
275
                xl_seq_rec      xlrec;
 
276
                XLogRecPtr      recptr;
 
277
                XLogRecData rdata[2];
 
278
                Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
 
279
 
 
280
                /* We do not log first nextval call, so "advance" sequence here */
 
281
                /* Note we are scribbling on local tuple, not the disk buffer */
 
282
                newseq->is_called = true;
 
283
                newseq->log_cnt = 0;
 
284
 
 
285
                xlrec.node = rel->rd_node;
 
286
                rdata[0].data = (char *) &xlrec;
 
287
                rdata[0].len = sizeof(xl_seq_rec);
 
288
                rdata[0].buffer = InvalidBuffer;
 
289
                rdata[0].next = &(rdata[1]);
 
290
 
 
291
                rdata[1].data = (char *) tuple->t_data;
 
292
                rdata[1].len = tuple->t_len;
 
293
                rdata[1].buffer = InvalidBuffer;
 
294
                rdata[1].next = NULL;
 
295
 
 
296
                recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
 
297
 
 
298
                PageSetLSN(page, recptr);
 
299
                PageSetTLI(page, ThisTimeLineID);
 
300
        }
 
301
 
 
302
        END_CRIT_SECTION();
 
303
 
 
304
        UnlockReleaseBuffer(buf);
 
305
 
 
306
        /* process OWNED BY if given */
 
307
        if (owned_by)
 
308
                process_owned_by(rel, owned_by);
 
309
 
 
310
        heap_close(rel, NoLock);
 
311
}
 
312
 
 
313
/*
 
314
 * AlterSequence
 
315
 *
 
316
 * Modify the definition of a sequence relation
 
317
 */
 
318
void
 
319
AlterSequence(AlterSeqStmt *stmt)
 
320
{
 
321
        Oid                     relid;
 
322
 
 
323
        /* find sequence */
 
324
        relid = RangeVarGetRelid(stmt->sequence, false);
 
325
 
 
326
        /* allow ALTER to sequence owner only */
 
327
        /* if you change this, see also callers of AlterSequenceInternal! */
 
328
        if (!pg_class_ownercheck(relid, GetUserId()))
 
329
                aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
 
330
                                           stmt->sequence->relname);
 
331
 
 
332
        /* do the work */
 
333
        AlterSequenceInternal(relid, stmt->options);
 
334
}
 
335
 
 
336
/*
 
337
 * AlterSequenceInternal
 
338
 *
 
339
 * Same as AlterSequence except that the sequence is specified by OID
 
340
 * and we assume the caller already checked permissions.
 
341
 */
 
342
void
 
343
AlterSequenceInternal(Oid relid, List *options)
 
344
{
 
345
        SeqTable        elm;
 
346
        Relation        seqrel;
 
347
        Buffer          buf;
 
348
        Page            page;
 
349
        Form_pg_sequence seq;
 
350
        FormData_pg_sequence new;
 
351
        List       *owned_by;
 
352
 
 
353
        /* open and AccessShareLock sequence */
 
354
        init_sequence(relid, &elm, &seqrel);
 
355
 
 
356
        /* lock page' buffer and read tuple into new sequence structure */
 
357
        seq = read_info(elm, seqrel, &buf);
 
358
        page = BufferGetPage(buf);
 
359
 
 
360
        /* Copy old values of options into workspace */
 
361
        memcpy(&new, seq, sizeof(FormData_pg_sequence));
 
362
 
 
363
        /* Check and set new values */
 
364
        init_params(options, false, &new, &owned_by);
 
365
 
 
366
        /* Clear local cache so that we don't think we have cached numbers */
 
367
        /* Note that we do not change the currval() state */
 
368
        elm->cached = elm->last;
 
369
 
 
370
        /* Now okay to update the on-disk tuple */
 
371
        memcpy(seq, &new, sizeof(FormData_pg_sequence));
 
372
 
 
373
        START_CRIT_SECTION();
 
374
 
 
375
        MarkBufferDirty(buf);
 
376
 
 
377
        /* XLOG stuff */
 
378
        if (!seqrel->rd_istemp)
 
379
        {
 
380
                xl_seq_rec      xlrec;
 
381
                XLogRecPtr      recptr;
 
382
                XLogRecData rdata[2];
 
383
 
 
384
                xlrec.node = seqrel->rd_node;
 
385
                rdata[0].data = (char *) &xlrec;
 
386
                rdata[0].len = sizeof(xl_seq_rec);
 
387
                rdata[0].buffer = InvalidBuffer;
 
388
                rdata[0].next = &(rdata[1]);
 
389
 
 
390
                rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
 
391
                rdata[1].len = ((PageHeader) page)->pd_special -
 
392
                        ((PageHeader) page)->pd_upper;
 
393
                rdata[1].buffer = InvalidBuffer;
 
394
                rdata[1].next = NULL;
 
395
 
 
396
                recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
 
397
 
 
398
                PageSetLSN(page, recptr);
 
399
                PageSetTLI(page, ThisTimeLineID);
 
400
        }
 
401
 
 
402
        END_CRIT_SECTION();
 
403
 
 
404
        UnlockReleaseBuffer(buf);
 
405
 
 
406
        /* process OWNED BY if given */
 
407
        if (owned_by)
 
408
                process_owned_by(seqrel, owned_by);
 
409
 
 
410
        relation_close(seqrel, NoLock);
 
411
}
 
412
 
 
413
 
 
414
/*
 
415
 * Note: nextval with a text argument is no longer exported as a pg_proc
 
416
 * entry, but we keep it around to ease porting of C code that may have
 
417
 * called the function directly.
 
418
 */
 
419
Datum
 
420
nextval(PG_FUNCTION_ARGS)
 
421
{
 
422
        text       *seqin = PG_GETARG_TEXT_P(0);
 
423
        RangeVar   *sequence;
 
424
        Oid                     relid;
 
425
 
 
426
        sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin));
 
427
        relid = RangeVarGetRelid(sequence, false);
 
428
 
 
429
        PG_RETURN_INT64(nextval_internal(relid));
 
430
}
 
431
 
 
432
Datum
 
433
nextval_oid(PG_FUNCTION_ARGS)
 
434
{
 
435
        Oid                     relid = PG_GETARG_OID(0);
 
436
 
 
437
        PG_RETURN_INT64(nextval_internal(relid));
 
438
}
 
439
 
 
440
static int64
 
441
nextval_internal(Oid relid)
 
442
{
 
443
        SeqTable        elm;
 
444
        Relation        seqrel;
 
445
        Buffer          buf;
 
446
        Page            page;
 
447
        Form_pg_sequence seq;
 
448
        int64           incby,
 
449
                                maxv,
 
450
                                minv,
 
451
                                cache,
 
452
                                log,
 
453
                                fetch,
 
454
                                last;
 
455
        int64           result,
 
456
                                next,
 
457
                                rescnt = 0;
 
458
        bool            logit = false;
 
459
 
 
460
        /* open and AccessShareLock sequence */
 
461
        init_sequence(relid, &elm, &seqrel);
 
462
 
 
463
        if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK &&
 
464
                pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
 
465
                ereport(ERROR,
 
466
                                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
 
467
                                 errmsg("permission denied for sequence %s",
 
468
                                                RelationGetRelationName(seqrel))));
 
469
 
 
470
        if (elm->last != elm->cached)           /* some numbers were cached */
 
471
        {
 
472
                Assert(elm->last_valid);
 
473
                Assert(elm->increment != 0);
 
474
                elm->last += elm->increment;
 
475
                relation_close(seqrel, NoLock);
 
476
                last_used_seq = elm;
 
477
                return elm->last;
 
478
        }
 
479
 
 
480
        /* lock page' buffer and read tuple */
 
481
        seq = read_info(elm, seqrel, &buf);
 
482
        page = BufferGetPage(buf);
 
483
 
 
484
        last = next = result = seq->last_value;
 
485
        incby = seq->increment_by;
 
486
        maxv = seq->max_value;
 
487
        minv = seq->min_value;
 
488
        fetch = cache = seq->cache_value;
 
489
        log = seq->log_cnt;
 
490
 
 
491
        if (!seq->is_called)
 
492
        {
 
493
                rescnt++;                               /* last_value if not called */
 
494
                fetch--;
 
495
                log--;
 
496
        }
 
497
 
 
498
        /*
 
499
         * Decide whether we should emit a WAL log record.      If so, force up the
 
500
         * fetch count to grab SEQ_LOG_VALS more values than we actually need to
 
501
         * cache.  (These will then be usable without logging.)
 
502
         *
 
503
         * If this is the first nextval after a checkpoint, we must force a new
 
504
         * WAL record to be written anyway, else replay starting from the
 
505
         * checkpoint would fail to advance the sequence past the logged values.
 
506
         * In this case we may as well fetch extra values.
 
507
         */
 
508
        if (log < fetch)
 
509
        {
 
510
                /* forced log to satisfy local demand for values */
 
511
                fetch = log = fetch + SEQ_LOG_VALS;
 
512
                logit = true;
 
513
        }
 
514
        else
 
515
        {
 
516
                XLogRecPtr      redoptr = GetRedoRecPtr();
 
517
 
 
518
                if (XLByteLE(PageGetLSN(page), redoptr))
 
519
                {
 
520
                        /* last update of seq was before checkpoint */
 
521
                        fetch = log = fetch + SEQ_LOG_VALS;
 
522
                        logit = true;
 
523
                }
 
524
        }
 
525
 
 
526
        while (fetch)                           /* try to fetch cache [+ log ] numbers */
 
527
        {
 
528
                /*
 
529
                 * Check MAXVALUE for ascending sequences and MINVALUE for descending
 
530
                 * sequences
 
531
                 */
 
532
                if (incby > 0)
 
533
                {
 
534
                        /* ascending sequence */
 
535
                        if ((maxv >= 0 && next > maxv - incby) ||
 
536
                                (maxv < 0 && next + incby > maxv))
 
537
                        {
 
538
                                if (rescnt > 0)
 
539
                                        break;          /* stop fetching */
 
540
                                if (!seq->is_cycled)
 
541
                                {
 
542
                                        char            buf[100];
 
543
 
 
544
                                        snprintf(buf, sizeof(buf), INT64_FORMAT, maxv);
 
545
                                        ereport(ERROR,
 
546
                                                  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 
547
                                                   errmsg("nextval: reached maximum value of sequence \"%s\" (%s)",
 
548
                                                                  RelationGetRelationName(seqrel), buf)));
 
549
                                }
 
550
                                next = minv;
 
551
                        }
 
552
                        else
 
553
                                next += incby;
 
554
                }
 
555
                else
 
556
                {
 
557
                        /* descending sequence */
 
558
                        if ((minv < 0 && next < minv - incby) ||
 
559
                                (minv >= 0 && next + incby < minv))
 
560
                        {
 
561
                                if (rescnt > 0)
 
562
                                        break;          /* stop fetching */
 
563
                                if (!seq->is_cycled)
 
564
                                {
 
565
                                        char            buf[100];
 
566
 
 
567
                                        snprintf(buf, sizeof(buf), INT64_FORMAT, minv);
 
568
                                        ereport(ERROR,
 
569
                                                  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 
570
                                                   errmsg("nextval: reached minimum value of sequence \"%s\" (%s)",
 
571
                                                                  RelationGetRelationName(seqrel), buf)));
 
572
                                }
 
573
                                next = maxv;
 
574
                        }
 
575
                        else
 
576
                                next += incby;
 
577
                }
 
578
                fetch--;
 
579
                if (rescnt < cache)
 
580
                {
 
581
                        log--;
 
582
                        rescnt++;
 
583
                        last = next;
 
584
                        if (rescnt == 1)        /* if it's first result - */
 
585
                                result = next;  /* it's what to return */
 
586
                }
 
587
        }
 
588
 
 
589
        log -= fetch;                           /* adjust for any unfetched numbers */
 
590
        Assert(log >= 0);
 
591
 
 
592
        /* save info in local cache */
 
593
        elm->last = result;                     /* last returned number */
 
594
        elm->cached = last;                     /* last fetched number */
 
595
        elm->last_valid = true;
 
596
 
 
597
        last_used_seq = elm;
 
598
 
 
599
        START_CRIT_SECTION();
 
600
 
 
601
        MarkBufferDirty(buf);
 
602
 
 
603
        /* XLOG stuff */
 
604
        if (logit && !seqrel->rd_istemp)
 
605
        {
 
606
                xl_seq_rec      xlrec;
 
607
                XLogRecPtr      recptr;
 
608
                XLogRecData rdata[2];
 
609
 
 
610
                xlrec.node = seqrel->rd_node;
 
611
                rdata[0].data = (char *) &xlrec;
 
612
                rdata[0].len = sizeof(xl_seq_rec);
 
613
                rdata[0].buffer = InvalidBuffer;
 
614
                rdata[0].next = &(rdata[1]);
 
615
 
 
616
                /* set values that will be saved in xlog */
 
617
                seq->last_value = next;
 
618
                seq->is_called = true;
 
619
                seq->log_cnt = 0;
 
620
 
 
621
                rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
 
622
                rdata[1].len = ((PageHeader) page)->pd_special -
 
623
                        ((PageHeader) page)->pd_upper;
 
624
                rdata[1].buffer = InvalidBuffer;
 
625
                rdata[1].next = NULL;
 
626
 
 
627
                recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
 
628
 
 
629
                PageSetLSN(page, recptr);
 
630
                PageSetTLI(page, ThisTimeLineID);
 
631
        }
 
632
 
 
633
        /* update on-disk data */
 
634
        seq->last_value = last;         /* last fetched number */
 
635
        seq->is_called = true;
 
636
        seq->log_cnt = log;                     /* how much is logged */
 
637
 
 
638
        END_CRIT_SECTION();
 
639
 
 
640
        UnlockReleaseBuffer(buf);
 
641
 
 
642
        relation_close(seqrel, NoLock);
 
643
 
 
644
        return result;
 
645
}
 
646
 
 
647
Datum
 
648
currval_oid(PG_FUNCTION_ARGS)
 
649
{
 
650
        Oid                     relid = PG_GETARG_OID(0);
 
651
        int64           result;
 
652
        SeqTable        elm;
 
653
        Relation        seqrel;
 
654
 
 
655
        /* open and AccessShareLock sequence */
 
656
        init_sequence(relid, &elm, &seqrel);
 
657
 
 
658
        if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
 
659
                pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
 
660
                ereport(ERROR,
 
661
                                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
 
662
                                 errmsg("permission denied for sequence %s",
 
663
                                                RelationGetRelationName(seqrel))));
 
664
 
 
665
        if (!elm->last_valid)
 
666
                ereport(ERROR,
 
667
                                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 
668
                                 errmsg("currval of sequence \"%s\" is not yet defined in this session",
 
669
                                                RelationGetRelationName(seqrel))));
 
670
 
 
671
        result = elm->last;
 
672
 
 
673
        relation_close(seqrel, NoLock);
 
674
 
 
675
        PG_RETURN_INT64(result);
 
676
}
 
677
 
 
678
Datum
 
679
lastval(PG_FUNCTION_ARGS)
 
680
{
 
681
        Relation        seqrel;
 
682
        int64           result;
 
683
 
 
684
        if (last_used_seq == NULL)
 
685
                ereport(ERROR,
 
686
                                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 
687
                                 errmsg("lastval is not yet defined in this session")));
 
688
 
 
689
        /* Someone may have dropped the sequence since the last nextval() */
 
690
        if (!SearchSysCacheExists(RELOID,
 
691
                                                          ObjectIdGetDatum(last_used_seq->relid),
 
692
                                                          0, 0, 0))
 
693
                ereport(ERROR,
 
694
                                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 
695
                                 errmsg("lastval is not yet defined in this session")));
 
696
 
 
697
        seqrel = open_share_lock(last_used_seq);
 
698
 
 
699
        /* nextval() must have already been called for this sequence */
 
700
        Assert(last_used_seq->last_valid);
 
701
 
 
702
        if (pg_class_aclcheck(last_used_seq->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
 
703
                pg_class_aclcheck(last_used_seq->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
 
704
                ereport(ERROR,
 
705
                                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
 
706
                                 errmsg("permission denied for sequence %s",
 
707
                                                RelationGetRelationName(seqrel))));
 
708
 
 
709
        result = last_used_seq->last;
 
710
        relation_close(seqrel, NoLock);
 
711
 
 
712
        PG_RETURN_INT64(result);
 
713
}
 
714
 
 
715
/*
 
716
 * Main internal procedure that handles 2 & 3 arg forms of SETVAL.
 
717
 *
 
718
 * Note that the 3 arg version (which sets the is_called flag) is
 
719
 * only for use in pg_dump, and setting the is_called flag may not
 
720
 * work if multiple users are attached to the database and referencing
 
721
 * the sequence (unlikely if pg_dump is restoring it).
 
722
 *
 
723
 * It is necessary to have the 3 arg version so that pg_dump can
 
724
 * restore the state of a sequence exactly during data-only restores -
 
725
 * it is the only way to clear the is_called flag in an existing
 
726
 * sequence.
 
727
 */
 
728
static void
 
729
do_setval(Oid relid, int64 next, bool iscalled)
 
730
{
 
731
        SeqTable        elm;
 
732
        Relation        seqrel;
 
733
        Buffer          buf;
 
734
        Form_pg_sequence seq;
 
735
 
 
736
        /* open and AccessShareLock sequence */
 
737
        init_sequence(relid, &elm, &seqrel);
 
738
 
 
739
        if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
 
740
                ereport(ERROR,
 
741
                                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
 
742
                                 errmsg("permission denied for sequence %s",
 
743
                                                RelationGetRelationName(seqrel))));
 
744
 
 
745
        /* lock page' buffer and read tuple */
 
746
        seq = read_info(elm, seqrel, &buf);
 
747
 
 
748
        if ((next < seq->min_value) || (next > seq->max_value))
 
749
        {
 
750
                char            bufv[100],
 
751
                                        bufm[100],
 
752
                                        bufx[100];
 
753
 
 
754
                snprintf(bufv, sizeof(bufv), INT64_FORMAT, next);
 
755
                snprintf(bufm, sizeof(bufm), INT64_FORMAT, seq->min_value);
 
756
                snprintf(bufx, sizeof(bufx), INT64_FORMAT, seq->max_value);
 
757
                ereport(ERROR,
 
758
                                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
 
759
                                 errmsg("setval: value %s is out of bounds for sequence \"%s\" (%s..%s)",
 
760
                                                bufv, RelationGetRelationName(seqrel),
 
761
                                                bufm, bufx)));
 
762
        }
 
763
 
 
764
        /* Set the currval() state only if iscalled = true */
 
765
        if (iscalled)
 
766
        {
 
767
                elm->last = next;               /* last returned number */
 
768
                elm->last_valid = true;
 
769
        }
 
770
 
 
771
        /* In any case, forget any future cached numbers */
 
772
        elm->cached = elm->last;
 
773
 
 
774
        START_CRIT_SECTION();
 
775
 
 
776
        MarkBufferDirty(buf);
 
777
 
 
778
        /* XLOG stuff */
 
779
        if (!seqrel->rd_istemp)
 
780
        {
 
781
                xl_seq_rec      xlrec;
 
782
                XLogRecPtr      recptr;
 
783
                XLogRecData rdata[2];
 
784
                Page            page = BufferGetPage(buf);
 
785
 
 
786
                xlrec.node = seqrel->rd_node;
 
787
                rdata[0].data = (char *) &xlrec;
 
788
                rdata[0].len = sizeof(xl_seq_rec);
 
789
                rdata[0].buffer = InvalidBuffer;
 
790
                rdata[0].next = &(rdata[1]);
 
791
 
 
792
                /* set values that will be saved in xlog */
 
793
                seq->last_value = next;
 
794
                seq->is_called = true;
 
795
                seq->log_cnt = 0;
 
796
 
 
797
                rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
 
798
                rdata[1].len = ((PageHeader) page)->pd_special -
 
799
                        ((PageHeader) page)->pd_upper;
 
800
                rdata[1].buffer = InvalidBuffer;
 
801
                rdata[1].next = NULL;
 
802
 
 
803
                recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
 
804
 
 
805
                PageSetLSN(page, recptr);
 
806
                PageSetTLI(page, ThisTimeLineID);
 
807
        }
 
808
 
 
809
        /* save info in sequence relation */
 
810
        seq->last_value = next;         /* last fetched number */
 
811
        seq->is_called = iscalled;
 
812
        seq->log_cnt = (iscalled) ? 0 : 1;
 
813
 
 
814
        END_CRIT_SECTION();
 
815
 
 
816
        UnlockReleaseBuffer(buf);
 
817
 
 
818
        relation_close(seqrel, NoLock);
 
819
}
 
820
 
 
821
/*
 
822
 * Implement the 2 arg setval procedure.
 
823
 * See do_setval for discussion.
 
824
 */
 
825
Datum
 
826
setval_oid(PG_FUNCTION_ARGS)
 
827
{
 
828
        Oid                     relid = PG_GETARG_OID(0);
 
829
        int64           next = PG_GETARG_INT64(1);
 
830
 
 
831
        do_setval(relid, next, true);
 
832
 
 
833
        PG_RETURN_INT64(next);
 
834
}
 
835
 
 
836
/*
 
837
 * Implement the 3 arg setval procedure.
 
838
 * See do_setval for discussion.
 
839
 */
 
840
Datum
 
841
setval3_oid(PG_FUNCTION_ARGS)
 
842
{
 
843
        Oid                     relid = PG_GETARG_OID(0);
 
844
        int64           next = PG_GETARG_INT64(1);
 
845
        bool            iscalled = PG_GETARG_BOOL(2);
 
846
 
 
847
        do_setval(relid, next, iscalled);
 
848
 
 
849
        PG_RETURN_INT64(next);
 
850
}
 
851
 
 
852
 
 
853
/*
 
854
 * Open the sequence and acquire AccessShareLock if needed
 
855
 *
 
856
 * If we haven't touched the sequence already in this transaction,
 
857
 * we need to acquire AccessShareLock.  We arrange for the lock to
 
858
 * be owned by the top transaction, so that we don't need to do it
 
859
 * more than once per xact.
 
860
 */
 
861
static Relation
 
862
open_share_lock(SeqTable seq)
 
863
{
 
864
        LocalTransactionId thislxid = MyProc->lxid;
 
865
 
 
866
        /* Get the lock if not already held in this xact */
 
867
        if (seq->lxid != thislxid)
 
868
        {
 
869
                ResourceOwner currentOwner;
 
870
 
 
871
                currentOwner = CurrentResourceOwner;
 
872
                PG_TRY();
 
873
                {
 
874
                        CurrentResourceOwner = TopTransactionResourceOwner;
 
875
                        LockRelationOid(seq->relid, AccessShareLock);
 
876
                }
 
877
                PG_CATCH();
 
878
                {
 
879
                        /* Ensure CurrentResourceOwner is restored on error */
 
880
                        CurrentResourceOwner = currentOwner;
 
881
                        PG_RE_THROW();
 
882
                }
 
883
                PG_END_TRY();
 
884
                CurrentResourceOwner = currentOwner;
 
885
 
 
886
                /* Flag that we have a lock in the current xact */
 
887
                seq->lxid = thislxid;
 
888
        }
 
889
 
 
890
        /* We now know we have AccessShareLock, and can safely open the rel */
 
891
        return relation_open(seq->relid, NoLock);
 
892
}
 
893
 
 
894
/*
 
895
 * Given a relation OID, open and lock the sequence.  p_elm and p_rel are
 
896
 * output parameters.
 
897
 */
 
898
static void
 
899
init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel)
 
900
{
 
901
        SeqTable        elm;
 
902
        Relation        seqrel;
 
903
 
 
904
        /* Look to see if we already have a seqtable entry for relation */
 
905
        for (elm = seqtab; elm != NULL; elm = elm->next)
 
906
        {
 
907
                if (elm->relid == relid)
 
908
                        break;
 
909
        }
 
910
 
 
911
        /*
 
912
         * Allocate new seqtable entry if we didn't find one.
 
913
         *
 
914
         * NOTE: seqtable entries remain in the list for the life of a backend. If
 
915
         * the sequence itself is deleted then the entry becomes wasted memory,
 
916
         * but it's small enough that this should not matter.
 
917
         */
 
918
        if (elm == NULL)
 
919
        {
 
920
                /*
 
921
                 * Time to make a new seqtable entry.  These entries live as long as
 
922
                 * the backend does, so we use plain malloc for them.
 
923
                 */
 
924
                elm = (SeqTable) malloc(sizeof(SeqTableData));
 
925
                if (elm == NULL)
 
926
                        ereport(ERROR,
 
927
                                        (errcode(ERRCODE_OUT_OF_MEMORY),
 
928
                                         errmsg("out of memory")));
 
929
                elm->relid = relid;
 
930
                elm->lxid = InvalidLocalTransactionId;
 
931
                elm->last_valid = false;
 
932
                elm->last = elm->cached = elm->increment = 0;
 
933
                elm->next = seqtab;
 
934
                seqtab = elm;
 
935
        }
 
936
 
 
937
        /*
 
938
         * Open the sequence relation.
 
939
         */
 
940
        seqrel = open_share_lock(elm);
 
941
 
 
942
        if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
 
943
                ereport(ERROR,
 
944
                                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
 
945
                                 errmsg("\"%s\" is not a sequence",
 
946
                                                RelationGetRelationName(seqrel))));
 
947
 
 
948
        *p_elm = elm;
 
949
        *p_rel = seqrel;
 
950
}
 
951
 
 
952
 
 
953
/* Given an opened relation, lock the page buffer and find the tuple */
 
954
static Form_pg_sequence
 
955
read_info(SeqTable elm, Relation rel, Buffer *buf)
 
956
{
 
957
        Page            page;
 
958
        ItemId          lp;
 
959
        HeapTupleData tuple;
 
960
        sequence_magic *sm;
 
961
        Form_pg_sequence seq;
 
962
 
 
963
        *buf = ReadBuffer(rel, 0);
 
964
        LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);
 
965
 
 
966
        page = BufferGetPage(*buf);
 
967
        sm = (sequence_magic *) PageGetSpecialPointer(page);
 
968
 
 
969
        if (sm->magic != SEQ_MAGIC)
 
970
                elog(ERROR, "bad magic number in sequence \"%s\": %08X",
 
971
                         RelationGetRelationName(rel), sm->magic);
 
972
 
 
973
        lp = PageGetItemId(page, FirstOffsetNumber);
 
974
        Assert(ItemIdIsNormal(lp));
 
975
        tuple.t_data = (HeapTupleHeader) PageGetItem(page, lp);
 
976
 
 
977
        seq = (Form_pg_sequence) GETSTRUCT(&tuple);
 
978
 
 
979
        /* this is a handy place to update our copy of the increment */
 
980
        elm->increment = seq->increment_by;
 
981
 
 
982
        return seq;
 
983
}
 
984
 
 
985
/*
 
986
 * init_params: process the options list of CREATE or ALTER SEQUENCE,
 
987
 * and store the values into appropriate fields of *new.  Also set
 
988
 * *owned_by to any OWNED BY option, or to NIL if there is none.
 
989
 *
 
990
 * If isInit is true, fill any unspecified options with default values;
 
991
 * otherwise, do not change existing options that aren't explicitly overridden.
 
992
 */
 
993
static void
 
994
init_params(List *options, bool isInit,
 
995
                        Form_pg_sequence new, List **owned_by)
 
996
{
 
997
        DefElem    *start_value = NULL;
 
998
        DefElem    *restart_value = NULL;
 
999
        DefElem    *increment_by = NULL;
 
1000
        DefElem    *max_value = NULL;
 
1001
        DefElem    *min_value = NULL;
 
1002
        DefElem    *cache_value = NULL;
 
1003
        DefElem    *is_cycled = NULL;
 
1004
        ListCell   *option;
 
1005
 
 
1006
        *owned_by = NIL;
 
1007
 
 
1008
        foreach(option, options)
 
1009
        {
 
1010
                DefElem    *defel = (DefElem *) lfirst(option);
 
1011
 
 
1012
                if (strcmp(defel->defname, "increment") == 0)
 
1013
                {
 
1014
                        if (increment_by)
 
1015
                                ereport(ERROR,
 
1016
                                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1017
                                                 errmsg("conflicting or redundant options")));
 
1018
                        increment_by = defel;
 
1019
                }
 
1020
                else if (strcmp(defel->defname, "start") == 0)
 
1021
                {
 
1022
                        if (start_value)
 
1023
                                ereport(ERROR,
 
1024
                                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1025
                                                 errmsg("conflicting or redundant options")));
 
1026
                        start_value = defel;
 
1027
                }
 
1028
                else if (strcmp(defel->defname, "restart") == 0)
 
1029
                {
 
1030
                        if (restart_value)
 
1031
                                ereport(ERROR,
 
1032
                                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1033
                                                 errmsg("conflicting or redundant options")));
 
1034
                        restart_value = defel;
 
1035
                }
 
1036
                else if (strcmp(defel->defname, "maxvalue") == 0)
 
1037
                {
 
1038
                        if (max_value)
 
1039
                                ereport(ERROR,
 
1040
                                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1041
                                                 errmsg("conflicting or redundant options")));
 
1042
                        max_value = defel;
 
1043
                }
 
1044
                else if (strcmp(defel->defname, "minvalue") == 0)
 
1045
                {
 
1046
                        if (min_value)
 
1047
                                ereport(ERROR,
 
1048
                                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1049
                                                 errmsg("conflicting or redundant options")));
 
1050
                        min_value = defel;
 
1051
                }
 
1052
                else if (strcmp(defel->defname, "cache") == 0)
 
1053
                {
 
1054
                        if (cache_value)
 
1055
                                ereport(ERROR,
 
1056
                                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1057
                                                 errmsg("conflicting or redundant options")));
 
1058
                        cache_value = defel;
 
1059
                }
 
1060
                else if (strcmp(defel->defname, "cycle") == 0)
 
1061
                {
 
1062
                        if (is_cycled)
 
1063
                                ereport(ERROR,
 
1064
                                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1065
                                                 errmsg("conflicting or redundant options")));
 
1066
                        is_cycled = defel;
 
1067
                }
 
1068
                else if (strcmp(defel->defname, "owned_by") == 0)
 
1069
                {
 
1070
                        if (*owned_by)
 
1071
                                ereport(ERROR,
 
1072
                                                (errcode(ERRCODE_SYNTAX_ERROR),
 
1073
                                                 errmsg("conflicting or redundant options")));
 
1074
                        *owned_by = defGetQualifiedName(defel);
 
1075
                }
 
1076
                else
 
1077
                        elog(ERROR, "option \"%s\" not recognized",
 
1078
                                 defel->defname);
 
1079
        }
 
1080
 
 
1081
        /* INCREMENT BY */
 
1082
        if (increment_by != NULL)
 
1083
        {
 
1084
                new->increment_by = defGetInt64(increment_by);
 
1085
                if (new->increment_by == 0)
 
1086
                        ereport(ERROR,
 
1087
                                        (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
1088
                                         errmsg("INCREMENT must not be zero")));
 
1089
        }
 
1090
        else if (isInit)
 
1091
                new->increment_by = 1;
 
1092
 
 
1093
        /* CYCLE */
 
1094
        if (is_cycled != NULL)
 
1095
        {
 
1096
                new->is_cycled = intVal(is_cycled->arg);
 
1097
                Assert(new->is_cycled == false || new->is_cycled == true);
 
1098
        }
 
1099
        else if (isInit)
 
1100
                new->is_cycled = false;
 
1101
 
 
1102
        /* MAXVALUE (null arg means NO MAXVALUE) */
 
1103
        if (max_value != NULL && max_value->arg)
 
1104
                new->max_value = defGetInt64(max_value);
 
1105
        else if (isInit || max_value != NULL)
 
1106
        {
 
1107
                if (new->increment_by > 0)
 
1108
                        new->max_value = SEQ_MAXVALUE;          /* ascending seq */
 
1109
                else
 
1110
                        new->max_value = -1;    /* descending seq */
 
1111
        }
 
1112
 
 
1113
        /* MINVALUE (null arg means NO MINVALUE) */
 
1114
        if (min_value != NULL && min_value->arg)
 
1115
                new->min_value = defGetInt64(min_value);
 
1116
        else if (isInit || min_value != NULL)
 
1117
        {
 
1118
                if (new->increment_by > 0)
 
1119
                        new->min_value = 1; /* ascending seq */
 
1120
                else
 
1121
                        new->min_value = SEQ_MINVALUE;          /* descending seq */
 
1122
        }
 
1123
 
 
1124
        /* crosscheck min/max */
 
1125
        if (new->min_value >= new->max_value)
 
1126
        {
 
1127
                char            bufm[100],
 
1128
                                        bufx[100];
 
1129
 
 
1130
                snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
 
1131
                snprintf(bufx, sizeof(bufx), INT64_FORMAT, new->max_value);
 
1132
                ereport(ERROR,
 
1133
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
1134
                                 errmsg("MINVALUE (%s) must be less than MAXVALUE (%s)",
 
1135
                                                bufm, bufx)));
 
1136
        }
 
1137
 
 
1138
        /* START WITH */
 
1139
        if (start_value != NULL)
 
1140
                new->start_value = defGetInt64(start_value);
 
1141
        else if (isInit)
 
1142
        {
 
1143
                if (new->increment_by > 0)
 
1144
                        new->start_value = new->min_value;      /* ascending seq */
 
1145
                else
 
1146
                        new->start_value = new->max_value;      /* descending seq */
 
1147
        }
 
1148
 
 
1149
        /* crosscheck START */
 
1150
        if (new->start_value < new->min_value)
 
1151
        {
 
1152
                char            bufs[100],
 
1153
                                        bufm[100];
 
1154
 
 
1155
                snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->start_value);
 
1156
                snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
 
1157
                ereport(ERROR,
 
1158
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
1159
                                 errmsg("START value (%s) cannot be less than MINVALUE (%s)",
 
1160
                                                bufs, bufm)));
 
1161
        }
 
1162
        if (new->start_value > new->max_value)
 
1163
        {
 
1164
                char            bufs[100],
 
1165
                                        bufm[100];
 
1166
 
 
1167
                snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->start_value);
 
1168
                snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
 
1169
                ereport(ERROR,
 
1170
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
1171
                          errmsg("START value (%s) cannot be greater than MAXVALUE (%s)",
 
1172
                                         bufs, bufm)));
 
1173
        }
 
1174
 
 
1175
        /* RESTART [WITH] */
 
1176
        if (restart_value != NULL)
 
1177
        {
 
1178
                if (restart_value->arg != NULL)
 
1179
                        new->last_value = defGetInt64(restart_value);
 
1180
                else
 
1181
                        new->last_value = new->start_value;
 
1182
                new->is_called = false;
 
1183
                new->log_cnt = 1;
 
1184
        }
 
1185
        else if (isInit)
 
1186
        {
 
1187
                new->last_value = new->start_value;
 
1188
                new->is_called = false;
 
1189
                new->log_cnt = 1;
 
1190
        }
 
1191
 
 
1192
        /* crosscheck RESTART (or current value, if changing MIN/MAX) */
 
1193
        if (new->last_value < new->min_value)
 
1194
        {
 
1195
                char            bufs[100],
 
1196
                                        bufm[100];
 
1197
 
 
1198
                snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
 
1199
                snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
 
1200
                ereport(ERROR,
 
1201
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
1202
                                 errmsg("RESTART value (%s) cannot be less than MINVALUE (%s)",
 
1203
                                                bufs, bufm)));
 
1204
        }
 
1205
        if (new->last_value > new->max_value)
 
1206
        {
 
1207
                char            bufs[100],
 
1208
                                        bufm[100];
 
1209
 
 
1210
                snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
 
1211
                snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
 
1212
                ereport(ERROR,
 
1213
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
1214
                          errmsg("RESTART value (%s) cannot be greater than MAXVALUE (%s)",
 
1215
                                         bufs, bufm)));
 
1216
        }
 
1217
 
 
1218
        /* CACHE */
 
1219
        if (cache_value != NULL)
 
1220
        {
 
1221
                new->cache_value = defGetInt64(cache_value);
 
1222
                if (new->cache_value <= 0)
 
1223
                {
 
1224
                        char            buf[100];
 
1225
 
 
1226
                        snprintf(buf, sizeof(buf), INT64_FORMAT, new->cache_value);
 
1227
                        ereport(ERROR,
 
1228
                                        (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 
1229
                                         errmsg("CACHE (%s) must be greater than zero",
 
1230
                                                        buf)));
 
1231
                }
 
1232
        }
 
1233
        else if (isInit)
 
1234
                new->cache_value = 1;
 
1235
}
 
1236
 
 
1237
/*
 
1238
 * Process an OWNED BY option for CREATE/ALTER SEQUENCE
 
1239
 *
 
1240
 * Ownership permissions on the sequence are already checked,
 
1241
 * but if we are establishing a new owned-by dependency, we must
 
1242
 * enforce that the referenced table has the same owner and namespace
 
1243
 * as the sequence.
 
1244
 */
 
1245
static void
 
1246
process_owned_by(Relation seqrel, List *owned_by)
 
1247
{
 
1248
        int                     nnames;
 
1249
        Relation        tablerel;
 
1250
        AttrNumber      attnum;
 
1251
 
 
1252
        nnames = list_length(owned_by);
 
1253
        Assert(nnames > 0);
 
1254
        if (nnames == 1)
 
1255
        {
 
1256
                /* Must be OWNED BY NONE */
 
1257
                if (strcmp(strVal(linitial(owned_by)), "none") != 0)
 
1258
                        ereport(ERROR,
 
1259
                                        (errcode(ERRCODE_SYNTAX_ERROR),
 
1260
                                         errmsg("invalid OWNED BY option"),
 
1261
                                errhint("Specify OWNED BY table.column or OWNED BY NONE.")));
 
1262
                tablerel = NULL;
 
1263
                attnum = 0;
 
1264
        }
 
1265
        else
 
1266
        {
 
1267
                List       *relname;
 
1268
                char       *attrname;
 
1269
                RangeVar   *rel;
 
1270
 
 
1271
                /* Separate relname and attr name */
 
1272
                relname = list_truncate(list_copy(owned_by), nnames - 1);
 
1273
                attrname = strVal(lfirst(list_tail(owned_by)));
 
1274
 
 
1275
                /* Open and lock rel to ensure it won't go away meanwhile */
 
1276
                rel = makeRangeVarFromNameList(relname);
 
1277
                tablerel = relation_openrv(rel, AccessShareLock);
 
1278
 
 
1279
                /* Must be a regular table */
 
1280
                if (tablerel->rd_rel->relkind != RELKIND_RELATION)
 
1281
                        ereport(ERROR,
 
1282
                                        (errcode(ERRCODE_WRONG_OBJECT_TYPE),
 
1283
                                         errmsg("referenced relation \"%s\" is not a table",
 
1284
                                                        RelationGetRelationName(tablerel))));
 
1285
 
 
1286
                /* We insist on same owner and schema */
 
1287
                if (seqrel->rd_rel->relowner != tablerel->rd_rel->relowner)
 
1288
                        ereport(ERROR,
 
1289
                                        (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 
1290
                                         errmsg("sequence must have same owner as table it is linked to")));
 
1291
                if (RelationGetNamespace(seqrel) != RelationGetNamespace(tablerel))
 
1292
                        ereport(ERROR,
 
1293
                                        (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 
1294
                                         errmsg("sequence must be in same schema as table it is linked to")));
 
1295
 
 
1296
                /* Now, fetch the attribute number from the system cache */
 
1297
                attnum = get_attnum(RelationGetRelid(tablerel), attrname);
 
1298
                if (attnum == InvalidAttrNumber)
 
1299
                        ereport(ERROR,
 
1300
                                        (errcode(ERRCODE_UNDEFINED_COLUMN),
 
1301
                                         errmsg("column \"%s\" of relation \"%s\" does not exist",
 
1302
                                                        attrname, RelationGetRelationName(tablerel))));
 
1303
        }
 
1304
 
 
1305
        /*
 
1306
         * OK, we are ready to update pg_depend.  First remove any existing AUTO
 
1307
         * dependencies for the sequence, then optionally add a new one.
 
1308
         */
 
1309
        markSequenceUnowned(RelationGetRelid(seqrel));
 
1310
 
 
1311
        if (tablerel)
 
1312
        {
 
1313
                ObjectAddress refobject,
 
1314
                                        depobject;
 
1315
 
 
1316
                refobject.classId = RelationRelationId;
 
1317
                refobject.objectId = RelationGetRelid(tablerel);
 
1318
                refobject.objectSubId = attnum;
 
1319
                depobject.classId = RelationRelationId;
 
1320
                depobject.objectId = RelationGetRelid(seqrel);
 
1321
                depobject.objectSubId = 0;
 
1322
                recordDependencyOn(&depobject, &refobject, DEPENDENCY_AUTO);
 
1323
        }
 
1324
 
 
1325
        /* Done, but hold lock until commit */
 
1326
        if (tablerel)
 
1327
                relation_close(tablerel, NoLock);
 
1328
}
 
1329
 
 
1330
 
 
1331
void
 
1332
seq_redo(XLogRecPtr lsn, XLogRecord *record)
 
1333
{
 
1334
        uint8           info = record->xl_info & ~XLR_INFO_MASK;
 
1335
        Buffer          buffer;
 
1336
        Page            page;
 
1337
        char       *item;
 
1338
        Size            itemsz;
 
1339
        xl_seq_rec *xlrec = (xl_seq_rec *) XLogRecGetData(record);
 
1340
        sequence_magic *sm;
 
1341
 
 
1342
        /* Backup blocks are not used in seq records */
 
1343
        Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
 
1344
 
 
1345
        if (info != XLOG_SEQ_LOG)
 
1346
                elog(PANIC, "seq_redo: unknown op code %u", info);
 
1347
 
 
1348
        buffer = XLogReadBuffer(xlrec->node, 0, true);
 
1349
        Assert(BufferIsValid(buffer));
 
1350
        page = (Page) BufferGetPage(buffer);
 
1351
 
 
1352
        /* Always reinit the page and reinstall the magic number */
 
1353
        /* See comments in DefineSequence */
 
1354
        PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
 
1355
        sm = (sequence_magic *) PageGetSpecialPointer(page);
 
1356
        sm->magic = SEQ_MAGIC;
 
1357
 
 
1358
        item = (char *) xlrec + sizeof(xl_seq_rec);
 
1359
        itemsz = record->xl_len - sizeof(xl_seq_rec);
 
1360
        itemsz = MAXALIGN(itemsz);
 
1361
        if (PageAddItem(page, (Item) item, itemsz,
 
1362
                                        FirstOffsetNumber, false, false) == InvalidOffsetNumber)
 
1363
                elog(PANIC, "seq_redo: failed to add item to page");
 
1364
 
 
1365
        PageSetLSN(page, lsn);
 
1366
        PageSetTLI(page, ThisTimeLineID);
 
1367
        MarkBufferDirty(buffer);
 
1368
        UnlockReleaseBuffer(buffer);
 
1369
}
 
1370
 
 
1371
void
 
1372
seq_desc(StringInfo buf, uint8 xl_info, char *rec)
 
1373
{
 
1374
        uint8           info = xl_info & ~XLR_INFO_MASK;
 
1375
        xl_seq_rec *xlrec = (xl_seq_rec *) rec;
 
1376
 
 
1377
        if (info == XLOG_SEQ_LOG)
 
1378
                appendStringInfo(buf, "log: ");
 
1379
        else
 
1380
        {
 
1381
                appendStringInfo(buf, "UNKNOWN");
 
1382
                return;
 
1383
        }
 
1384
 
 
1385
        appendStringInfo(buf, "rel %u/%u/%u",
 
1386
                           xlrec->node.spcNode, xlrec->node.dbNode, xlrec->node.relNode);
 
1387
}