473,241 Members | 1,608 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

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 2656

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

Similar topics

12
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
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
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
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
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
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
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
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
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
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.