Difference between revisions of "Firebird embedded/ru"

From Lazarus wiki
Jump to navigationJump to search
Line 27: Line 27:
 
# использовать 32-битную FPC и Lazarus на Windows 64
 
# использовать 32-битную FPC и Lazarus на Windows 64
  
== Installation ==
+
== Установка ==
On Windows, Firebird embedded and regular Firebird client libraries are different files. Firebird embedded can always serve as a regular client, making it a logical choice for inclusion in your installation.
+
В Windows встроенный Firebird и обычные клиентские библиотеки Firebird - это разные файлы. Встроенный Firebird всегда может служить обычным клиентом, что делает его логичным выбором для включения в вашу установку.
  
  
 
=== Windows ===
 
=== Windows ===
Download and unzip the Firebird embedded kit. Make sure the .dll and .manifest files are either:
+
Загрузите и разархивируйте комплект embedded Firebird. Убедитесь, что файлы .dll и .manifest находятся либо:  
* in your project directory and executable output directory (where the .exe is generated) or
+
* в каталоге вашего проекта и в каталоге исполняемых файлов (где генерируется .exe), либо
* in a directory in your PATH (not your system directory) (useful if you don't want to keep copying dlls)
+
* в каталоге в вашем PATH (не в системном каталоге) (полезно, если вы не хотите сохранять скопированные dll)  
Note that bitness must match: you must use the 64 bit embedded version if you compile your program for 64 bit, and 32 if you're writing 32 bit programs.
 
Also make sure the the .dlls and .manifest files are placed in your project output (executable) directory, and distribute them with your applications, along with the license files.
 
  
As an indication, the minimum necessary files for Firebird 2.5 are:
+
Обратите внимание, что битность должна совпадать: вы должны использовать embedded x64 версию, если вы компилируете свою программу под 64-бит, и embedded x32, если вы пишете 32-битные программы. Также убедитесь, что файлы .dlls и .manifest размещены в выходном (исполняемом) каталоге вашего проекта, и распространяйте их вместе с приложениями и файлами лицензий.
 +
 
 +
Как указание, минимально необходимыми файлами для Firebird 2.5 являются:
 
* fbembed.dll
 
* fbembed.dll
 
* firebird.msg
 
* firebird.msg
Line 52: Line 52:
  
 
=== Linux ===
 
=== Linux ===
For Debian, probably similar for Ubuntu:
+
Для Debian, вероятно, похоже на Ubuntu:
Get library files as well as the symlink: e.g. /usr/lib/x86_64-linux-gnu/libfbembed.so linking to /user/lib/x86_64-linux-gnu/libfbembed.so.bla.x.y
+
получите файлы библиотеки, а также символическую ссылку: например, /usr/lib/x86_64-linux-gnu/libfbembed.so linking для /user/lib/x86_64-linux-gnu/libfbembed.so.bla.x.y
 
<syntaxhighlight lang=bash>
 
<syntaxhighlight lang=bash>
 
aptitude install libfbembed2.5 firebird-dev
 
aptitude install libfbembed2.5 firebird-dev
 
</syntaxhighlight>
 
</syntaxhighlight>
  
For at least Firebird 2.5+: Do not specify a username or password as that will force a lookup to security.fdb which may fail if system-wide security.fdb cannot be accessed. Do specify the role RDB$ADMIN on Firebird 2.5+ as that should give you full control over the database file.
+
По крайней мере, для Firebird 2.5+: не указывайте имя пользователя или пароль, так как это приведет к поиску security.fdb, что может привести к сбою в случае невозможности доступа к общесистемному security.fdb. Укажите роль RDB$ADMIN в Firebird 2.5+, так как она должна дать вам полный контроль над файлом базы данных.
  
Put these files in your project directory (to do: test if this is all needed):
+
Поместите эти файлы в каталог вашего проекта (для этого: проверьте, все ли это необходимо):
  firebird/libfbembed.so (or perhaps libfbembed.so.2.5)
+
  firebird/libfbembed.so (или возможно libfbembed.so.2.5)
 
  firebird.conf
 
  firebird.conf
  firebird/security.fdb #perhaps not necessary
+
  firebird/security.fdb #возможно, нет необходимости
 
  firebird/intl/fbintl
 
  firebird/intl/fbintl
 
  firebird/udf/fbudf.so
 
  firebird/udf/fbudf.so
  
For Firebird 3 you will need:
+
Для Firebird 3 вам понадобится:
 
  firebird/libfbclient.so
 
  firebird/libfbclient.so
 
  plugins/libEngine12.so
 
  plugins/libEngine12.so
  
You need to change plugins directory variable. If you cannot do that you need libEngine into its original directory.
+
Вам нужно изменить переменную каталога плагинов. Если вы не можете этого сделать, вам нужно поместить libEngine в его оригинальный каталог.
  
Had set this in firebird.conf (to do: check if this is all needed)
+
Установите это в firebird.conf (для этого: проверьте, все ли это необходимо)
 
<syntaxhighlight lang=ini>
 
<syntaxhighlight lang=ini>
RootDirectory=./firebird #replace with your directory
+
RootDirectory=./firebird #замените на ваш каталог
DatabaseAccess = Full #probably useful
+
DatabaseAccess = Full #наверное полезно
ExternalFileAccess = Full #probably useful
+
ExternalFileAccess = Full #наверное полезно
UdfAccess = Full #probably useful
+
UdfAccess = Full #наверное полезно
 
#disable
 
#disable
#TempDirectories = /tmp #=> didn't fix /tmp/firebird lock issues
+
#TempDirectories = /tmp #=> не удалось исправить проблемы блокировки /tmp/firebird
#TempDirectories = ~/tmp #=> didn't fix /tmp/firebird lock issues
+
#TempDirectories = ~/tmp #=> не удалось исправить проблемы блокировки /tmp/firebird
 
</syntaxhighlight>
 
</syntaxhighlight>
  
2 environment variables need to be set before the application is started.
+
Перед запуском приложения необходимо установить 2 переменные среды. Предположим, что приложение установлено в /home/pascaldev/embed:
Supposing the application is installed in /home/pascaldev/embed:
 
 
<syntaxhighlight lang="bash">
 
<syntaxhighlight lang="bash">
# tell dynamic loader where to find embedded lib:
+
# сообщаем динамическому загрузчику, где найти embedded lib:
 
LD_LIBRARY_PATH=/home/pascaldev/embed/firebird
 
LD_LIBRARY_PATH=/home/pascaldev/embed/firebird
# tell server where to find files (messages, config etc)
+
# сообщаем серверу, где искать файлы (сообщения, настройки и т. д.)
FIREBIRD=. #or use absolute path: /home/pascaldev/embed
+
FIREBIRD=. #или используйте абсолютный путь: /home/pascaldev/embed
 
</syntaxhighlight>
 
</syntaxhighlight>
  
If you hit errors like
+
Если вы поймали ошибку такую, как
  
 
  EIBDatabaseError/ : DoInternalConnect :
 
  EIBDatabaseError/ : DoInternalConnect :
 
   -Can't access lock files' directory /tmp/firebird
 
   -Can't access lock files' directory /tmp/firebird
  
you probably have stale lock files lying around that are owned by another user
+
возможно, у вас лежат устаревшие файлы блокировки, принадлежащие другому пользователю. Удаление каталога /tmp/firebird работает, но проблема в том, что он будет воссоздан под вашими локальными разрешениями.
Deleting the /tmp/firebird directory works, but the problem is that it will be recreated under your own local permissions
 
  
See [http://www.firebirdfaq.org/faq51/ How to setup Firebird embedded on Linux or Mac?] for hints on working with embedded Firebird on Linux or Apple OSX.
+
См. [http://www.firebirdfaq.org/faq51/ Как установить embedded Firebird на Linux or Mac?] для подсказок по работе со встроенным Firebird на Linux или Apple OSX.
Somebody used Firebird embedded with FPC: [http://www.mwasoftware.co.uk/index.php?option=com_content&task=view&id=105 Earlier version of Firebird embedded on Linux]
+
Кто-то использовал embedded Firebird в FPC: [http://www.mwasoftware.co.uk/index.php?option=com_content&task=view&id=105 Более ранняя версия embedded Firebird на Linux].
  
 
=== OSX ===
 
=== OSX ===
* todo: write this, perhaps adapt [http://www.mwasoftware.co.uk/index.php?option=com_content&task=view&id=105 Earlier version of Firebird embedded on Linux] and especially [http://paulbeachsblog.blogspot.mx/2012/09/firebird-embedded-on-macosx.html]
+
* todo: описать это, возможно адаптация [http://www.mwasoftware.co.uk/index.php?option=com_content&task=view&id=105 Более ранняя версия embedded Firebird на Linux] и особенно [http://paulbeachsblog.blogspot.mx/2012/09/firebird-embedded-on-macosx.html Firebird Embedded на MacOSX]
  
 
=== FreeBSD ===
 
=== FreeBSD ===
* to do: write this, perhaps adapt [http://www.mwasoftware.co.uk/index.php?option=com_content&task=view&id=105 Earlier version of Firebird embedded on Linux]
+
* to do: описать это, возможно адаптация [http://www.mwasoftware.co.uk/index.php?option=com_content&task=view&id=105 Более ранняя версия embedded Firebird на Linux]
  
 
== Connecting to Firebird servers ==
 
== Connecting to Firebird servers ==

Revision as of 22:52, 12 October 2019

English (en) русский (ru)

Что это такое

Firebird Embedded - это специальная версия сервера баз данных Firebird. Она позволяет вам запускать ваши программы без выделенного (прим.перев.: предварительно запущенного) сервера базы данных. Вместо этого вы добавляете библиотеку (.dll/.so/.dylib) в свое приложение) и позволяете вашему приложению получать доступ к файлу базы данных Firebird .fdb с помощью этой библиотеки.

Это похоже на работу таких программ, как Microsoft Access и LibreOffice Base.

Преимущества:

  • работает на многих архитектурах (Linux, OSX, Windows, FreeBSD, Solaris)
  • отдельная настройка сервера не требуется, что снижает сложность использования
  • вы можете легко переключаться с embedded на полноценный клиент/сервер - без изменения строк кода (кроме строки подключения). Это, вероятно, хорошее преимущество по сравнению с sqlite.
  • прим.перев.: не требуется пароль (он может быть произвольным)

Недостатки:

  • только однопользовательский доступ
  • необходимо распространять некоторые библиотеки вместе с вашей программой при ее распространении (если вы не можете статически связать их)

Предупреждение: Windows x64

Warning-icon.png

Предупреждение: В версиях FPC ниже FPC 2.7.1 r23738 (март 2013 г.), FPC x64 в Windows не очень хорошо работает с embedded dll Firebird или другими DLL. Раздел ниже содержит обходной путь, если у вас есть старая версия FPC

В версиях FPC ниже 2.7.1 r23738 вы можете получать ошибки/исключения объекта IBConnection, даже если вы пишете правильный код(см., например, Create database bug report.

Обходное решение:

  1. перейти к моментальному снимку разработки/версии FPC после FPC 2.7.1 r23738; см. Exception handling has been changed to be ABI-conformant
  2. если на FPC 2.7.1 ниже, чем r23738, скомпилируйте FPC с ключом -dTEST_WIN64_SEH, чтобы использовать новый код Структурированной Обработки Исключений (SEH) на Win64.
  3. использовать 32-битную FPC и Lazarus на Windows 64

Установка

В Windows встроенный Firebird и обычные клиентские библиотеки Firebird - это разные файлы. Встроенный Firebird всегда может служить обычным клиентом, что делает его логичным выбором для включения в вашу установку.


Windows

Загрузите и разархивируйте комплект embedded Firebird. Убедитесь, что файлы .dll и .manifest находятся либо:

  • в каталоге вашего проекта и в каталоге исполняемых файлов (где генерируется .exe), либо
  • в каталоге в вашем PATH (не в системном каталоге) (полезно, если вы не хотите сохранять скопированные dll)

Обратите внимание, что битность должна совпадать: вы должны использовать embedded x64 версию, если вы компилируете свою программу под 64-бит, и embedded x32, если вы пишете 32-битные программы. Также убедитесь, что файлы .dlls и .manifest размещены в выходном (исполняемом) каталоге вашего проекта, и распространяйте их вместе с приложениями и файлами лицензий.

Как указание, минимально необходимыми файлами для Firebird 2.5 являются:

  • fbembed.dll
  • firebird.msg
  • ib_util.dll
  • icudt30.dll
  • icuin30.dll
  • icuuc30.dll
  • IDPLicense.txt
  • IPLicense.txt
  • Microsoft.VC80.CRT.manifest
  • msvcp80.dll
  • msvcr80.dll

Linux

Для Debian, вероятно, похоже на Ubuntu: получите файлы библиотеки, а также символическую ссылку: например, /usr/lib/x86_64-linux-gnu/libfbembed.so linking для /user/lib/x86_64-linux-gnu/libfbembed.so.bla.x.y

aptitude install libfbembed2.5 firebird-dev

По крайней мере, для Firebird 2.5+: не указывайте имя пользователя или пароль, так как это приведет к поиску security.fdb, что может привести к сбою в случае невозможности доступа к общесистемному security.fdb. Укажите роль RDB$ADMIN в Firebird 2.5+, так как она должна дать вам полный контроль над файлом базы данных.

Поместите эти файлы в каталог вашего проекта (для этого: проверьте, все ли это необходимо):

firebird/libfbembed.so (или возможно libfbembed.so.2.5)
firebird.conf
firebird/security.fdb #возможно, нет необходимости 
firebird/intl/fbintl
firebird/udf/fbudf.so

Для Firebird 3 вам понадобится:

firebird/libfbclient.so
plugins/libEngine12.so

Вам нужно изменить переменную каталога плагинов. Если вы не можете этого сделать, вам нужно поместить libEngine в его оригинальный каталог.

Установите это в firebird.conf (для этого: проверьте, все ли это необходимо)

RootDirectory=./firebird #замените на ваш каталог
DatabaseAccess = Full #наверное полезно
ExternalFileAccess = Full #наверное полезно
UdfAccess = Full #наверное полезно
#disable
#TempDirectories = /tmp #=> не удалось исправить проблемы блокировки /tmp/firebird
#TempDirectories = ~/tmp #=> не удалось исправить проблемы блокировки /tmp/firebird

Перед запуском приложения необходимо установить 2 переменные среды. Предположим, что приложение установлено в /home/pascaldev/embed:

# сообщаем динамическому загрузчику, где найти embedded lib:
LD_LIBRARY_PATH=/home/pascaldev/embed/firebird
# сообщаем серверу, где искать файлы (сообщения, настройки и т. д.)
FIREBIRD=. #или используйте абсолютный путь: /home/pascaldev/embed

Если вы поймали ошибку такую, как

EIBDatabaseError/ : DoInternalConnect :
 -Can't access lock files' directory /tmp/firebird

возможно, у вас лежат устаревшие файлы блокировки, принадлежащие другому пользователю. Удаление каталога /tmp/firebird работает, но проблема в том, что он будет воссоздан под вашими локальными разрешениями.

См. Как установить embedded Firebird на Linux or Mac? для подсказок по работе со встроенным Firebird на Linux или Apple OSX. Кто-то использовал embedded Firebird в FPC: Более ранняя версия embedded Firebird на Linux.

OSX

FreeBSD

Connecting to Firebird servers

As mentioned, Firebird embedded can work like a regular Firebird client. Therefore, using the embedded Firebird library instead of the client/server Firebird library can help make your application more flexible.

Note: there is a bug at least in Firebird embedded 2.5.3 together with FPC 2.6.4 that crashes when closing a connection to a remote server. This bug has been fixed in FPC trunk.

Use

Once you have the proper Firebird embedded libraries in the right path (see above), you need to specify that you are connecting to an embedded instead of a client server environment. Leave the hostname property of the IBConnection object empty. The rest of the properties work like in the client/server version, e.g. the DatabaseName is the full path to your .fdb file - or just the database name if it is in the same directory as fbembed.dll. Additionally, older versions of FPC (FPC 2.6.2+ certainly don't need this) may require that you set the UseEmbeddedFirebird property to true. The property is not present in the SQLDB units, but you need to add ibase60dyn to your uses clause.

Creating databases

Using Firebird ISQL

You can create databases by using the Firebird isql application (e.g. as provided in the regular Firebird (client) package). On Windows, this executable should be in the same directory as your fbembed.dll. Note: isql expects the fbclient library, not fbembed; you can copy and rename fbembed, e.g. into fbclient.dll on Windows, to fix this. Run isql, then do:

create database 'employee.fdb' user 'SYSDBA' password 'masterkey' page_size 16384 default character set UTF8;
exit;

Dropping/deleting a database would basically mean deleting the file, but you can also run: isql

connect 'employee.fdb' user 'sysdba' password 'masterkey';
drop database;
commit;
exit;

Programmatically

You can also create a database from within your program. The program in the Creating the test database section below shows how you can detect missing databases and create them on the fly. A similar procedure could be called in Lazarus applications when initializing your form (FormShow event).

Creating objects like tables,views,triggers,...

Creating the objects - as most things - is the same in Firebird and Firebird embedded. Please see Firebird#Creating_objects_programmatically

Running FPC database test suite

It can be useful to run the FPC database test framework (in packages\fcl-db\tests) when you are hunting bugs, trying to find out how something works, or improving the database code.

Telling the framework which database to use

You will need to edit the db test framework .ini file to tell the test executable that it needs to use your embedded database. See Databases#Running_FPC_database_tests for instructions on how to do this.

Creating the test database

If you have set up the framework to use Firebird, you will need to prepare the environment for testing.

Copy over the Firebird embedded libraries and other files for your architecture into the test directory.

Now create the test database - manually or programmatically

Manually creating a database

isql

create database 'test.fdb' user 'SYSDBA' password 'masterkey' page_size 16384 default character set UTF8;
exit;

Programmatically creating a database

You can programmatically create a database. The example below creates a local, embedded database, but it can be easily changed to a remote database (adjust hostname and if necessary path):

program firebirdembeddedtest;
{$mode objfpc}{$H+}

uses 
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF} 
  Classes, SysUtils,
  sqldb, IBConnection {for Firebird};

const
  // Name for the database. Be sure to specify the same name in your database.ini
  DatabaseFile = 'test.fdb'; //Sensible name for a test database, right?
var
  Fire: TIBConnection;

begin
  //Connection to Firebird database
  // The next line is needed for quite old FPC versions
  // Newer versions will first look for fbembed.dll in the application directory automatically
  //UseEmbeddedFirebird:=true; // Using embedded (and fbembed.dll) or regular client/server (fbclient.dll), requires ibase60dyn in uses
  Fire:=TIBConnection.Create(nil);
  try
    Fire.HostName := ''; //must be empty for embedded Firebird; must be filled for client/server Firebird
    Fire.DatabaseName := DatabaseFile; //(path and) filename
    // Username and password do not matter for authentication, but you do get authorizations in the database
    // based on the name (and optionally role) you give.
    Fire.Username := 'SYSDBA';
    Fire.Password := 'masterkey'; //default password for SYSDBA
    Fire.Charset := 'UTF8'; //Send and receive string data in UTF8 encoding
    Fire.Dialect := 3; //Nobody uses 1 or 2 anymore.
    Fire.Params.Add('PAGE_SIZE=16384'); //I like a large page size (used when creating a database). Useful for larger indexes=>larger possible column sizes

    // Find out if there is a database in the application directory.
    // If not, create it. Note: this may fail if you don't have enough permissions.

    // If you use client/server, you obviously don't need this part of the code.
    if (FileExists(DatabaseFile)=false) then
    begin
        writeln('File '+DatabaseFile+' does not exist.');
        writeln('Creating a Firebird embedded database...');
        // Create the database as it doesn't exist
        try
          Fire.CreateDB; //Create the database file.
        except
          on E: Exception do
          begin
            writeln('ERROR creating database. Probably problems loading embedded library:');
            writeln('- not all files present');
            writeln('- wrong architecture (e.g. 32 bit instead of 64 bit)');
            writeln('Exception message:');
            writeln(E.ClassName+'/'+E.Message);
          end;
        end;
        Fire.Close;
    end;
  finally
    Fire.Free;
  end; 
end.

Running the test suite

Finally compile and run the dbtestframework.pas database test program. It should generate status output on the console and XML output in files with test results that can be analysed and sent to developers.

External references