Académique Documents
Professionnel Documents
Culture Documents
Inside Savepoints
by Dmitri Kouzmenko
Developers area a number of times. Also in future issues
products – and I completely agree. – please feel invited to read on.
we will pay attention to community
They are different, but people who use
Working with temporary tables in InterBase 7.5 ................. 18 events like BorCon and the Firebird We need your feedback
them are the same. Development
Conference.
by Dmitri Kovalenko
approaches, problems and techniques This is the first issue of “The Interbase
are almost always the same. and Firebird Developer Magazine”.
Working with UNICODE in InterBase/Firebird ..................... 21 In this issue We have got plenty of ideas for the fol-
by Dmitri Kouzmenko
Of course, InterBase and Firebird are lowing issues and will try to make “The
different but it is not the same kind of Ok, what do we have in this issue? The Interbase and Firebird Developer
difference as between Oracle and MS first and largest article “Inside Save- Magazine” the best database devel-
Hyperthreading, SMP and InterBase, Firebird, Yaffil ........... 23
SQL – they are different like brothers. points” by Dmitri Yemanov is devote to oper magazine around. And the most
the internal details of server save- important thing we would like to know
To receive future issues notifications send email to
Subscribe now! points. Explicit savepoints are a rather
Who need our magazine is your opinion and your thoughts
subscribe@ibdeveloper.com
You sometimes hear the opinion that recent improvement in both InterBase about our work. Please do not hesitate
“InterBase is not a serious DBMS” and and Firebird, and I think it will be very to contact us:
Credits “Firebird? What’s this?” And it is a interesting for all readers to know nitty-
hardly known fact that the size of our gritty details of their functioning. readers@ibdeveloper.com
Alexey Kovyazin, Chief Editor
Dmitri Kouzmenko, Editor community is close to the community Sincerely yours, Alexey Kovyazin.
size of such monsters as Oracle and Another hot article is “Using Embed-
Lev Tashchilin, Designer Chief Editor
MS SQL. Despite the fact that Oracle ded User Authentication in InterBase
Volker Rehn, Subeditor
7.5” by Dmitri Kouzmenko. We have
Figure 2 Releasing a savepoint: undo data moved to upward savepoint automatically deleted. and would be canceled entirely, if an
2. Execution of the BEGIN…END block error occurs.
in PSQL (stored procedure or a trigger) Secondly, in the presence of a
in case the block contains an error han- WHEN-handler, the occurrence of an
dler (WHEN-block). In that case, each error leads a rollback of the only oper-
BEGIN operator sets a savepoint, and ator, and after that the process is man-
a corresponding END operator deletes aged by the handler.
it. This enables to provide error han- That is to say, there are obvious dif-
dling ferences in the server’s reactions, which
in the PSQL-block. depend on the presence of a WHEN-
handler.
3. Execution of an SQL-operator in the
context of a “BEGIN…END” block, It is worth considering a known
which contains an error handler anomaly, which does not fit the scheme
(WHEN-block). That is, if the block con- described above. The scheme works as
tains an error handler, any SQL-opera- follows: the paragraph 3 (enclosing of
tor in this block is framed by a save- each SQL-operator inside a PSQL-
point frame. block by its own savepoint frame) is
true for SQL-operators only (moreover,
Exception handling not for all of them). In other words, for
Let’s consider the errors handling example, an assignment operator will
process on the server. When an excep- not be framed by a savepoint frame.
Tip: tion occurs, automatic rollback to the As a result of an error in assign-
As is illustrated below, each custom SQL-query is a set of savepoints within a transaction. last set savepoint is performed. As a ment, execution leads to a normal roll-
result, all operations performed by an back to the previous savepoint, which
invalid SQL-query would be canceled. is… exactly! – the block’s savepoint.
Thus, the combination of all changes, not created, and if regular deletion of the current stack is performed, the
which were successfully executed dur- combined undo log is simply deleted, and transaction is marked dead, and Then, in case of a PSQL-block, it is That is to say, even if there is a
ing transaction, is stored in undo logs. all changes are to be cleared (garbage collection). checked, if there is a custom WHEN- WHEN-handler, the error may cause
That is why, when the automatic undo handler. If it does exist, control is trans- the rollback of the whole block before
log is enabled, the server can cancel all Savepoints and exception handling ferred to it, and after exiting, savepoint control to the error handler.
performed changes, and in the TIP this There are several events, which make server create system-defined (i.e. is deleted. I consider this situation as a serious
transaction would be marked as com- user-uncontrollable) savepoints: Then the process repeats recursively, flaw in the server’s exceptions handling
mitted, and not as dead. until embedded handlers end. Thus, if a logic. Below is the full list of operators,
1. Execution of any user SQL-query. As has been said above, this done in
When specifying the stored procedure doesn't contain a for which the savepoint frame is creat-
order to guarantee atomicity of a query. That is to say, if any exception
isc_tpb_no_auto_undo parameter at handler which would be able to handle ed: INSERT, UPDATE, DELETE, EXCEP-
occurs during query execution, the changes made in the database will
transaction start, a global savepoint is this error, the whole procedure will be TION, EXECUTE STATEMENT [INTO].
always be canceled. After the query is executed, the savepoint will be
considered as a single SQL-operator, To understand the reasons of this
and canceled. anomaly, it is necessary to take into
Tip:
It is necessary to note that the isc_tpb_no_auto_undo parameter does not disable the savepoints mecha- Let’s make a summary account the following 2 facts:
nism (this is impossible due to the atomicity guarantee for SQL-operators ). It only disables the creation Firstly, if there is no WHEN-handler, •If an error occurs, rollback to the
of a transaction undo log as a single whole. any PSQL-block (including stored pro- last savepoint is performed uncondi-
cedure and trigger) becomes atomic, tionally.
•A block’s savepoint deletion (or roll- point #2 was deleted right before assignment execution), INSERT will be
back to it) is performed together with the canceled. Therefore, a rollback of the whole BEGIN...END block will be InterBase Myths № 1
verification of the savepoint’s identifier performed before entering the handler. When performing a "restore" outdated, versions are
deleted (and, therefore, are stored in backup) or
gbak -g creates a backup file without versions, and
This means that when an error occurs in Below is the same procedure with an explicit exception statement, enclosed
In this case, INSERT will not be canceled, would be desirable to provide an a transaction. If you attempt to create (delete) savepoints when they are no longer necessary. This can be accom-
due to the fact that the exception initiation alternative to choose between two savepoints with similar names, the plished using the following operator:
RELEASE SAVEPOINT <name> [ONLY];
of E results in rollback to savepoint #3 and UNDO- and EXIT- behavior of a first savepoint is deleted, and the speci-
subsequent transfer of control to the error handler, and repair the described fied name is given to the second one.
handler. In order to cancel the INSERT anomaly. This command deletes the selected (and all following) savepoints from
For rollback to a savepoint, the follow-
operator in this case, you should inhibit the transaction context. The “ONLY” option is a switch to delete the selected
ing operator is used:
execution of the deletion handler: Custom savepoints savepoint only; at that, all following savepoints will be saved. If a savepoint
CREATE PROCEDURE PROC5
was not released explicitly, it will be automatically deleted as
ROLLBACK [WORK] TO [SAVEPOINT] <name>;
In addition to the internal
AS realization of savepoints at soon as the transaction is finished.
BEGIN
transaction (and opera- Note: The “ONLY” option is non-standard extension, and is
INSERT INTO TAB (COL) VALUES (89);
tor/block) levels, the latest Note: the SAVEPOINT keyword is not supported by InterBase 7.1.
EXCEPTION E;
versions of servers (Inter- obligatory in InterBase 7.1.
END
Base 7.1, Firebird 1.5, and
During execution of this operator, the
Yaffil 1.1) provide an SQL-
following actions are performed:
interface, developed for
INSERT INTO AUDIT_LOG (ID, EVENT, STATUS) VALUES (:ID, :EVENT, 1);
it is necessary to display error messages (or save them for future presentation as
a list), and let this bulk operation continue. Since the document handling opera-
tion is not atomic, on the client’s side it is better not to use regular exception han- SAVEPOINT OPER;
dling since we cannot continue the transaction if we know that an exception per- TRY
formed a rollback of only half of the operation.
<…> // operations on database
EXCEPT
Such a dilemma can be resolved by handling each document sequentially in a
ROLLBACK TO SAVEPOINT OPER;
separate transaction. Nevertheless, this does increase the consumption of inter-
END
increment), and is therefore not the best alternative.
COMMIT;
In addition, if there is a need to fix a set of documents during the handling process
(for example, by changing the transaction isolation mode or explicit blocking of
the SELECT … WITH LOCK type), it would require using only one transaction for through the SAVEPOINT global opera-
the delta packet. Using a savepoint, the following algorithm would be used (in
Savepoints in stored procedures and triggers
Now let us consider the usage of custom savepoints in procedures and triggers. tor). In addition, procedure savepoints
pseudocode):
START TRANSACTION;
must be local and their scope must be
At first glance, it looks very attractive and useful. Originally this functionality is declared defined by the procedure. That is to say,
OPEN C FOR ( SELECT … ); in InterBase 7.1. Let’s consider the capabilities in detail. there can be a savepoint named “S1”
FOR ( C ) DO First of all, savepoints must not break the atomicity of SQL-operators. This means that both in the transaction and in procedures
LOOP none of the commands can be canceled partially. Remember that EXECUTE PROCE- and triggers executed in the context of this
TRY DURE is a legal SQL-operator, and any operators updates may lead to trigger execu- transaction. At that, such savepoints will
SAVEPOINT DOC;
tion. Generally speaking, any “simple” operator, such as INSERT or UPDATE may result be isolated from each other. Note that this
<…> ///single document handling commands
in launching of a whole chain of triggers and procedures. That is why we are to examine very method is used in InterBase 7.1.
EXCEPT
the scope of a savepoint. A question emerges: how would custom
ROLLBACK TO SAVEPOINT DOC;
It is obvious that in order to meet the atomicity requirement, savepoint affected instruc- savepoints coexist with internal save-
tions with in a procedure should not have an access to the transaction savepoint (set points managed by the server?
<…> //either log the error or display it
Some theory INSERT INTO TABLE3 … In this case, all operators within the 2. each block of PSQL-code with an
Let us consider a simple example of savepoint usage in PSQL, suggested by EXECUTE PROCEDURE … loop will be automatically canceled, in exception handler is enclosed in a frame
Borland in the InterBase 7.1 server documentation: … the event that an exception occurs,
CREATE PROCEDURE ADD_EMP_PROJ2 (
Thus we arrive at a conclusion that any
WHEN ANY DO
since the operators are located in the code area of the following type:
EMP_NO SMALLINT, BEGIN SAVEPOINT S1;
atomic block by which the savepoint
EMP_NAME VARCHAR(20), ROLLBACK TO SAVEPOINT
frame for SQL-operators mechanism
…
PROJ_ID CHAR(5) ) S1;
was enabled. After that, the server will
BEGIN
AS ERROR = REC_ID;
go through the chain of embedded
…
blocks, and will switch to the handler.
BEGIN SUSPEND;
ROLLBACK TO SAVEPOINT S1;
BEGIN END
Therefore, in virtually any case, one
END
the whole block. Thus, we can easily block. This would destroy the internal
Now let us return from theory to prac-
END
turn the EXIT-handler to UNDO in case undo log, and may corrupt the data-
if necessary. Of course, this functionali- tice and test this reasoning in InterBase base.
This example demonstrates how exceptional situations are handled when ty can be obtained by standard means 7.1. The result is quite depressing: none
(!!!) of the given examples work, and Thank God, the InterBase developers
using savepoints. That is to say, when an exception with code -530 occurs as well: did not create such cardinal realization,
FOR SELECT ID, … INTO
(the violation of reference integrity by a foreign key) we cancel the insert error messages appear:
Statement failed, SQLCODE = -504
and server attempts to cancel the
:REC_ID, …
operation and initiate a user exception. Actually, this example is absolute-
Savepoint <name> unknown.
previous (last) savepoint directly,
BEGIN
ly useless, since we do not need a savepoint here: only if its name matches. Since sys-
BEGIN BEGIN
tem savepoints are unnamed, in
INSERT INTO …
Even the first example, which was taken
INSERT INTO TABLE1 …
this case such an attempt would fail.
WHEN SQLCODE –530 DO
from the Release Notes (!), is not work-
INSERT INTO TABLE2 …
This is proven by the above mentioned
ing properly. At the same time, the most
EXCEPTION unknown_emp_id; INSERT INTO TABLE3 …
error message.The above makes us
primitive examples, such as:
END
arrive to the conclusion that working-
EXECUTE PROCEDURE … SAVEPOINT S1; with savepoints in PSQL is limited by the
… INSERT …
nesting level, in case we are dealing
END
This code will execute the same function, since the server itself cancels the
ROLLBACK TO SAVEPOINT S1;
INSERT operation when an exception during it's execution. with blocks with a WHEN-handler.
WHEN ANY DO However, it turned out that the most
BEGIN
Let’s consider a more complicated example:
FOR SELECT ID, … INTO :REC_ID, …
work correctly. So what’s the matter? If interesting thing is yet to come. The
END
ber the two facts described above: RELEASE SAVEPOINT operator is
INSERT INTO TABLE1 …
END
amusing. Let’s illustrate this using an
INSERT INTO TABLE2 …
1. savepoints constitute a stack, and
can be canceled sequentially only example:
BEGIN
Summary neither available in Firebird, nor in Yaffil.
INSERT INTO TABLE1 …
There are some peculiarities in save- Note: As far as I understand it, the same reasons prevent from using commit/roll-
ROLLBACK TO SAVEPOINT S1;
points logic, which prevent realization back retaining in PSQL, since in that case the savepoint-frame of a procedure would
INSERT INTO TABLE2 …
of their complete support by PSQL. The be destroyed.
analysis of InterBase 7.1 behavior
END proves the point. The rationale of that is
the presence of system savepoints, Savepoint in distributed transactions
This is an emulation of an error, which which interaction with custom ones is InterBase 7.1 introduces the option to work with savepoints in coordinated transac-
usually occurs if the required save- limited, due to data integrity require- tions.
point cannot be found within a single ments. That's why this functionality is For this purpose, three new API functions are introduced:
code block. As one would expect, the
execution of the procedure returns the ISC_STATUS isc_start_transaction(ISC_STATUS* status,
same error. But!!! Procedure execution isc_tr_handle* trans, char* name);
does not stop at this point. Instead, the ISC_STATUS isc_release_transaction(ISC_STATUS* status,
isc_tr_handle* trans, char* name);
second INSERT is executed (which you
ISC_STATUS isc_rollback_transaction(ISC_STATUS* status,
can easily verify by substituting
/* Create savepoint */
as one might expect. Even though the
code after ROLLBACK TO SAVE-
POINT is executed, nothing really isc_start_savepoint(status, &trans, "A");
happens. Which means, that in case
/* Executing database operations */
the described error occurs in a proce-
isc_dsql_execute_immediate(status, &db1, &trans, 0, "DELETE FROM TABLE1", 1, NULL);
dure, all changes made by this proce-
As a result of a rollback to savepoint, Even if only one of them fails, InterBase has an interesting undocumented feature. Usually when the COMPUTED stored as integers’ one, and therefore
I expect rollback to be performed in an error returns. Generally, BY field is declared, the following syntax is used: when one enters 1.88, in NUMERIC(15,
<col_def> = col { datatype | COMPUTED [BY] (< expr>) |
both databases I work with. Then I this error does not character- 2) it would look as 1.88, though actual-
domain}
commit the transaction, and after that ize the current situation, in ly (as a string) will turn out to be
[DEFAULT { literal | NULL | USER}]
I need to see all data on their places, terms of correctness of the 1.8799999952316.
operation as a single whole.
[NOT NULL] [ <col_constraint>]
since DELETE operators were can-
Thus, we can make up several conclu-
celed.
[COLLATE collation]
Of course, one might say that sions:
And that would be that way, but for only one method of working
with savepoints should be •real numbers’ accuracy is bounded,
the manually executed "RELEASE
As you see, syntax requires specifying either type of the column (datatype), or the and therefore numbers stored as real,
SAVEPOINT A." applied – either through
calculated expression (computed by). The "either/or" directive is the | symbol. Usu- should never be used in equality (every-
SQL, or through API.
At first, savepoint rollback was per- ally, type of the COMPUTED BY field is similar to the source one (which it is based one knows that)
formed for the first connection and all Now you know what it leads on). However, it is possible to specify column type, even if it would not coincide with
to. However, for working •precision of the FLOAT fields is quite
changes were canceled. the source.
with savepoints in InterBase short (similar to Delphi’s single). That is
Then the same operation was accom- The following experiment can be performed. Create a table with structure as shown why it is better to use DOUBLE PRECI-
7.1, a new API can be com-
plished for second connection, while… below: SION instead.
pletely substituted by server’s
oops! … there is no savepoint any-
standard means. (the PRIMARY KEY definition may be omitted, since in this case it is used only for •not all types are interconvertible: the
more. As a result, the client receives
Database Explorer tables’ usability: BDE does not allow update tables, which do NUMERIC(15, 2) field as INTEGER
an error message. But rollback of one The server should either sup-
not have a primary key)
CREATE TABLE TESTCOMP(
press possibility to control COMPUTED BY... will contain 0.
of the DELETE operators was success-
t_data FLOAT NOT NULL PRIMARY KEY,
ful (!) This is a situation, when the savepoints in certain connec- •inaccuracy should be taken into
in InterBase 7.5
One of the most important new features in InterBase 7.5 is user 3. if the passwords are equal, the user manage this functionality (in “gsec” a •internal gds software consistency
authentication, which is embedded in the database. Let’s con- connects to the database he/she speci- “user_database” option is added for check (decompression overran buffer
sider the scheme used in the previous version: fied. And if they do not, the user is user management in such databases). (179), file: sqz.c line: 229)
unable to connect to the database This functionality is supported only for for databases, in which EUA was never
Standard scheme ("wrong user name or password" error ODS 11.2, i.e. for the databases creat- enabled
In InterBase, a separate special database isc4.gdb is intended for user list reported). ed or restored from backup in InterBase In other words, there is no other way to
storing. In InterBase 7.0 this database was renamed (admin.ib), and in As you can see, to access any database 7.5. At that, previous versions of Inter- connect to the database, but from Inter-
addition, new ibconfig parameter was added (ADMIN_DB), which allows on this server, a user must be specified Base, for example, 7.1 and below, Base 7.5 specifying a required pass-
to specify any name for this database. in isc4/admin only once. In the future, when attempting to connect to such word (stored in the database) for a spe-
in a particular database, user access is database, will return two types of mes- cific user (we do not consider the possi-
defined by the rights he is granted. sages: bility of “hacking” such database, i.e.
This scheme is insufficient when used in: •product DATABASE ACCESS is not editing it in HEX-editor).
•single-user applications. It becomes licensed
necessary to deploy both the database for databases, in which EUA is enabled continued on page 12
and admin.ib. or disabled
•deployed or stolen databases. Any-
one can "slip" his/her own “admin.ib”
with SYSDBA/masterkey to the server,
and, as a result, completely control a
database.
•systems, in which a user has to con-
nect to only those databases, with
which one is allowed to work.
In isc4.gdb/admin.ib, there is a basic “USERS” table, which contains user- Embedded User
name, password, and other parameters. When a client connects to a data-
Authentication
base:
In InterBase 7.5 you can either refuse
1. the front-end encrypts the password by DES algorithm with data loss, using admin.ib (see below), or combine
and then sends the username and encrypted password to the server. admin.ib with user control in the data-
2. the server encrypts the received password once again by the same lossy base. For that purpose, attributes of
DES, and then calls isc4/admin in the “USERS” table, finds the necessary several system tables were extended,
user, and then verifies the received password with the stored one. and new SQL-operators were added to
INACTIVE
(RDB$DEFAULT_ROLE, RDB$USER_ACTIVE, and RDB$USER_PRIVILEGE columns
are added).
When enabling EUA, it becomes active right away, and in the RDB$USERS table the
SYSDBA user standard record appears (the password is encrypted “masterkey”), Examples:
ALTER DATABASE SET ADMIN OPTION ACTIVE ALTER USER TEST SET NO LAST NAME, DEFAULT ROLE ABC;
During deactivation, in RDB$USERS field RDB$USER_ACTIVE is set to 'N' for all Draw attention to the fact that one can “enable” and “disable” users by the alter
user records (including SYSDBA). When activating, it is performed conversely: user xxx set inactive/active command. There is no such possibility in the standard
RDB$USER_ACTIVE is entered to 'Y' for all users. Doing that, be careful, since if admin.ib.
some users were disabled before EUA deactivation, as soon as EUA is activated, all
EUA users will be able to access the database (i.e. all EUA accounts will be
Authentication order
enabled).
It is important to comment how exactly connections are performed in case EUA is
You can completely delete EUA, together with all user records by the command: active in a database:
ALTER DATABASE DROP ADMIN OPTION •The server opens a specific database.
This will clear the RDB$USERS table, and restore functioning of the standard 1. EUA disabled – user authentication is accomplished from admin.ib
authentication scheme (through admin.ib).
2. EUA enabled - user authentication (any user, including SYSDBA), is accom-
plished from rdb$users of this particular database
User management
If EUA is enabled, you can manage users: That is, when enabling SYSDBA and changing password for SYSDBA, it will be pos-
{CREATE | ALTER} USER SET
sible to connect to this database under the “SYSDBA” name, only if the user speci-
fies a correct password.
option : PASSWORD
Attention: Admin.ib is mandatory in any case. The server, when trying to connect
create user USR set password 'usr'; • Probably, it would be better to create a flag in Header Page of the database,
4. All this leads to an interesting situation. The “TEST” user can perform backup, but which would signify presence of EUA. In this case, users would be ignored during
would it be a backup from admin.ib, or from the database? Let’s change the TEST’s restore process. This is up to InterBase 7.5 developers.
password in admin.ib. Let the password be “tttt”. • In spite of apparent “autonomy” of EUA, if there is no admin.ib, it would be pos-
5. try to backup from TEST user through admin.ib sible neither to connect to the database, nor perform restoring.
Conclusion
Regarding all that, we can come to several conclusions:
• EUA in this version does not "outlive" backup/restore not only for the owner, but
for SYSDBA as well. SYSDBA is "both king and god" for databases and that is why
rdb$user_privilege = null is unnoticeable for a developer. This becomes important
when one begins to use the database in operating mode.
• When performing restore, there is a need to verify username/password. For reg-
ular databases, restoring with other usernames is performed when it is necessary to
change the database owner. However, since EUA is enabled for users within the
database, restore can be performed in no other way but specifying a new user at
gbak -c. Actually, SYSDBA from admin.ib may be a "wrong user" differing from
SYSDBA in the database with EUA, if they have different passwords.
KEEPALIVE_PROBES
nection in case the client becomes inaccessible due to connection release. tcp stack versions, and many other con-
It is important to promptly release the resources busy with such phantom ditions. That is to say, effectiveness of Number of KEEPALIVE-probes
connections, especially when using servers with Classic architecture. such system in a real network tends to
zero. The TCP stack tracks the moment when closed after the following time interval:
If some users connect to the server through an unstable modem connection, packets stop transmit between the client KEEPALIVE_ TIME+ ( KEEPALIVE_
then the risk of disconnection becomes rather high. KEEPALIVE-sockets are a more interest-
and the server, by launching the PROBES+1)* KEEPALIVE_ INTERVAL.
ing mechanism. Implemented in Inter-
For instance, a client saves a modified record set, and after UPDATE is exe- Base 6.0 and higher, it is intended for KEEPALIVE timer. As soon as the timer By default, the parameters values are
cuted (while COMMIT is not) the connection is released. connection failure tracking. KEEPALIVE reaches the KEEPALIVE_ TIME point, rather big, and this makes use of them
is enabled by setting the SO_ the server TCP stack would execute the ineffective. For example, the default
As a rule, client applications in such situations reconnect to the server, but
KEEPALIVE socket option at the open- first KEEPALIVE probe. Probe is an value of KEEPALIVE_ TIME parameter is
the client (as he/she continues working with the data, after saving which
ing. There’s no need to manually set it if empty packet with ACK flag sent to a “2 hours,” both in Linux and in Win-
one received error message due to connection fail) will be unable to save
you use Firebird 1.5 or higher, since it is user. If everything is alright on the client dows. Actually, 1-2 minutes would be
changes, since he/she will receive a message about lockout conflict (“lock
implemented in the program code of side, then the TCP stack on client side enough to make a decision about
conflict on update”). The previous connection, which opened the transac-
the Firebird server, both for Classic, sends a response packet with ACK flag, forced disconnection of an inaccessible
tion (in the context of which UPDATE was executed, while COMMIT was-
and for Superserver. and the server TCP stack resets the client. On the other hand, KEEPALIVE
n’t), still holds these records.
KEEPALIVE timer as soon as it receives default settings sometimes cause forced
Connection failures may occur in a local network too, if the hardware (net- For Interbase and Firebird versions a response. disconnections in Windows networks,
cards, hubs, commutators) is out of order or not adapted well, and/or due lower than 1.5, in the variant with Clas-
If the client does not response to the which are stay inactive during these 2
to clutter in the network. In Interbase and Firebird logs, failures of tcp con- sic architecture, an additional setting is
probe, the probes from the server con- hours (of course, one may cast doubt
nections are displayed as error 10054 in Windows and 104 in Unix; net- necessary. This setting is described
tinue to be sent. Their quantity equals to on necessity of such connections in the
beui failures are displayed as 108/109 errors. below.
the KEEPALIVE_ PROBES value; they applications, but this is a different mat-
In this case, the operating system TCP are executed at the KEEPALIVE_ INTER- ter).
Hung connections control methods stack (instead of the Firebird server) VAL time interval. If the client does not Below adjustment of these parameters
In InterBase and Firebird, the mechanisms of DUMMY-packets or becomes responsible for connection respond to the last probe, then after for Windows and Linux operating sys-
KEEPALIVE-sockets are used for tracking and disabling of such “dead” status. However, to enable this mecha- another KEEPALIVE_ INTERVAL time tems is described.
connections. nism, one must adjust KEEPALIVE expires, the operating system TCP stack
In InterBase 5.0 and higher, the mechanism of DUMMY-packets is imple- parameters. closes the connection, and the server (in
Setting KEEPAILVE in Linux
mented at the application layer between an InterBase/ Firebird server and this case, instance of InterBase or Fire-
KEEPALIVE description KEEPALIVE parameters in Linux can be
a gds32/fbclient client library. It is included in ibconfig/ firebird. conf and bird server) releases all resources busy
changed either by file system direct
is not examined in the present article. KEEPALIVE-sockets behavior is con- with provision of this connection.
editing / proc, or by calling sysctl.
trolled by the parameter presented in Thus, a failed client connection will be
Note: As we know from previous experience, stability of the dummy-pack-
the following table.
For the first case, the following lines should be edited: KeepAliveTime interval expires, after each KeepAliveInterval time (in millisec-
/proc/sys/net/ipv4/tcp_keepalive_time
onds) KEEPALIVE-probes are sent with maximum number of MaxDataRetries. If no
/proc/sys/net/ipv4/tcp_keepalive_intvl
response comes, the connection closes. Default value is 1 second (1000).
/proc/sys/net/ipv4/tcp_keepalive_probes
•MaxDataRetries = 32-digit value
Type: STRING
For the second case, the following commands should be executed:
Defines maximum number of KEEPALIVE-probes. Default value is 5.
sysctl –w net.ipv4.tcp_keepalive_time=value
sysctl –w net.ipv4.tcp_keepalive_intvl=value Setting KEEPALIVE in Windows 2000/NT/XP
sysctl –w net.ipv4.tcp_keepalive_probes=value Register branch
Time value is expressed in seconds. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Pa
rameters\.
For automatic setting of these parameters in case of server restarting, add the fol-
lowing lines to / etc/ sysctl. conf: Everything about TCP adjustment:
net.ipv4.tcp_keepalive_intvl = value 2000/ NT: http://support.microsoft.com/kb/120642
net.ipv4.tcp_keepalive_time = value XP: http://support.microsoft.com/kb/314053
net.ipv4.tcp_keepalive_probes = value The MaxDataRetries parameter is substituted by
Substitute the < value> word with necessary values. TCPMaxDataRetransmissions.
If you use version of Firebird Classic lower than 1.5, then in /etc/xinet.d/firebird All other parameters have the same names as in Windows 9x
the following should be added:
FLAGS=REUSE KEEPALIVE Setting KEEPALIVE in Windows (for clients)
This setting is optional, but it possibly will reduce number of messages about con-
Adjusting KEEPALIVE in Windows 95/98/ME nection failure if one uses unreliable communications channels. Insert to the register
Register branch branch
HKEY_ LOCAL_ MACHINE\ System\ CurrentControlSet\ Services\ VxD\ MSTCP HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Pa
Everything about adjustment of TCP can be found here: rameters
We kept everything unchanged, as it was registered during installation. Nothing KEEPALIVE-checks of normally
needs to be added. working connections, which InterBase Myths № 4
•Change the TCP stack parameters launched long transactions. If I see the word NATURAL in the query, it
sysctl –w net.ipv4.tcp_keepalive_time = 15 is a bad one!
The KEEPALIVE_ INTERVAL
Nothing terrible.
value is above or equal 10
sysctl –w net.ipv4.tcp_keepalive_intvl = 10
Some data retrieval (depending on query) is better by nat-
seconds, and the KEEPALIVE_
sysctl –w net.ipv4.tcp_keepalive_probes = 5
ural table scan, than by an index scan.
PROBES value is above or
equal 5 checks. When many
It's better to check, how long time ago you refreshed statistics for
•Connect to any database on the server from any network client. users work simultaneously,
•Check traffic on the server using any packet filter. remember that if you perform indices in your database. See documentation about SET STATISTICS
If parameters specified as /proc/sys/net/tcp_ keepalive_*, within 15 seconds after
checking too frequently, it may INDEX <index_name> statement.
considerably increase network
everything stops in the channel, the server creates a probe. If the client is “alive,”
traffic.
the server receives a response packet. 15 seconds after that, checking repeats, and
KEEPALIVE_TIME 1 minutes
so on. Also remember that in case
KEEPALIVE_PROBES 3
your users actively change
•If a client is physically turned off (either the multiplexer or the modem unexpect-
common data, lockout errors
KEEPALIVE_INTERVAL 30 seconds
edly turns off – anything is possible), then the server does not receive a response,
will occur as a result of opti-
TOTAL 3 minutes
and the server begins to send probes with 10 seconds interval. If the client does not
mum situation. In this case, you
respond to the fifth probe, then 10 seconds after that, the server process discharges,
would need a correct lockout
and releases resources and blockings lockouts. If the client gives any signals and
error handling in the client •Clients use LAN connection; most of transactions in the system are short; downtime
responses at least to the fifth probe (if worst comes to worst), then, after another 15-
applications. At the same time, is limited by 2 minutes.
seconds time-out, the server will begin send probes. And so on.
KEEPALIVE_TIME 30 sec
the application should be able
KEEPALIVE_PROBES 5
to minimize occurrence of such
Guidelines
KEEPALIVE_INTERVAL 10 sec
errors.
In conclusion, we would like to give you some advice about how KEEPALIVE values
TOTAL 90 seconds
should be selected.
Examples of default
Firstly, determine necessary value of KEEPALIVE_ TIME. The more the value is, the configuration
later KEEPALIVE-probes would start. If you constantly see 10054/104 errors in the •Clients use any connections; downtime is not regulated.
Finally, here are some more
KEEPALIVE_TIME 15 minutes
log of the server, and you have to delete them manually, it is recommended to examples of default configura-
KEEPALIVE_PROBES 4
increase the KEEPALIVE_ TIME value. tions. Downtime is the time,
KEEPALIVE_INTERVAL 1 minutes
Secondly, the values of the KEEPALIVE_ INTERVAL and KEEPALIVE_ PROBES within which users will be
TOTAL 20 minutes
should meet your needs concerning before-the-fact release of already hung con- unable to update data, (which
nections. If your users connect to the server through unreliable channels, then you by that moment were updated
probably would want to increase number of probes and the interval between them, by the transaction opened by
in order to give the user a chance to detect the failure and reconnect to the server. the hung connection). Total •Clients use any connections, continuous transactions are possible in the system,
In case clients use a DSL connection to the Internet, or access a SQL-server through time is the time, on the expiry and downtime limit is 15 minutes.
a local network, it is possible to decrease the interval between KEEPALIVE-probes. of which the hung connection KEEPALIVE_TIME12 minutes
KEEPALIVE_PROBES 7
General recommendations: if you for no particular reason receive from the clients will be closed.
many error messages, concerning results saving, due to lockout conflict (i.e. there •Clients use modem connec- KEEPALIVE_INTERVAL 15 sec
are no concurrent connections working with the same data), then you need to tions; most of transactions in TOTAL 14 minutes
increase system’s reaction to the hung connections release. Practically, the the system are short; downtime
KEEPALIVE_ TIME value may be above or equal 1 min. You should yourself estimate is limited by 3 minutes. We hope that the examples we have shown would be enough for correct adjustment
the time the longest transaction executes, so that traffic would not be overloaded by of TCP stack KEEPALIVE mechanism.
Now you may create a procedure, which would fill in the table with some data
CREATE PROCEDURE XTRANS InterBase Myths № 5
AS
InterBase is designed for Windows, and therefore
DECLARE variable I INT;
it is incompatible with Unix (Linux, Solaris, etc).
BEGIN
I = 0; This is not true! First version of InterBase was created
WHILE (:I < 10000) DO for Unix, and, before the Windows-version was released, there were
BEGIN 15 “ports” for different Unix versions (AIX, IRIX, SCO, HP-UX...). Actu-
ally, the Windows version was released 7-8 years after the first ver-
INSERT INTO detail VALUES (:I, 'asdfasdfasdfasdfasdf');
sion of InterBase.
I = :I+1;
END
END
You may insert as many records as you need: if all you want is to check the work, CREATE GLOBAL TEMPORARY table TMPCONN (
100-10К would be enough. If you want to test speed, it is recommended to begin ID int not null,
NAME varchar(20),
either from 100К records or million records (for example, on my computer this pro-
constraint PK_TMPTRANS primary key (id) )
cedure loads 1 million records to a database with 4K within approximately 47 sec-
Table Records RecLength VerLen Versions Max Vers Data Pages Slots Avg fill%
when creating FK one should take into consideration the
TMPTRANS 1000000 31.00 0.00 0 0 51725 51725 68
record view area in both tables. For example, you create two
tables:
MASTER, on commit delete
For a time of connection
DETAIL, on commit preserve
GLOBAL TEMPORARY PRESERVE tables store records until current connection (dur-
ing which they were added) is released. At that, they can be displayed only within
the period of this connection. and create FK from DETAIL to MASTER. As a result, (actually, InterBase would not
Let’s create a table allow to create such FK) after creation of records in master and detail, the first com-
mit would delete all records in master, and that causes presence of records with approximately 25 seconds for server to ON COMMIT PRESERVE is a more favorable way, though the process of
missing connections in DETAIL (in fact, such type of connection as commit preserve delete 1 million temporary records, and disconnection of applications would be more time-consuming (of course,
-> on commit delete is not permitted, though you can perform the opposite). ~120 seconds to delete 3 million tem- unless these applications created records in temporary tables). In order to
To do that (and to change “temporariness” type of the records), the ALTER TABLE porary records. avoid users’ complaints, you will probably need to specially handle appli-
operator has the following extension: • For the ON COMMIT PRESERVE cation disconnection, and to display a message asking to wait some time.
ALTER TABLE <table> ON COMMIT {PRESERVE | DELETE} ROWS tables, garbage is collected when dis- p.s. during the temporary tables test, a spontaneous processor loading by
{RESTRICT| CASCADE}
connecting the connection, which creat- the IB7.5.0.28 server was observed (though the applications were inactive).
ed these records. At that, the loading appeared in certain order of transactions’ starting and
This operator changes table’s type (preserve/delete) and can also perform cascad- finishing, while they did not contain the executed operator. The reason of
ing correction of type of the tables bound by FK, in order to prevent the situations Resume
this effect is currently being ascertained (with InterBase 7.5 SP1 also).
with mismatch of records’ lifetime in master and detail. The RESTRICT directive will • The more records a connection cre-
inform about error, if other temporary tables refer to this table. ates in temporary tables, the longer the
Temporary tables of all types cannot use FK pointing to constant tables. application would “hang” when dis-
connection is performed. Deletion of 1
Garbage collecting million temporary records, as well as in
As already mentioned, in spite of “temporariness” of table content, the on commit the previous case, takes ~25-35 sec-
delete and on commit preserve records, are nevertheless stored on the disk, as onds.
in ordinary tables. Therefore, the server sometime must remove them (as garbage).
This happens when the following events occur: Summary
Table type When garbage is collected Temporary tables InterBase 7.5 – are
very useful for applications, which form
ON COMMIT DELETE At first "exclusive" connection to the database
complex reports and execute interme-
diate calculations on the server. How-
ON COMMIT PRESERVE When canceling the connection created the record ever, due to strange behavior of ON
COMMIT DELETE, it becomes possible
to use transaction context temporary
An example of the procedure, which automatically fills a temporary table with
tables only in the applications, which
records, is given on purpose. Tests were held using 1 million records. For the tests,
works with only one transaction at a
2 IBExpert instances were launched and one IB_SQL was used. Without going into
time. Or they can work with several
details of the test, we will list its results and conclusions
transactions, on condition that a commit
• For ON COMMIT DELETE tables, garbage is collected during first exclusive con- of competitive transaction is forbidden Registering for the Conference
nection to the database. Assume we have 10 working applications, which fill in tem- until the transaction (which works with
porary tables. To delete records in all temporary tables, all 10 applications should the temporary table) performs a com-
disconnect, and at least one should connect. Right at that moment, garbage collect- mit. Call for papers
ing in the ON COMMIT DELETE tables begins. All connections, which attempt to
Furthermore, use of ON COMMIT
connect to the server before garbage collecting is finished, will "hung". Sponsoring the Firebird Conference
DELETE tables causes collecting of
Resume garbage records during multiuser work
• Working with ON COMMIT DELETE temporary folders may lead to fast grow of (since database’s size increases), and
the database during a day, since it is very seldom that during this period of time all collects garbage on first connection to
users disconnect from the database the database. This can cause an unde-
• The more garbage is collected in the ON COMMIT DELETE temporary tables, the
sirable delay in the beginning of the
users’ work.
http://firebird-conference.com/
longer will be the delay between the first connection and the working. It takes
in InterBase/Firebird
What is UNICODE_FSS? Example
InterBase proceeds from the fact that UNICODE characters within the range
Working with database
[0x0000,0xFFFF] will be stored in UTF-8. Therefore, when specifying size for stor-
Exchange with server uses the following data categories:
ing text data with UNICODE_FSS codepage, the number of characters is multiplied
by 3 bytes. In addition, all current versions of InterBase, when working with •General text fields with CHAR and VARCHAR types
CHAR/VARCHAR data in data presentation, controls number of bytes, not of char- •BLOB text fields
acters. That is why, for example, one can enter up to 9 single-byte characters to the
CHAR(3) column with UNICODE_FSS codepage. •Arrays
•SQL query text.
This myth is based on the fact that the procedure after first
access query text is prepared. byte, and this may result in overflow.
A user does not have to worry about So please consider it, if you want to use call (that is the moment when query plans, written in the procedure,
calculation of size needed for text connections with several codepages in are computed) remains in the metadata cache until all clients, who
field data in the clipboard. We recom- the context of a single database. called this procedure, disconnect. In this case, actually, while the pro-
mend using the value specified in the cedure is in memory, query plans do not change, even if statistics of
definition of the field. However, do BLOB text fields the indexes used by the plans change. Read about this in InterBase
not forget that, for the VARCHAR As is well known, the link to data is documentation - DataDef.pdf, Chapter 9, section "Altering and drop-
columns (SQL_VARYING type), one stored in the InterBase record, which ping procedures in use".
should add 2 bytes to the specified contains a BLOB-field (subtype inde-
value, in order to reserve some space pendent). The data are stored separate-
for column length indicator. The ly and handled by InterBase API func- Arrays containing national coding characters to
returned value will be expressed in tions, designed specially for working UNICODE support in text arrays is simi- UTF-8, the resulting text may be larger
bytes. with BLOB. lar to the one for text fields. than the source one, and thus it would
exceed 64K limit.
TIP: As in the text fields case, the server,
when working with text arrays, operates
By the way, one of the undocumented features of InterBase is that for text Access components for
on the byte-level, not on the level of
fields in XSQLVAR.subtype the number of the field codepage is specified in
the lower byte, while the collate number is specified in the upper byte. characters. Therefore, the number of working with UNICODE_FSS
characters in a string written in an array Generally speaking, support of a specif-
When recording text fields, you That is to say, BLOB-fields data are read cell, may exceed the length specified ic codepage means that the access to
convert a text to UTF-8, and then and written with separate calls of API. when the text array column had been database component is able to ensure
handle it as an ordinary record. That is why the rules of working with text created. client’s work with other codepage. To
Buffer size and line length param- information in BLOB differ from the ones In exactly the same way, the server sup- do that, it is enough to guarantee con-
eters are expressed in bytes. of working with CHAR/VARCHAR. ports recoding of input and output version of text data (at that, UCS-2, an
The basic rule is: take care of yourself. arrays data, taking into account the con- intermediate format is used). Conver-
If the field codepage differs from the
By default, the server does not interpret nection codepage. sion of text columns, arrays and SQL-
codepage of connection to database,
contents of BLOB-fields, and treats them queries is not a problem at all, but BLOB
then the server performs conversion of
as ordinary binary information. Thus, fields conversion is quite a laborious
incoming and outgoing data. SQL query text
the client becomes responsible for data task, especially when accessing the
However, for all that, buffer size will be Strange as it may seem at first sight, SQL
recoding. BLOB field data through a stream mech-
computed according to the column query text is also must use a codepage
anism.
codepage. Thus, if the codepage of the Usually it is enough to use for connection to a database. The point
UNICODE_FSS coding on the client, is that a SQL query text is one of the Theoretically, client application, of
win1252 field and UNICODE_FSS con-
and not use UNICODE_FSS and one- methods of parameter values explicit course, should not depend on the code-
nection is used, and no other additional
byte coding simultaneously, since con- transfer. pages’ differences. Therefore, access
operations are launched, then you will
version to one-byte coding can cause components must block all possible
probably receive the «Cannot transliter- There are no severe limitations, except
data loss. ways of text data transfer, and provide
ate characters between character sets» for general length of an SQL query,
necessary information recoding.
error message. which is 64K. When converting a query
http://www.intel.com/support/pla two virtual processors would be slower In the "2 and more processors Server Server type Operating 2 and more
tform/ht/os.htm?iid=ipp_htm+os& than it is on two physical processors. If " column: system processors
Note: InterBase 7.1 tests on Windows in addition to a database, some appli- "No" – not recommended or it
cations are active on the server, then InterBase 6.0 SuperServer Windows No
2000 and Windows2003 with enabled makes sense to tie a server
HyperThreading have shown that Win enabling HT would cause decrease of process to a specific processor Linux No
2000’s productivity becomes worse. At general productivity (this does not con- (for example, for Windows Solaris-SPARC No
the same time, it is similar for both OS’, cern single-processor systems, in which through the ibaffinity utility or
if HT is disabled. That is why the ibcon- a slightly increase of productivity may Classic Linux Yes
through the CPU_AFFINITY
fig ENABLE_HYPERTHREADING para- be). parameter in ibconfig/fire- InterBase 6.5 SuperServer Windows No
meter for IB 7.1 is disabled by default. http://www.intel.com/technology/ bird.conf). Linux No
5. Generally, there are applications, hyperthread/
"Yes" – this server variant with Solaris-SPARC No
which may work incorrectly (fail) on this operating system will use
multiprocessor computers if Hyper- Supplement all processors. In IB 7.x, it is InterBase 7.x SuperServer Windows Yes
Threading is enabled. While we hope you understood that required to purchase proces- Linux Yes
(search Google for bsod+hyperthread- HyperThreading must be turned off on sor license for each additional Solaris-SPARC Yes
ing) server, it is still not clear whether it is physical processor.
better to use a single-processor server, Firebird 1.0 SuperServer Windows No
6. The HyperThreading technology is For clarity sake, "yes" variants
or a multiprocessor one. The answer to Linux No
designed for increasing of multi-thread in the table are typed in bold.
that question depends on architecture
applications’ productivity. Therefore, of the server and operating system: Solaris-x86 No
execution speed of two processes on HP-UX No
Classic Linux Yes
Solaris-x86 Yes
Solaris-SPARC Yes
FreeBSD Yes
MacOS/X Yes
HP-UX Yes
Firebird 1.5 SuperServer Windows No
Linux No
Classic Windows Yes
Linux Yes
FreeBSD Yes
MacOS/X Yes
Sinixz Yes
Solaris-x86 Yes
Yaffil SuperServer Windows No
Subscribe now! To receive future issues notifications send email to subscribe@ibdeveloper.com Classic Windows Yes