Difference between revisions of "Firebird/fr"

From Free Pascal wiki
Jump to navigationJump to search
Line 100: Line 100:
  
 
== Administration de la base de données ==
 
== Administration de la base de données ==
FPC/Lazarus has a component for database adminstration; see [[TFBAdmin/fr|TFBAdmin]]
+
FPC/Lazarus a un composant pour l'administration de base de données ; voir [[TFBAdmin/fr|TFBAdmin]].
  
 
== Problèmes courants et résolutions ==
 
== Problèmes courants et résolutions ==

Revision as of 06:12, 16 May 2017

English (en) français (fr) русский (ru)

Portail de la base de données

Références:

Tutoriels/articles pratiques :

Bases de données

Advantage - MySQL - MSSQL - Postgres - Interbase - Firebird - Oracle - ODBC - Paradox - SQLite - dBASE - MS Access - Zeos

Il s'agit d'un guide sur l'utilisation de la base de données Firebird dans Lazarus/FPC, en utilisant Firebird avec SQLdb (la bibliothèque de base de données intégrée dans Lazarus/FPC). D'autres méthodes d'accès sont décrites dans Autres bibliothèques Firebird.

Vue d'ensemble

Firebird est un serveur de bases de données, open source qui est utilisé et développé depuis des décennies (il s'est développé à partir d'Interbase 6 passé en Open source par Borland). Il inclut une prise en charge riche des ordres SQL (p.ex. INSERT...RETURNING), des procédures stockées, des déclencheurs (triggers), etc. Vous pouvez écrire des bibliothèques d'UDFs compilées (User-Defined Functions) pour le serveur en Free Pascal si vous voulez étendre la liste déjà étendue de fonctions de Firebird).

La base de données ne requiert que peu de travail manuel d'administration une fois configurée, la rendant idéale pour les petite affaires ou l'utilisation en incorporé. Il peut grossir jusqu'à l'échelle du tera-octet avec un réglage approprié, bien que PostgreSQL puisse être un meilleur choix pour de tels environnements.

Firebird offre à la fois des bases de données incorporées (sans serveur autonome) et en client/serveur - utilisable sans avoir à changer une seule ligne de code dans Lazarus/FPC. S'il est utilisé en mode incorporé, il offre un support plus riche de SQL que SQLite ainsi qu'une migration transparente vers une base de données client-serveur, alors que SQLite ne peut être qu'en mode incorporé.

La dernière version stable, Firebird 2.5, tourne sous Windows (32- et 64-bit), diverses versions de Linux (32- et 64-bit), (Sparc et Intel), HP-UX (PA-Risc), OSX et Androïd.

Il n'est pas disponible sur Windows CE/Windows Mobile.

La prise en charge de Firebird dans la bibliothèque SQLdb de FPC est plutôt bonne, comparable au niveau de celle de PostgreSQL.

Documentation

La documentation officielle est incluse dans FPC 2.6.2+ : Documentation SQLDB pour IBConnection.

Installation en client/serveur et en incorporé

Firebird peut fonctionner en mode client/serveur en mode incorporé.

Client/Server veut dire que vous avez un serveur Firebird quelque part : soit sur votre propre machine locale soit sur une autre machine accessible par votre réseau. Les connexions au serveur passent par TCP/IP ; en spécifiant la connexion, le nom d'hôte (hostname) contient un nom ou une adresse IP. La DLL firebird dont vous avez besoin pour ceci est fbclient.dll (avec ses fichiers de support).

Embedded Firebird veurt dire que votre application charge les DLLs Firebird sur une machine locale. En spécifiant la connexion, le nom d'hôte est toujours vide. La DLL Firebird dont vous avez besoin est 'fbembed.dll (avec ses fichiers de support).

Voir le wiki sur Firebird incorporé pour plus de détails.

Notez que fbembed.dll peut être utilisé à la fois en utilisation client/serveur et en incorporé, ainsi installer seulement cette DLL peut être une chose maline à faire.

Windows

Win64 : Veuillez lire l'avertissement ici sur l'emploi de certaines versions Win64 de FPC/Lazarus.

Sur Windows : (ceci s'applique à tous les pilotes SQLdb) vous devez avoir la DLL fbclient.dll (ou fbembed.dll) et DLLs de prise en charge installées dans :

  • le répertoire du projet et le répertoire de sortie de l'exécutable/celui de l'application (p.ex. lib/something dans le répertoire de votre projet).
  • ou un répertoire dans votre PATH (et non pas dans votre répertoire système).
  • Si vous voulez utilisez le répertoire système, veuillez utiliser l'installateur officiel et cocher "copy fbclient to system directory".

Comme avec toutes DLLs (base de données), la bitité (pas de terme pour bitness, largeur du bus d'adressage, 32 ou 64 bit) : utilisez une bibliothèque 32 bit pour un programme compilé en 32 bit et une bibliothèque 64 bit pour un programme compilé en 64 bit.

Unix/Linux/OSX

Sur Linux/OSX/FreeBSD, la bibliothèque client Firebird devrait être installée (p.ex. par votre gestionnaire de paquets ; installer le paquet normal et le paquet -dev), ou elle devrait être placée dans le chemin de recherche des bibliothèques.

FPC recherche les noms de bibliothèque les plus communes (p.ex. libfbclient.so.2.5, libgds.so et libfbembed.so.2.5 ; veuillez vérifier le fichier ibase60.inc si votre version est différente). Si vous le souhaitez, vous pouvez spécifier explicitement le nom de bibliothèque. Il y a deux façons de faire pour cela :

  • Utiliser le composant TSQLDBLibraryLoader de sqldblib (FPC 2.7.1). Fonctionne pour tous les composants connecteurs de SQLdb.
  • Appeler
    function InitialiseIBase60(Const LibraryName : AnsiString) : integer;
    avec la nom de bibliothèque correct (vous pouvez avoir besoin d'utiliser l'unité ibase60dyn pour cela).

Exemples de connexion

Exemple pour le client/serveur :

Hostname: 192.168.1.1
* The database is on the server with IP address 192.168.1.1. 
DatabaseName: /interdata/example.fdb  
* The name of the database file is "example.fdb" in the /interdata directory of the server (the machine with IP address 192.168.1.1).
Username: SYSDBA
Password: masterkey

Autre exemple pour le client/serveur :

Hostname: dbhost
* The database is on the server with the host name dbhost
DatabaseName: F:\Program Files\firebird\examples\employee.fdb  
* The name of the database file is "employee.fdb" in the Program Files\firebird\examples directory on the F: drive of dbhost.
Username: SYSDBA
Password: masterkey

Un exemple en incorporé :

Hostname: <empty string>
* Leaving the hostname empty selects embedded use.
DatabaseName: test.fdb
* The database file is "test.fdb" in the directory where the application runs (make sure fbembed.dll is in the application executable directory)
Username: SYSDBA
* On embedded, you do have to specify a username...
Password: <empty string>
* ... but it doesn't matter what password you give.

Solution à des problèmes client/serveur

Assurez-vous que vosu avez démarré le serveur Interbase/Firebird sur le serveur IP/hostname que vous avez spécifié. Vous pouvez tester la connectivité avec telnet sur la machine. Habituellement, Firebird écoute sur le port 3050 :

telnet 192.168.1.1 3050

Vous devriez voir quelque chose, peut-être juste un écran blanc, mais vous pouvez tapez quelque chose. Cela signifie que vous pouvez envoyer de la donnée vers la base de données Firebird.
Pour des informations plus détaillées, veuillez consulter la documentation Firebird.

Surveillance des événements

FPC/Lazarus vient avec un composant pour surveiller les événements provenant des bases de données de Firebird. Consultez TFBEventMonitor.

Création d'objets par programmation

Bien que vous puissiez utiliser des outils tels que Flamerobin pour créer des tables, etc., vous pouvez également les créer par programme ou dynamiquement, ce qui pourrait être utile lorsque vous souhaitez que vos programmes mettent à jour les schémas existants de la base de données vers un nouveau schéma.

Vous pouvez utiliser p.exe. TSQLQuery.ExecSQL pour réaliser cette tâche :

Query.ExecSQL('CREATE TABLE TEST(ID INTEGER NOT NULL, TESTNAME VARCHAR(800))');
// You need to commit the transaction after DDL before any DML - SELECT, INSERT etc statements.
// Otherwise the SQL won't see the created objects

Pour faire ceci, utiliser l'objet TSQLScript - voir TSQLScript.

Administration de la base de données

FPC/Lazarus a un composant pour l'administration de base de données ; voir TFBAdmin.

Problèmes courants et résolutions

Sometimes using Firebird in Lazarus seems to be tricky. Please find solutions below.

Tentative de mise à jour de colonne en lecture seule / champs COMPUTED BY

If you have COMPUTED BY fields (server-side calculated fields) in your Firebird table, SQLDB will not pick up that these are read only fields (for performance reasons).

In this case, auto-generated INSERTSQL,UPDATESQL statements can lead to error messages like "attempted update of read-only column". The solution is to manually specify that the field in question may not be updated after setting the TSQLQuery's SQL property, something like:

// Disable updating this field or searching for changed values as user cannot change it
sqlquery1.fieldbyname('full_name').ProviderFlags:=[];

Bigint: précision perdue

If you use the bigint datatype (64 bit signed integer) in Firebird, please use .AsLargeInt instead of .AsInteger for parameters:

// Assuming ID is bigint here
sqlquery1.sql.text := 'insert into ADDRESS (ID) values (:ID)';
// Use this:
sqlquery1.params.parambyname('ID').aslargeint := <some qword or 64 bit integer variable>;
// Do not use this:
//sqlquery1.params.parambyname('ID').asinteger := <some qword or 64 bit integer variable>;
...

... otherwise you might get errors like duplicate PK (primary key) - if using the bigint as a primary key.

Types de données Booléens

Firebird versions below 3.0 do not support boolean data types.

At least on FPC trunk (2.7.1) this datatype can be emulated:

Use a DOMAIN that uses a SMALLINT type (other integer types may work as well - please test and adjust text):

CREATE DOMAIN "BOOLEAN"
 AS SMALLINT
 CHECK (VALUE IS NULL OR VALUE IN (-1,0,1))
 /* -1 used for compatibility with FPC SQLDB; 1 is used by many other data access layers */
;


Let your field/column use this domain type e.g.

CREATE TABLE MYTABLE
(
...
  MYBOOLEANCOLUMN "BOOLEAN",
);
  • Now you can use .AsBoolean for assigning field values etc

To do: verify this works with Lazarus grids etc as well.

Problèmes INSERT INTO...RETURNING /Cursor is not open =

If you try to select SQL (e.g. Query.Open) with SQL like this:

INSERT INTO PEOPLE (NICKNAME) VALUES ('Superman') RETURNING ID

and get something like this error:

Database error:  : Fetch :
 -Dynamic SQL Error
 -SQL error code = -504
 -Invalid cursor reference
 -Cursor is not open(error code: 335544569)

while running FPC 2.6.0 (which is supplied with Lazarus 1.0) or lower, then you probably ran into an FPC SQLDB parser bug.

SQLDB thinks the statement you're running is a normal INSERT statement, which doesn't return data. Obviously, it should return data. Newer FPC code has fixes for this.

If you're using generators/sequences for your primary keys (like many do), a workaround is to first get the next sequence number:

SELECT NEXT VALUE FOR GEN_PEOPLEID FROM RDB$DATABASE /* If your generator name is GEN_PEOPLEID */

then use that to do a regular INSERT. see FAQ entry

Locate ne semble pas fonctionner

Source: Issue ##21988

When running locate on UTF8 (or presumably other multibyte character sets) CHAR fields, locate may not find your record.

The problem is related mostly to UTF8 charset used and how Firebird reports column length. In case of UTF8 Firebird reports the maximum column length (in bytes) as 4*"character length". So if you have a column defined as char(8), Firebird reports 4*8=32.

Values are right-padded to this length 32. When locating say '57200001' there is no match because the field actually stores '57200001 ........................' (with trailing spaces represented by dots here).

Workaround: rewrite your select query:

SELECT substring(THEFIELD from 1 for 8) AS THEFIELD ...
or
SELECT cast(THEFIELD as varchar(8)) as THEFIELD ...

or use VARCHAR fields.

Note: this problem may occur for other databases as well depending on their reporting of field length.

Transactions avancées

Sources for this information/further reading:

Niveaux d'isolation de transaction

If you want to, you can change the transaction isolation levels by adding a line in the transaction's Parameters property:

  • isc_tpb_read_committed: you see all changes committed by other transactions
  • isc_tpb_concurrency: also called Snapshot: you see database as it was when the transaction started. Has more overhead than isc_tpb_read_committed. Better than ANSI Serializable because it has no phantom reads.
  • isc_tpb_consistency: also called Table Stability: stable, serializable view of data, but locks tables. Unlikely you will need this

Exemple:

SQLTransaction1.Params.text:='isc_tpb_read_committed';

You can also add additional parameters that have an effect on the transaction (taken from the ibconnection.pp source file and [1]):

Mode d'accès

This allow reads only or read/write

  • isc_tpb_read: read permission
  • isc_tpb_write: read+write permission

Résolution de verrous (Lock resolution)

  • isc_tpb_nowait: if another transaction is editing the record then don't wait
  • isc_tpb_wait: if another transaction is editing the record then wait for it to finish. Can mitigate "live locks" in heavy contention ([2]). See below for timeout value.

Réservation de table

Deals with locking entire tables.

  • isc_tpb_shared: first specify this, then either lock_read or lock_write for one or more tables. Shared read or write mode for tables.
  • isc_tpb_protected: first specify this, then either lock_read or lock_write for one or more tables. Lock on tables; can allow deadlock-free operation at the cost of delayed transactions
  • isc_tpb_lock_read: Set a read lock. Specify which table to lock, e.g. isc_tpb_lock_read=CUSTOMERS
  • isc_tpb_lock_write: Set a read/write lock. Specify which table to lock, e.g. isc_tpb_lock_read=CUSTOMERS

Combinations:

  • Shared, lock_write: write transactions with concurrency or read committed isolation

can update the table. All transactions can read the table

  • Shared, lock_read: any transaction can read or update
  • Protected, lock_write: Other transactions cannot update the table. Only concurrency and

read committed transactions can read the table

  • Protected, lock_read: Other transactions cannot update the table. Any transaction can

read the table

Versions d'enregistrement

This setting is apparently only relevant for isc_tpb_read_committed isolation mode for records being modified by other transactions:

  • isc_tpb_no_rec_version: only newest record version is read. Can be useful for batch/bulk insert operations together with isc_tpb_read_committed)
  • isc_tpb_rec_version: the latest committed version is read, even when the other transaction has other uncommitted changes note: verify this. More overhead than isc_tpb_no_rec_version

Options diverses

For completeness, some more options appearing in the Firebird/Interbase FPC code. You will likely only ever use isc_tpb_no_auto_undo to speed up batch inserts/edits.

  • isc_tpb_exclusive (apparently translates to protected in Firebird, see [3])
  • isc_tpb_verb_time (Related to deferred constraints, which could execute at verb time or commit time. Firebird: not implemented, always use verb time)
  • isc_tpb_commit_time (Related to deferred constraints, which could execute at verb time or commit time. Firebird: not implemented, always use verb time)
  • isc_tpb_ignore_limbo (ignores the records created by transactions in limbo. Limbo transactions are failing two-phase commits in multi-database transactions. Unlikely that you will need this feature)
  • isc_tpb_autocommit (autocommit this transaction: every statement is a separate transaction. Probably specifically for JayBird JDBC driver.)
  • isc_tpb_restart_requests (apparently looks for requests in the connection which had been active in another transaction, unwinds them, and restarts them under the new transaction.)
  • isc_tpb_no_auto_undo (disable transaction-level undo log, handy for getting max throughput when performing a batch update. Has no effect when only reading data.)
  • isc_tpb_lock_timeout (specify number of seconds to wait for lock release, if you use isc_tpb_wait. If this value is reached without lock release, an error is reported.)

Firebird et les transactions ISO

Firebird transaction do not map 1 to 1 to ISO/ANSI transaction levels. An approximation is:

  • ISO Read Committed=READ COMMITTED+RECORD_VERSION
  • ISO Read Committed=READ COMMITTED+NO RECORD_VERSION
  • ISO Repeatable Read=SNAPSHOT (also known as CONCURRENCY)
  • ISO Serializable=SNAPSHOT TABLE STABILITY (also known as CONSISTENCY)

Combinaisons habituelles

Default is (probably, will have to check) read committed.

Insertion Batch/bulk

isc_tpb_read_committed and isc_tpb_no_rec_version could be a good combination: it allows other transactions to function while the batch is going on.

Transaction en lecture seule

If you want to only have read access to the database, you can do so by setting these transaction parameters:

  • isc_tpb_read
  • isc_tpb_read_committed
  • isc_tpb_rec_version
  • nowait

This combination will not block garbage collection, which is a good thing. Source: [4]

Note: the Firebird FAQ indicates you will need write access to the database file even if you only read from it, unless you set the database read-only flag (e.g. using gfix).

Liens et plus d'informations

The list below shows links to more information on Firebird and related tools.

Echantillons Lazarus Firebird

Outils

  • FlameRobin Flamerobin site Open source GUI tool to manage Firebird, available for Linux, Windows and Mac OSX. Highly recommended.
  • Turbobird Turbobird site Open source GUI tool to manage Firebird. Written with Lazarus using TIBConnection
  • ibconsole : Tool to manage Firebird an Interbase Databases with a GUI, available for Windows and Linux
  • Lazarus Data Desktop - included in the Lazarus repository (found in the 'tools/lazdatadesktop/' directory)
  • LazSQLX Multi-database open source database management tool. Written with Lazarus using both SQLDB and Zeos components. Includes support for Firebird.
  • tiSQLEditor - included in the "Support Apps" directory of the tiOPF repository. It is a tool used to write SQL with some code completion support, can run scripts, execute upgrade scripts for applications from one build to a later build, has various handy copy and paste functions for Object Pascal applications, has many features that are useful to tiOPF (creates Object Pascal code templates from query results, for tiOPF's visitor classes), export query results to CSV etc.

Firebird

  • Le SGBDR Firebird site de Firebird. Ce site contient aussi beaucoup de documentation sur Firebird.
  • FAQ Firebird [6]. Site pratique qui montre p.ex. les différences avec les autres SGBDR.