473,811 Members | 3,055 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Lock strategies!

Hi guys,

I have a simple table:

teste=# \d forn
Table "public.for n"
Column | Type | Modifiers
---------+---------+------------------------------------------------------
id | integer | not null default
nextval('public .forn_id_seq':: text)
forn_id | integer |
descrip | text |

Ok! The forn_id is supposed to be sequencial and
without holes (if someone perform a DELETE or UPDATE,
so there will be a hole... no problem if the hole
happens in this case!).

Well, to know the next value of the forn_id column, it
was planned to be done like this:

teste=# INSERT INTO forn (forn_id,descri p) VALUES
((SELECT max(forn_id) FROM forn),'descrip1 ');

It will cause a huge delay in case this table became
huge, because the forn_id isn't an indexed column (but
I would index it! The problem I am talking about is
ONLY about the sequence of numbers).

As a way to be sure it will not another other client
getting the exact value as the max(forn_id), there was
a dirty thing:

teste=# BEGIN;
teste=# LOCK TABLE forn IN ACCESS EXCLUSIVE MODE;
teste=# INSERT INTO ...
teste=# COMMIT;

Well, I really think it is not the best way to do that
and I am asking you for advices!

1) Is it (... max(forn_id)... ) the best way to get
the next value to be inserted in the table?

2) Is there a automatic way to do that?

Thanks in advance and
Best Regards,

Marcelo

_______________ _______________ _______________ _______________ __________

Yahoo! Mail: 6MB, anti-spam e antivírus gratuito! Crie sua conta agora:
http://mail.yahoo.com.br

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

Nov 12 '05 #1
5 1910
I think that defining forn_id as "serial" is what you are looking for.

This will handle the assignment of unique numbers to the id for you (it creates
a sequence table).

The locking stategy is fraught with danger... and unnecessary.

Marc A. Leith
redboxdata inc.

E-mail:ml****@red boxdata.com
Quoting MaRcElO PeReIrA <ga********@yah oo.com.br>:
Hi guys,

I have a simple table:

teste=# \d forn
Table "public.for n"
Column | Type | Modifiers
---------+---------+------------------------------------------------------
id | integer | not null default
nextval('public .forn_id_seq':: text)
forn_id | integer |
descrip | text |

Ok! The forn_id is supposed to be sequencial and
without holes (if someone perform a DELETE or UPDATE,
so there will be a hole... no problem if the hole
happens in this case!).

Well, to know the next value of the forn_id column, it
was planned to be done like this:

teste=# INSERT INTO forn (forn_id,descri p) VALUES
((SELECT max(forn_id) FROM forn),'descrip1 ');

It will cause a huge delay in case this table became
huge, because the forn_id isn't an indexed column (but
I would index it! The problem I am talking about is
ONLY about the sequence of numbers).

As a way to be sure it will not another other client
getting the exact value as the max(forn_id), there was
a dirty thing:

teste=# BEGIN;
teste=# LOCK TABLE forn IN ACCESS EXCLUSIVE MODE;
teste=# INSERT INTO ...
teste=# COMMIT;

Well, I really think it is not the best way to do that
and I am asking you for advices!

1) Is it (... max(forn_id)... ) the best way to get
the next value to be inserted in the table?

2) Is there a automatic way to do that?

Thanks in advance and
Best Regards,

Marcelo

_______________ _______________ _______________ _______________ __________

Yahoo! Mail: 6MB, anti-spam e antivírus gratuito! Crie sua conta agora:
http://mail.yahoo.com.br

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

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

Nov 12 '05 #2
On Mon, 24 Nov 2003 10:20:07 -0300 (ART)
MaRcElO PeReIrA <ga********@yah oo.com.br> wrote:
Hi guys,

I have a simple table:

teste=# \d forn
Table "public.for n"
Column | Type | Modifiers
---------+---------+-------------------------------------------------
-----
id | integer | not null default
nextval('public .forn_id_seq':: text)
forn_id | integer |
descrip | text |

Why not make forn_id a sequence as well?
then you simply call nextval('forn_i d_seq')
--
Jeff Trout <je**@jefftrout .com>
http://www.jefftrout.com/
http://www.stuarthamm.net/

---------------------------(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 12 '05 #3
Marceio

The sequence logic takes care of it. try it yourself

open two connections with psql

on one do a
begin;
insert into table
select curval('forn_id _seq');

on the other

do a
begin
insert into table
select curval('forn_id _seq');
You will see that they both increment the sequence number

you will also see how to get the current value as well.

Note, no locking is actually required, you can do this without the
transaction stuff, it is there just so you can see it in two sessions at
the same time.

Also note that a rollback will NOT roll back the sequence number, this
will end up with holes but sequences are not guaranteed to not have
holes.

Why do you have two columns, id, and forn_id, you only need one.

and then do an

insert into forn (descrip) values ( 'some description' );
then select curval('forn_id _seq');

forn_id will be populated for you with the value from curval.
Dave

On Mon, 2003-11-24 at 08:20, MaRcElO PeReIrA wrote:
Hi guys,

I have a simple table:

teste=# \d forn
Table "public.for n"
Column | Type | Modifiers
---------+---------+------------------------------------------------------
id | integer | not null default
nextval('public .forn_id_seq':: text)
forn_id | integer |
descrip | text |

Ok! The forn_id is supposed to be sequencial and
without holes (if someone perform a DELETE or UPDATE,
so there will be a hole... no problem if the hole
happens in this case!).

Well, to know the next value of the forn_id column, it
was planned to be done like this:

teste=# INSERT INTO forn (forn_id,descri p) VALUES
((SELECT max(forn_id) FROM forn),'descrip1 ');

It will cause a huge delay in case this table became
huge, because the forn_id isn't an indexed column (but
I would index it! The problem I am talking about is
ONLY about the sequence of numbers).

As a way to be sure it will not another other client
getting the exact value as the max(forn_id), there was
a dirty thing:

teste=# BEGIN;
teste=# LOCK TABLE forn IN ACCESS EXCLUSIVE MODE;
teste=# INSERT INTO ...
teste=# COMMIT;

Well, I really think it is not the best way to do that
and I am asking you for advices!

1) Is it (... max(forn_id)... ) the best way to get
the next value to be inserted in the table?

2) Is there a automatic way to do that?

Thanks in advance and
Best Regards,

Marcelo

_______________ _______________ _______________ _______________ __________

Yahoo! Mail: 6MB, anti-spam e antivírus gratuito! Crie sua conta agora:
http://mail.yahoo.com.br

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

---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 12 '05 #4
On Mon, 24 Nov 2003 12:48:26 -0300 (ART)
MaRcElO PeReIrA <ga********@yah oo.com.br> wrote:
The biggest problem it that I *can't* have holes in
that column, so it was because I used id (serial) and
forn_id (integer).


Well, if you cannot use a sequence you will have no choice but to use
locking.

don't use max - it isn't fast on PG use select forn_id from thetable
order by fornid desc limit 1. You'll need an index on forn_id or
performance will suffer.

--
Jeff Trout <je**@jefftrout .com>
http://www.jefftrout.com/
http://www.stuarthamm.net/

---------------------------(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 12 '05 #5
MaRcElO PeReIrA wrote:
Dave,

I actually use just the sequence, as you wrote!

The biggest problem it that I *can't* have holes in
that column, so it was because I used id (serial) and
forn_id (integer).


You could maintain some sort of systemnumber table yourself

create table sysnum (
first int not null,
next int not null,
last int not null
latest_updater text not null,
the_time timestamp? not null);
and get your serial number from the next column.

However, this strategy demands the same logic from
all programs using the table:

pseudo Ada code

loop
begin transaction
select * from sysnum into some Adarecord;
update sysnum
set next=next+1
latest_updater = The_pid_or_name _of_your_proces s_or_thread
the_time=now (with good enough acurracy)
where
latest_updater = Adarecord.lates t_updater and
The_time = Adarecord.The_t ime;

if Rows_Affected = 0 then
Rollback transaction;
else
commit transaction:
exit
end if;
(perhaps a small delay, say 0.05 sec?)
end loop;
you can get Rows_affected from PQ_Cmd_Tuples

if Rows_affected is 0 then you have a transaction conflict,
and must start all over again, to get a unique value.

What this does to performance, I don't know, but I do know it works,
IF AND ONLY IF all processes follow the same rule.

There should proberly be some code to handle when
you fall over the edge, ie next > last => next = first

/Björn


Nov 12 '05 #6

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

Similar topics

1
5974
by: Jeff Roughgarden | last post by:
I was at a conference and had it asserted to me by an Oracle afficiando that Oracle and DB2 handled low-level locks "better" than SQL Server, and that this was likely the cause of SQL Server's relatively slower and more deadlock-prone performance when running the same application. (SQL does seem to perform more poorly for this app, a PeopleSoft customer service and billing app.) Is there any significant difference in lock escalation...
2
1530
by: robin | last post by:
The Oblique Strategies were originally a set of one-hundred cards, each bearing a short phrase. They were devised by Brian Eno and Peter Schmidt as ways of working through creative problems. When a blockage occurs, draw a card, and see if it can direct you in a tangential way that helps solve the problem. I have created a Python implementation that includes two different decks. Since one of these is my own, I can be sure this is an...
0
3392
by: Bruce Pullen | last post by:
DB2 v7.2 (FP7 - DB2 v7.1.0.68) on AIX 5.2.0.0. We're seeing unexpected single row (then commit) insert locking behaviour. We're seeing Applications that already hold row-level W locks in lock-wait, waiting to acquire row-level X locks. The lock-waits are behind applications that have row-level X locks on different rows (honestly). Both executing and lock-waiting applications have been granted IX table locks.
0
17827
by: Nashat Wanly | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaskdr/html/askgui06032003.asp Don't Lock Type Objects! Why Lock(typeof(ClassName)) or SyncLock GetType(ClassName) Is Bad Rico Mariani, performance architect for the Microsoft® .NET runtime and longtime Microsoft developer, mentioned to Dr. GUI in an e-mail conversation recently that a fairly common practice (and one that's, unfortunately, described in some of our...
17
2524
by: euan_woo | last post by:
Hi, Sometimes my program stops and when I break it I see 2 threads both waiting at a lock statement trying to lock the same object. If I look up the call stack of these threads there aren't any other calls to lock statements so I don't see how it's possible for anything to be locked. Can anyone explain this to me? Thanks
17
5419
by: Ryan Liu | last post by:
Hi, If I have many threads write to a variable(e.g. var++) and another thread read it on an interval base. For those writing thread, I know I need lock, or its value could be lower ( even I think it is mostly not going to happen for ++ operation since it is not something like read a value and wait sometime then write back in multiple threading environment, BTW, is this understanding right?).
13
1787
by: CoreyWhite | last post by:
When playing games, perhaps the most simple is tic-tac-toe. The game has two simple strategies, one is defensive and the other offensive. It is not hard at first to learn how to tie games when playing an opponent. And then the next stage in development comes after you learn how to beat an opponent. You really can only employ either strategy when you get to make the first move, and your opponent will quickly learn what you are doing...
24
2532
by: David | last post by:
Hi list. What strategies do you use to ensure correctness of new code? Specifically, if you've just written 100 new lines of Python code, then: 1) How do you test the new code? 2) How do you ensure that the code will work correctly in the future? Short version:
0
1929
by: origami.takarana | last post by:
Intrusion Detection Strategies ----------------------------------- Until now, we’ve primarily discussed monitoring in how it relates to intrusion detection, but there’s more to an overall intrusion detection installation than monitoring alone. Monitoring can help you spot problems in your network, as well as identify performance problems, but watching every second of traffic that passes through your network, manually searching for...
0
9731
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10393
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
10405
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
10136
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
6893
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5697
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3871
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3020
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.