473,779 Members | 2,078 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Restart increment to 0 each year = re-invent the sequences mecanism?

Hello,

I have to design a table wich will store some action reports. Each
report have an ID like this 1/2004, 2/2004, ... and each years, they
restart to 1 (1/2004, 1/2005, 1/2006,...).

So, I was thinking to split that in two fields : one with the increment
and one with the year. But I don't know how can I manage the sequences
since I have to restart to 0 each year...

Do you think I should re-invent the sequences mecanism with a second
table and a stored procedure, only to manage theses 'home-made' sequences ?

Or should I create some sequences like myseq_2004, myseq_2004,
my_seq_2005,... and use a concatenation of the myseq_ string and the
current year when calling nextval and curvall ?

Or is there another way to do that ?

Thanks in advance :-)

--
Bruno Baguette - pg******@baguet te.net

---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postg resql.org so that your
message can get through to the mailing list cleanly

Nov 23 '05
18 4005
> You don't have to mess with sequences.
If there are two fields ID and year then the next number is:

next_number := ( select ID from table_name where year =
year_from_curre nt_date order by ID desc limit 1 ) + 1;


Gee, I wonder why no one else thought of that... lets see, what is this
thing I've heard about called, er, what was that word... oh yeah, I
remember: "concurrenc y". Hmm, I wonder...

CREATE TABLE test.test_table
(
column1 int4 DEFAULT 0,
column2 int4 DEFAULT 0
);

INSERT INTO test.test_table VALUES (1,0);

-- Process #1
BEGIN;
UPDATE test.test_table SET column2 = 1+(SELECT column2
FROM test.test_table
WHERE column1=1
ORDER BY column2 DESC
LIMIT 1);

/* ... */

-- Process #2
BEGIN;
UPDATE test.test_table SET column2 = 1+(SELECT column2
FROM test.test_table
WHERE column1=1
ORDER BY column2 DESC
LIMIT 1);

-- Note: Process #2 hangs indefinitely at this point.

COMMIT;
SELECT * FROM test.test_table ;

/* ... */

-- Process #1
COMMIT;
SELECT * FROM test.test_table ;

-- Result: (1,1)
/* ... */

-- Process #2
-- Result: (1,1)

-- "D-"

--Berend Tober


---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 23 '05 #11
bt****@computer .org said:
CREATE OR REPLACE FUNCTION expense_report_ next(int4)
RETURNS int4 AS
'
DECLARE
l_employee_pk ALIAS FOR $1;
BEGIN
UPDATE employee
SET expense_report_ seq = (expense_report _seq + 1)
WHERE employee_pk = l_employee_pk;
RETURN (SELECT expense_report_ seq FROM employee WHERE employee_pk =
l_employee_pk) ;
END;'
LANGUAGE 'plpgsql' VOLATILE;

/*
NOTE: I'm informed by good sources that the stored procedure defined
above handles concurrency issues correctly because 1) the UPDATE
statment locks the record until a COMMIT is invoked, so the subsequent
SELECT will return YOUR incremented value, not someone else's, and
2) since this procedure is called from within an ON INSERT trigger, it
therefore occurs within a transaction block (which is established
implicitly by the trigger).
*/


Actually, I'm not sure that this procedure is safe. It might be possible
to get a race condition where the RETURN (SELECT .... ) retrieves the
value generated by another invocation of the procedure by another process
for the same employee - but this depends on when the row is unlocked.

Perhaps the following would avoid the problem (if there is such a problem)

-- get current value, and lock row
SELECT expense_report_ seq INTO vSeqNum
FROM employee
WHERE employee_pk = l_employee_pk
FOR UPDATE;

-- increment the counter, and release the lock?
UPDATE employee
SET expense_report_ seq = (expense_report _seq + 1)
WHERE employee_pk = l_employee_pk;

-- return the correct value
return (1 + vSeqNum);

In the above example, generation of the correct sequence and the updating
of the record is effectively atomic by virtue of the row level lock
(enforced by the "FOR UPDATE" statement). Whereas in your version it may
be possible to get a different value from the one you just updated - again
I'm not sure about this. Perhaps someone who is sure can illuminate this
for me.

With had nested transactions, then addition of a commit statement in the
procedure would make the release of the lock explicit.

Thanks

John Sidney-Woollett

---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 23 '05 #12
bt****@computer .org said:
CREATE OR REPLACE FUNCTION expense_report_ next(int4)
RETURNS int4 AS
'
DECLARE
l_employee_pk ALIAS FOR $1;
BEGIN
UPDATE employee
SET expense_report_ seq = (expense_report _seq + 1)
WHERE employee_pk = l_employee_pk;
RETURN (SELECT expense_report_ seq FROM employee WHERE employee_pk =
l_employee_pk) ;
END;'
LANGUAGE 'plpgsql' VOLATILE;

/*
NOTE: I'm informed by good sources that the stored procedure defined
above handles concurrency issues correctly because 1) the UPDATE
statment locks the record until a COMMIT is invoked, so the subsequent
SELECT will return YOUR incremented value, not someone else's, and
2) since this procedure is called from within an ON INSERT trigger, it
therefore occurs within a transaction block (which is established
implicitly by the trigger).
*/


Actually, I'm not sure that this procedure is safe. It might be possible
to get a race condition where the RETURN (SELECT .... ) retrieves the
value generated by another invocation of the procedure by another process
for the same employee - but this depends on when the row is unlocked.

Perhaps the following would avoid the problem (if there is such a problem)

-- get current value, and lock row
SELECT expense_report_ seq INTO vSeqNum
FROM employee
WHERE employee_pk = l_employee_pk
FOR UPDATE;

-- increment the counter, and release the lock?
UPDATE employee
SET expense_report_ seq = (expense_report _seq + 1)
WHERE employee_pk = l_employee_pk;

-- return the correct value
return (1 + vSeqNum);

In the above example, generation of the correct sequence and the updating
of the record is effectively atomic by virtue of the row level lock
(enforced by the "FOR UPDATE" statement). Whereas in your version it may
be possible to get a different value from the one you just updated - again
I'm not sure about this. Perhaps someone who is sure can illuminate this
for me.

With had nested transactions, then addition of a commit statement in the
procedure would make the release of the lock explicit.

Thanks

John Sidney-Woollett

---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 23 '05 #13
bt****@computer .org said:
How "not sure" are you?
Not "not sure" at all.
But I'd welcome a correction to my
thinking from anyone that really-truely-for-sure (like in source code
level intimacy) knows.


Me too!

Because while I was blissfully sure in my ignorance before, now I'm really
not sure! :)

John Sidney-Woollett

---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 23 '05 #14
bt****@computer .org said:
How "not sure" are you?
Not "not sure" at all.
But I'd welcome a correction to my
thinking from anyone that really-truely-for-sure (like in source code
level intimacy) knows.


Me too!

Because while I was blissfully sure in my ignorance before, now I'm really
not sure! :)

John Sidney-Woollett

---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 23 '05 #15
On Mon, Apr 26, 2004 at 09:38:41 -0400,
bt****@computer .org wrote:
You don't have to mess with sequences.
If there are two fields ID and year then the next number is:

next_number := ( select ID from table_name where year =
year_from_curre nt_date order by ID desc limit 1 ) + 1;


Gee, I wonder why no one else thought of that... lets see, what is this
thing I've heard about called, er, what was that word... oh yeah, I
remember: "concurrenc y". Hmm, I wonder...


Yes, you need to do a lock table if you do things that way. But that
still is probably what he wants to do. Sequences can leave gaps, which
he probably doesn't want. If that is true then things need to be
serialized somehow. I doubt that these reports are being generated
at such a rate that he needs to worry about contention problems with
locking the table.

---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)

Nov 23 '05 #16
On Mon, Apr 26, 2004 at 09:38:41 -0400,
bt****@computer .org wrote:
You don't have to mess with sequences.
If there are two fields ID and year then the next number is:

next_number := ( select ID from table_name where year =
year_from_curre nt_date order by ID desc limit 1 ) + 1;


Gee, I wonder why no one else thought of that... lets see, what is this
thing I've heard about called, er, what was that word... oh yeah, I
remember: "concurrenc y". Hmm, I wonder...


Yes, you need to do a lock table if you do things that way. But that
still is probably what he wants to do. Sequences can leave gaps, which
he probably doesn't want. If that is true then things need to be
serialized somehow. I doubt that these reports are being generated
at such a rate that he needs to worry about contention problems with
locking the table.

---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)

Nov 23 '05 #17
> bt****@computer .org said:
CREATE OR REPLACE FUNCTION expense_report_ next(int4)
RETURNS int4 AS
'
DECLARE
l_employee_pk ALIAS FOR $1;
BEGIN
UPDATE employee
SET expense_report_ seq = (expense_report _seq + 1)
WHERE employee_pk = l_employee_pk;
RETURN (SELECT expense_report_ seq FROM employee WHERE employee_pk =
l_employee_pk) ;
END;'
LANGUAGE 'plpgsql' VOLATILE;

/*
NOTE: I'm informed by good sources that the stored procedure defined
above handles concurrency issues correctly because 1) the UPDATE
statment locks the record until a COMMIT is invoked, so the
subsequent SELECT will return YOUR incremented value, not someone
else's, and 2) since this procedure is called from within an ON
INSERT trigger, it therefore occurs within a transaction block (which
is established implicitly by the trigger).
*/
Actually, I'm not sure that this procedure is safe.


How "not sure" are you?
It might be
possible to get a race condition where the RETURN (SELECT .... )
retrieves the value generated by another invocation of the procedure by
another process for the same employee - but this depends on when the
row is unlocked.
It isn't. At least in my testing anyway, where I have stepped through the
the sequence of events by using two separate processes and observed the
fact the the second process is blocked on the UPDATE until the first
completes. What was explained to me by other guru's in this forum is that
the row is unlocked at the end of the trigger (which is what invokes this
procedure), so a second invocation of the trigger for the same employee
waits until the first is complete. It may depend on the locking level
that is set for an particular database, but I've seen it working, albeit
in a not-to-heavily used database.
Perhaps the following would avoid the problem (if there is such a
problem)

-- get current value, and lock row
SELECT expense_report_ seq INTO vSeqNum
FROM employee
WHERE employee_pk = l_employee_pk
FOR UPDATE;

-- increment the counter, and release the lock?
UPDATE employee
SET expense_report_ seq = (expense_report _seq + 1)
WHERE employee_pk = l_employee_pk;

-- return the correct value
return (1 + vSeqNum);
That works too, but my method accomplishes the same thing without having
to declare the local variable vSeqNum.
In the above example, generation of the correct sequence and the
updating of the record is effectively atomic by virtue of the row level
lock (enforced by the "FOR UPDATE" statement). Whereas in your version
it may be possible to get a different value from the one you just
updated - again I'm not sure about this. Perhaps someone who is sure
can illuminate this for me.
Yes. No it is not -- I'm pretty sure. But I'd welcome a correction to my
thinking from anyone that really-truely-for-sure (like in source code
level intimacy) knows.

With had nested transactions, then addition of a commit statement in
the procedure would make the release of the lock explicit.


Unnecessary, in this case.

--Berend Tober

---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings

Nov 23 '05 #18
> bt****@computer .org said:
CREATE OR REPLACE FUNCTION expense_report_ next(int4)
RETURNS int4 AS
'
DECLARE
l_employee_pk ALIAS FOR $1;
BEGIN
UPDATE employee
SET expense_report_ seq = (expense_report _seq + 1)
WHERE employee_pk = l_employee_pk;
RETURN (SELECT expense_report_ seq FROM employee WHERE employee_pk =
l_employee_pk) ;
END;'
LANGUAGE 'plpgsql' VOLATILE;

/*
NOTE: I'm informed by good sources that the stored procedure defined
above handles concurrency issues correctly because 1) the UPDATE
statment locks the record until a COMMIT is invoked, so the
subsequent SELECT will return YOUR incremented value, not someone
else's, and 2) since this procedure is called from within an ON
INSERT trigger, it therefore occurs within a transaction block (which
is established implicitly by the trigger).
*/
Actually, I'm not sure that this procedure is safe.


How "not sure" are you?
It might be
possible to get a race condition where the RETURN (SELECT .... )
retrieves the value generated by another invocation of the procedure by
another process for the same employee - but this depends on when the
row is unlocked.
It isn't. At least in my testing anyway, where I have stepped through the
the sequence of events by using two separate processes and observed the
fact the the second process is blocked on the UPDATE until the first
completes. What was explained to me by other guru's in this forum is that
the row is unlocked at the end of the trigger (which is what invokes this
procedure), so a second invocation of the trigger for the same employee
waits until the first is complete. It may depend on the locking level
that is set for an particular database, but I've seen it working, albeit
in a not-to-heavily used database.
Perhaps the following would avoid the problem (if there is such a
problem)

-- get current value, and lock row
SELECT expense_report_ seq INTO vSeqNum
FROM employee
WHERE employee_pk = l_employee_pk
FOR UPDATE;

-- increment the counter, and release the lock?
UPDATE employee
SET expense_report_ seq = (expense_report _seq + 1)
WHERE employee_pk = l_employee_pk;

-- return the correct value
return (1 + vSeqNum);
That works too, but my method accomplishes the same thing without having
to declare the local variable vSeqNum.
In the above example, generation of the correct sequence and the
updating of the record is effectively atomic by virtue of the row level
lock (enforced by the "FOR UPDATE" statement). Whereas in your version
it may be possible to get a different value from the one you just
updated - again I'm not sure about this. Perhaps someone who is sure
can illuminate this for me.
Yes. No it is not -- I'm pretty sure. But I'd welcome a correction to my
thinking from anyone that really-truely-for-sure (like in source code
level intimacy) knows.

With had nested transactions, then addition of a commit statement in
the procedure would make the release of the lock explicit.


Unnecessary, in this case.

--Berend Tober

---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings

Nov 23 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
2047
by: MikeT | last post by:
I have a page that produces little thumbnails of the 3D models it finds in a specified directory (and iterates down through any sub directories). It basically scans each directory for 3D Studio Max files using the filesystemobject and writes an activeX component called iDrop for each file so it can be displayed on the page (and drag-dropped straight into Max). If it happens to find a similarly named XML file in the directory, it loads...
34
2132
by: VK | last post by:
And this script supposes to work everywhere. It allows to get the name of any function from within the function itself. <html> <head> <title>Function name</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script type="text/javascript">
12
3564
by: Herby | last post by:
Hi, I am currently reviewing what is required to convert a current MFC, COM server application into a .NET application. The objective is to compile ultimately to clr/safe. So we are seeking a clear migration path for C++\MFC\COM to .NET. We have now chosen to select C++\CLI. We then need to remove the MFC classes such as CString CArray CMap etc
7
3806
by: David Freeman | last post by:
Hi There! I'm trying to create a User Registration page in ASP.NET and wondering what is the best way to get the list of up-to-date Countries and Cities? Are there any Web Services on the web that I can use to retrieve such information? If not, what are the options? Please, any suggestions and pointers will be very much appreciated! Dave
8
9322
by: kenneth fleckenstein nielsen | last post by:
hi guru's I want to restart my webservice when ever it throws an exception that isn't cought. can i do that by web.config or iss or how ??
22
2200
by: Joe Smith | last post by:
It is nothing short of embarrassing to feel the need to ask for help on this. I can't see how I would make the main control for this. What I want is a for loop and a test condition. And while I know, from things I pondered 2 decades ago, that a fella can write code without a goto, I'm stuck. /* sieve1.c */ #define whatever 20 #define N whatever
10
2040
by: el__marcin | last post by:
hi I am using MS office Access 2003. ANybody knows how to convert more than 300-400K rows from text into e.g. number ? I tried to do so a few times and access told me there aint enough memory or something. Anybody knows quick fix to that problem ? thanks
1
2220
by: lisa.engblom | last post by:
Hi, I am using matplotlib with python to generate a bunch of charts. My code works fine for a single iteration, which creates and saves 4 different charts. The trouble is that when I try to run it for the entire set (about 200 items) it can run for 12 items at a time. On the 13th, I get an error from matplotlib that says it can't access data. However, if I start the program at the point it failed before it works fine and will create...
7
2189
by: zb | last post by:
I am not convinced and need your opinion. My understanding is that if bin directory's content is changed then the ASP.Net application recycles (Applicatin is restarted). Is it also true for the web.config file. When Application is restarted all sessions are cleared. Now, if the application is running and a change is made in web.config file if this triggers application restart it will clear all sessions?
10
7601
by: =?Utf-8?B?U3RlZmFuIEJhcmxvdw==?= | last post by:
This has been working perfectly for months. Since we switched from ASP.NET 1.1 to 2.0, we have constant and sporadic issues with updating our applications. Touching the web.config works about 40% of the time to cause an AppDomain to reload and flush all assemblies. Sometimes it works perfectly, but other times some Assemblies are not reloaded into the AppDomain, even after multiple web.config file touches. Sometimes multiple versions...
0
10139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10075
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9931
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.