473,491 Members | 1,917 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

postgresql Error handling in client app

Hi,

i have a question about how to handle postgresql constraint errors in
the client app. I found some mails in the archive about it, too. But
i have still so many questions about how to do it, where to check it
and how to display a good error message. I would love to hear some
comments about my ideas:

1. usual way: double check all values in client app

CREATE TABLE accounts (
id SERIAL PRIMARY KEY
);

CREATE TABLE users (
account text REFERENCES accounts(id),
username text,
CONSTRAINT username_valid CHECK(username~'^[a-zA-Z0-9-]{3,20}$'),
PRIMARY KEY (account, username)
);

# insert into users VALUES ('jk_user');
ERROR: ExecInsert: rejected due to CHECK constraint "username_valid"
on "users"

The client app (like a php web app or whatever) has two possibilties:

a) check the username before trying to insert it. The client app will
have to know all the constraints already defined in the database and
has a catalog of valueable error messages.

drawbacks:
- If database constraint changes, all client apps will have to change
its validation routines.
- Some constraints can't be easily checked outside the database. If
there is only a limited amount of users allowed per account, the
client app has to SELECT FOR UPDATE the users table first, check it,
and insert it in one transaction. And this check has to be also done
on insert by the database, too.

b) just do the insert and parse the sql error message for known
constraint_names and lookup a reasonable error message. One user
proposed in the archives to insert the error message in the
constraint name like this:

CONSTRAINT "#valid_dusername#Please only use alphanumeric values##"
CHECK(username~'^[a-zA-Z0-9-]{3,20}$')

drawbacks:
- sql Error messages can't be parsed easily and are subject of change.
- you can only show one error message at a time because postgresql
returns on first failing constraint.

2. way: building triggers for validation

Now i thought of keeping all information inside the database and have
all errors logged inside a table "errors". The returning errorcode
can be looked up in the error table to get real world error messages:

Its real world code and works with postgresl 7.3.3 if your databse
supports plpgsql language (createdb test; creatlang plpgsql test)

CREATE TABLE errors (
id SERIAL,
tablename text,
colname text,
errormsg text
);

CREATE TABLE accounts (
id text PRIMARY KEY
);

CREATE TABLE users (
account text REFERENCES accounts(id),
name text,
email text,
PRIMARY KEY (account, name)
);

CREATE FUNCTION tg_users_check () RETURNS TRIGGER AS '
DECLARE
var_errmsg text := ''users'';
var_error boolean;
var_error_nr int8;
rec_any RECORD;
var_count int4;
var_maxmitgl int4 := 3;
BEGIN

SELECT INTO var_error_nr nextval(''errors_id_seq'');

---------------
-- count --
---------------

IF TG_OP = ''INSERT'' THEN
SELECT INTO var_count
COUNT(name)
FROM users
WHERE account = NEW.account;

IF var_count >= var_maxmitgl THEN
var_error := ''true'';
INSERT INTO errors VALUES (currval(''errors_id_seq''),
''users'', ''name'', ''Maximum amount of users ('' || var_maxmitgl ||
'') reached.'');
END IF;
END IF;

---------------
-- name --
---------------

NEW.name := btrim(NEW.name);

IF TG_OP = ''INSERT'' THEN
SELECT INTO rec_any
name
FROM users
WHERE name = NEW.name AND account = NEW.account;

IF FOUND THEN
var_error := ''true'';
INSERT INTO errors VALUES (currval(''errors_id_seq''),
''users'', ''name'', ''username is already registered.'');
END IF;
END IF;

IF NEW.name !~ ''^[A-Za-z][A-Za-z0-9-]+$'' THEN
var_error := ''true'';
INSERT INTO errors VALUES (currval(''errors_id_seq''),
''users'', ''name'', ''username has to been alphanumeric and start
with a letter.'');
END IF;

IF length(NEW.name) > 20 THEN
var_error := ''true'';
INSERT INTO errors VALUES (currval(''errors_id_seq''),
''users'', ''name'', ''username is too long.'');
END IF;

IF length(NEW.name) < 3 THEN
var_error := ''true'';
INSERT INTO errors VALUES (currval(''errors_id_seq''),
''users'', ''name'', ''username is too short.'');
END IF;

IF var_error THEN
RAISE EXCEPTION ''%'', var_error_nr;
END IF;
RETURN NEW;
END;
' language 'plpgsql';

CREATE TRIGGER tg_users BEFORE INSERT OR UPDATE ON users FOR EACH ROW
EXECUTE PROCEDURE tg_users_check();

INSERT INTO accounts VALUES ('foo');
INSERT INTO accounts VALUES ('bar');
INSERT INTO users VALUES ('bar', 'john', 'j***@doe.com');
INSERT INTO users VALUES ('bar', 'john', 'j***@doe.com');
INSERT INTO users VALUES ('bar', 'john.=donjohnsonistoolong',
'j***@doe.com');


you can even place all error messages inside a table and reference it
from errors. but this code should be enough to understand my approach.

benefits:
- most of the errorchecking can be done at one place: inside the db.
- you get reasonable error messages.
- the client app doesn't care anymore about the validation of data.
- you can lookup the most common errors of your users
- parsing the sql error message for error code is easy

drawbacks:
- if you want to tell the user beforehand which characters he can use
for a username, you still have to hardcode it into the client app.
- you usually dont want to give him a "Register as new user" form if
there are already to many users
- performance issues??
- sometimes you even have to check all the basic postgresql
constraints like a UNIQUE username
- database code becomes maybe unmaintainable??
What do you think about it? How do you usually do it?

I would really love to hear some comments on it.

kind regards,
janning



---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 22 '05 #1
0 2670

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

Similar topics

12
6642
by: Christian Christmann | last post by:
Hi, assert and error handling can be used for similar purposes. When should one use assert instead of try/catch and in which cases the error handling is preferable? I've read somewhere that...
1
4571
by: Christopher.Becker | last post by:
When I'm running my app, I occaisonally receive this error message: PostgreSQL Error Code(1) "could not create socket: An address incompatible with the requested protocol was used" It appears...
14
3859
by: Al Smith | last post by:
I need help in implementing proper error handling. I am trying to upload a file based on the sample code below. The code works well except if the file selected is too big. I do know about the...
5
2258
by: Jurgen Defurne | last post by:
I am currently designing an application which should be accessible from different interfaces. For this I like to be using stored procedures to process the contents of form submissions and dialog...
3
372
by: dgiagio | last post by:
Hi, I'm creating a SMTP application and I would like to hear opinions about error handling. Currently there are two functions that communicate with the remote peer: ssize_t...
3
4912
by: J055 | last post by:
Hi How do I tell the user he has tried to upload a file which is too big... 1. when the httpRuntime.maxRequestLength has been exceeded and 2. when the uploaded file is under then...
1
3413
by: suhas | last post by:
Hi We have .net remoting applications (using .net framework 1.1) I want to implement error handling in much better way to conclude about the problem/failure occurred. What are the standard or...
4
1943
by: John Wright | last post by:
I need some good ideas or references for robust error handling in VB.NET. I am using try catch but find myself using the generic exception handler. I would like to get more precise error handling...
35
3734
by: jeffc226 | last post by:
I'm interested in an idiom for handling errors in functions without using traditional nested ifs, because I think that can be very awkward and difficult to maintain, when the number of error checks...
0
6980
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...
0
7157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7192
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...
1
6862
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...
0
5452
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,...
0
4579
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...
0
3078
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1397
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 ...
0
282
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...

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.