Sign in Join
Wiki copytemporary

SQLDBRestBridge/ru

English · Русский

Цель

Все больше и больше приложений перемещаются в Интернет: сегодня Pas2JS позволяет программировать паскаль для Интернета.

Данные должны храниться на сервере, и REST сегодня является предпочтительной архитектурой для этого. Чаще всего данные попадают в базу данных.

Поэтому необходим простой способ сделать данные доступными через службу REST.

Модуль SQLDBRestBridge предлагает средство для раскрытия любой базы данных, к которой SQLDB может получить доступ, используя REST API.

Это не подразумевается как общая структура REST API, для этого существуют другие платформы. Это также не структура RPC.

Конструкция такова, что полная база данных может быть представлена с использованием одной строки кода с разумными настройками по умолчанию.

Что компонент делает?

По сути, этот компонент можно использовать в приложении FCL-Web для превращения его в REST-сервер:

Затем сервер примет обычные команды REST GET/POST/PUT/Delete и автоматически переведет их в соответствующую базу данных CRUD (создание/чтение/обновление/удаление).

Его можно использовать просто: одной строки кода достаточно, чтобы таким образом представить полную базу данных.

Или это может быть полностью настроено и точно подкручено: схема может быть полностью определена: все операторы SQL могут быть заданы, могут быть определены списки полей, могут быть заданы псевдонимы, могут быть реализованы бизнес-правила.

Полученный в результате сервер можно использовать в установке клиента/сервера (например, используя pas2js в качестве клиента) для обслуживания данных без необходимости написания всего необходимого сантехнического кода на REST-сервере.

Чего компонент не делает?

Чтобы использовать данные, обслуживаемые этим компонентом, вам нужно написать клиент.

Нет никаких предположений относительно клиента, за исключением того, что он знает, как выполнять HTTP-запросы, и что он понимает один из доступных форматов данных.

Используя некоторые приемы, это можно сделать, но это не цель проекта.

В конечном итоге все данные попадают в базу данных, и этот компонент использует прямой механизм для достижения этой цели.

Характеристики

На стороне базы данных SQL

  1. Каждый ресурс REST определяется до 4 операторов SQL, соответствующих 4 операциям CRUD.
  2. Операторы CRUD могут быть автоматически сгенерированы на лету на основе имени таблицы и определений полей.
  3. Для каждого поля можно указать псевдоним.
  4. Доступны следующие типы на стороне клиента, автоматически сопоставленные с собственным типом базы данных:
    1. String
    2. 64-bit integer
    3. 32-bit integer
    4. Boolean
    5. Date, Time, DateTime
    6. Blob (base64-encoded)
  5. Встроена поддержка последовательностей для генерации идентификаторов.
  6. Полный контроль над тем, какие операции (GET, POST, PUT, DELETE) разрешены.
  7. Ресурсы собраны в схему.
  8. К сервису могут быть прикреплены несколько схем.
  9. Могут быть заданы несколько баз данных (соединений).
  10. Схема может быть привязана к одному соединению, или соединения могут совместно использовать схемы (вариант использования: другое соединение для клиента).
  11. Компоненты бизнес-процессоров могут быть подключены к ресурсу, чтобы упростить реализацию бизнес-логики.
  12. Выражения SQL могут содержать параметры, значения для параметров будут взяты из URL запроса.
  13. Поддержка для получения пользовательских наборов данных.
  14. Поддержка клиентских операторов SQL SELECT (необязательно, по умолчанию отключено)
  15. Полная поддержка конфигурации через файл .ini из коробки.

На стороне HTTP

  1. Аутентификация обрабатывается с использованием протокола HTTP.

  2. Базовая аутентификация включена по умолчанию, но полностью подключаема.

  3. Обычная аутентификация может искать действительных пользователей в базе данных (по умолчанию база данных незащищенная).

  4. Выходной формат может быть зафиксирован или определен для каждого запроса (?Fmt=format). Обнаружение по типу контента также доступно.

  5. Список полей для включения в вывод можно указать в URL:
    fl=field1,field2

  6. Список полей, исключаемых из вывода, может быть указан в URL:
    fe=field1,field2

  7. Различные форматы вывода доступны из коробки

    1. JSON (по умолчанию)
    2. XML (пользовательский формат)
    3. CSV (для ввода и вывода)
    4. CDS (Формат, используемый Delphi'йским TClientDataset)
    5. Запланировано: пакеты данных ADO (как он используется MS Access)
  8. Используется заводской шаблон, новые форматы могут быть добавлены по желанию.

  9. Простые схемы URL. Доступны 2 основные схемы BASEURL/Resource/ BASEURL/Resource/ID

    или используя соединение в качестве префикса:

    pascal
    BASEURL/Connection/Resource/
    BASEURL/Connection/Resource/ID
  10. Поддержка самоанализа/обнаружения или метаданных: BASEURL/metadata/

    возвращает список доступных ресурсов и их операций.

    pascal
    BASEURL/metadata/resourcename

    возвращает структуру ресурса: поля, типы и т. д.

  11. параметры limit и offset для подкачки результатов: BASEURL/resourcename?limit=10 BASEURL/resourcename?limit=10&Offset=50

    Может быть применен максимальный лимит. Когда операторы SQL поддерживают это, limit и offset переводятся в предложения fetch/offset [языка] SQL.

  12. Порядок сортировки можно указать в URL-адресе запроса, если это позволяет определение ресурса, используя ?Sort=fieldname. Возможность сортировки может быть указана на основе поля. BASEURL/resourcename?sort=MyField BASEURL/resourcename?sort=MyField%20desc

  13. Фильтрация может быть указана на основе поля в URL-адресе запроса, и операция фильтрации преобразуется в SQL-предложение Where: BASEURL/resourcename?MyField=10 BASEURL/resourcename?MyField_null=1 BASEURL/resourcename?MyField_null=0 BASEURL/resourcename?MyField_lt=10 BASEURL/resourcename?MyField_lte=10 BASEURL/resourcename?MyField_gt=10 BASEURL/resourcename?MyField_gte=10

    переводится в SQL-предложение WHERE:

    pascal
    (MyField=10)
    (MyField is null)
    (MyField is not null)
    (MyField<10)
    (MyField_lte<=10)
    (MyField>10)
    (MyField>=10)

    Возможность фильтрации по полю можно указать в схеме для каждого поля.

  14. Запрос может указать, должны ли метаданные быть включены в ответ: BASEURL/resourcename?metadata=1

  15. Запрос может указывать, должен ли результат быть понятным для человека или нет BASEURL/resourcename?humanreadable=1

    Если установлено значение 1, результат запроса будет отформатирован. Не все форматы поддерживают это.

Доступные компоненты

TSQLDBRestSchema

Представляет схему REST: список доступных ресурсов с их разрешенными операциями, определения полей, операторы SQL.

Свойства

Методы

delphi
Procedure SaveToFile(Const aFileName : UTF8String);
delphi
Procedure SaveToStream(Const aStream : TStream);
delphi
function AsJSON(const aPropName: UTF8String=''): TJSONData;

Если указано, aPropName - это имя свойства, ниже которого хранятся все определения.

delphi
Procedure LoadFromFile(Const aFileName : UTF8String);
delphi
Procedure LoadFromStream(Const aStream : TStream);
delphi
Procedure FromJSON(aData: TJSONData;const aPropName: UTF8String='');

Если указано, aPropName - имя свойства, под которым расположены все определения.

delphi
procedure PopulateResourceFields(aConn: TSQLConnection; aRes: TSQLDBRestResource; aMinFieldOpts : TRestFieldOptions = []);

PopulateResourceFields заполняет определения полей в aRes, проверяя таблицу в соединении с базой данных aConn. Каждое созданное поле получает как минимум aMinFieldOptions в его свойстве Options

delphi
procedure PopulateResources(aConn: TSQLConnection; aTables: array of string; aMinFieldOpts: TRestFieldOptions= []);
procedure PopulateResources(aConn : TSQLConnection; aTables : TStrings = Nil; aMinFieldOpts : TRestFieldOptions = []);

TSQLDBRestDispatcher

Свойства

  1. ooMetadata отправка метаданных в запросе
  2. ooSparse не отправлять null-значения (если формат позволяет)
  3. ooHumanReadable "человекочитабельная" печать
  1. rdoConnectionInURL - использовать соединение в качестве элемента пути в URL
  2. rdoExposeMetadata - выставлять URL метаданных
  3. rdoCustomView - разрешить использование пользовательского URL-адреса (выбирается SQL, указанный в запросе)
  4. rdoHandleCORS - обрабатывать предпосылаемый запрос CORS
  5. rdoAccessCheckNeedsDB - эта [опция] контролирует, когда проверка доступа выполняется для ресурсов: до или после установления соединения с базой данных. Если вам необходимо выполнить дополнительные запросы к базе данных, чтобы решить, предоставляется ли доступ (например, проверка ACL в БД), этот параметр должен быть включен

Методы

TRestBasicAuthenticator

This class implements HTTP Basic authentication for the SQLDB REST Dispatcher

TSQLDBRestModule

TSQLDBRestResource

This is a collection item, found in the 'Resources' property of the TSQLDBRestSchema. It represents a single REST resource.

properties

It has the following properties:

Events

The following events are available:

Note: when set, the corresponding event in the business processor is not triggered.

Methods

The following methods exist:

pascal
 Function GetDataset(aContext : TBaseRestContext; aFieldList : TRestFieldPairArray; aOrderBy : TRestFieldOrderPairArray; aLimit, aOffset : Int64) : TDataset;

Get the custom dataset for this resource.

pascal
 function GenerateDefaultSQL(aKind: TSQLKind): UTF8String; virtual;

Get the default SQL for this resource if none was specified.

pascal
 function GetFieldList(aListKind: TFieldListKind): UTF8String;

Return a list of fields as a string, separated by a correct separator token

pascal
 function GetFieldArray(aListKind: TFieldListKind): TSQLDBRestFieldArray;

Return a list of fields, similar to GetFieldList, but returns the raw fields.

pascal
 Function GetResolvedSQl(aKind : TSQLKind; Const AWhere : UTF8String; Const aOrderBy : UTF8String = ; aLimit : UTF8String = ) : UTF8String;

Return the actual SQL Statement that will be executed, with macros

pascal
 Procedure PopulateFieldsFromFieldDefs(Defs : TFieldDefs; aIndexFields : TStringArray; aProcessIdentifier : TProcessIdentifier; aMinFieldOpts : TRestFieldOptions);

Populate the fields collection from a TFieldDefs collection.

TSQLDBRestField

The TSQLDBREstResource has a collection of fields (TSQLDBRestField) that determine the output fields of the REST resource

It has the following properties;

TSQLDBRestBusinessProcessor

This class serves to implement any business rules you want to attach to your rest resource. You can drop one TSQLDBRestBusinessProcessor instance per resource on a module, set the schema and resource name (a list of resource names is available in the Object Inspector) and implement the events.

The following properties and events are available:

All calls get passed a TRestContext instance. This contains 2 properties and a method:

pascal
  Function GetVariable(Const aName : UTF8String; aSources : TVariableSources; Out aValue : UTF8String) : Boolean;

Call this to get a HTTP Query variable, header,... The function returns true if the variable was found.

text
  Property UserID : UTF8String

This will be set when calling.

text
  Property Data : TObject

You can attach data to this if you want to. It will be kept for the duration of the request. You are responsible for freeing this data, though.

Special Resources

metaData

The /baseURL/metaData resource lists all the resources defined in the schema, together with the allowed operations.

The usual formats and parameters are supported.

metaData/resourceName

The /baseURL/metaData/resourceName resource lists all the fields in the resourceName resource, together with the properties.

The usual formats and parameters are supported for this resource.

customview

The customView resource is special. Its availability must be enabled using the Dispatcher's Options. When rdoCustomView is included in the options, the

text
 baseURL/customView

URL becomes available. It allows the client to specify an SQL Select statement using the SQL parameter:

text
 baseURL/customView?SQL=select count(*) as thecount from person

(you must encode the sql using the usual URI encoding mechanism, it is omitted for readability reasons here) The usual parameters for fieldlists, format are supported, but not the limit and offset parameters.

The engine will check that only SELECT statements passed on. Nevertheless, this is an inherently less safe mechanism which should only be used in case of need.

_connection

(Work in progress) This is a resource that allows you to manage the connections through REST. This can be useful in development environments, where you can simply create a single binary that does not need any configuration, the whole configuration can be done through REST, including the management of the available connections.

Because this is security-wise a dangerous option to enable, it is disabled by default, and must be enabled explicitly with the rdoConnectionResource option of the dispatcher.

Use cases are a development environment where this can be used to confiure the restserver from within the IDE. When moving to production, the option can be disabled, and only fixed and known connections will be allowed/

Available Output formats

JSON (the default)

XML (a custom format)

CSV

CDS

A Delphi demo program is provided.

ADO

Ini file Support

The following classes can load/save their configuration settings from/to an .ini file

The support for this is implemented in 2 units;

The helpers implement LoadFromFile/SaveToFile methods, as well as LoadFromIni/SaveToIni methods. There are some options to control the level of depth.

The schemas (if so required) are saved as JSON files in the same directory as the .ini file, using the name of the schema as the filename.

Lazarus Support

Lazarus support for the SQLDB REST Bridge is in the lazsqldbrest.lpk package, under the fpweb directory. It registers the TSQLDBRestDispatcher, TSQLDBRestSchema and TRestBasicAuthenticator components on the component palette:

Additionally it registers some component- and property editors:

Further integration with Lazarus is planned: 1. Add a nicer schema editor 1. Let the IDE act as a REST server. (alternatively, add a tool with a menu entry under tools for easy configuration)

Lazarus support can work with FPC 3.0.4. To make this work, the files can be copied from SVN or a 3.2 release to the lazarus fpweb directory.

To this end,

  1. create a directory src below the components/fpweb directory (where the package is located)
  2. copy all files in directory
text
 packages/fcl-web/src/restbridge de

to directory

text
 lazarus/components/fpweb/src
  1. compile the lazsqldbrest.lpk package. It should find the files in the src directory and use them.

Pas2JS Support

The SQLDB Rest bridge will be integrated in the compile server that comes with pas2JS: This means that pas2js will come with a toll that

So no actual server is needed during development.

Usage

In a fcl-web application.

The rest bridge was designed to be simple to use.

Expose a single database, no authentication.

Simple expose of a database. Run the following code in the startup of your program (for example, DoRun of the web application class, or startup code of the program)

delphi
FDisp:=TSQLDBRestDispatcher.Create(Self);
FDisp.ExposeDatabase(
    'postgres','localhost','expensetracker','me','secret'
    ,Nil,
    [foFilter,foInInsert,foInUpdate,foOrderByDesc]);
FDisp.Active:=True;   
FDisp.SaveToFile('demo.ini');

This exposes all tables of the database 'expenstracker', allows to filter,update and sort on all fields. The connection will be named 'Connection1', the schema 'SchemaConnection1'

The configuration will be saved in a file called 'demo.ini'.
It can be reused to quickly set up a REST dispatcher.

Expose single database, HTTP Basic authentication.

Similar to the previous example, but with HTTP BASIC authentication for a single user:

delphi
FAuth:=TRestBasicAuthenticator.Create(Self);
FAuth.DefaultUserName:='me';
FAuth.DefaultPassword:='secret';
FDisp:=TSQLDBRestDispatcher.Create(Self);
FDisp.Authenticator:=Fauth;
FDisp.ExposeDatabase(
    'postgres','localhost','expensetracker','me','secret'
    ,Nil,
    [foFilter]);
FDisp.Active:=True;

This exposes all tables of the database 'expenstracker', allows to filter,update and sort on all fields. The connection will be named 'Connection1', the schema 'SchemaConnection1'. No updates are possible: the fields will not be in update/insert statements. Sorting is also not allowed.

Expose single database, HTTP Basic authentication (2)

Smilar to the previous example, but with HTTP BASIC authentication, using the database to authenticate a user:

delphi
FAuth:=TRestBasicAuthenticator.Create(Self);
FAuth.AuthenticateUserSQL.Text:='select uID from users where (uLogin=:UserName) and (uPassword=:Password)';
FDisp:=TSQLDBRestDispatcher.Create(Self);
FDisp.Authenticator:=Fauth;
FDisp.ExposeDatabase(
    'postgres','localhost','expensetracker','me','secret'
    ,['projects','expenses'],
    []);
FDisp.Active:=True;

Here only the 'projects' and 'expenses' tables are exposed, read-only.

Using a Config file and schema files.

Start a dispatcher, loading the file demo.ini. The dioSkipReadSchemas tells it not to load schema files, the schemas will be created from the connections.

delphi
FDisp:=TSQLDBRestDispatcher.Create(Self);
FDisp.LoadFromFile('demo.ini',[dioSkipReadSchemas]);
FDisp.Active:=True;

The .ini file can be created using SaveToFile on a configured dispatcher instance.

In the lazarus IDE.

To work in the lazarus IDE with the SQLDB Rest bridge, you must install the lazsqldbrest package, which can be found in the directory components/fpWeb.

Using a datamodule

In this approach, a datamodule is created that is in memory throughout the whole lifetime of the application (fcl-web application)

  1. Create a HTTP server application or FCGI application. (a CGI will also work but is very inefficient)
  2. Add a plain datamodule to the application.
  3. Drop a TSQLDBRestSchema class from the 'FCL-Web' tab of the component palette
  4. Edit the schema (property resources), or import it from file using the component editor context menu
  5. Drop a TSQLDBRestDispatcher class from the 'FCL-Web' tab of the component palette
  6. Edit the connections
  7. Add an item to the Schemas property and point it to the TSQLDBRestSchema added previously
  8. For HTTP Basic authentication, add a TRESTBAsicAuthenticator class, and set the TSQLDBRestDispatcher instance's Authentocator property to it.

The end result should look more or less like this:

That's it. The project is ready to run.

Using a SQLDBRestdatamodule

This approach is basically the same as the previous one.

  1. Create a HTTP application
  2. Under File - New, create a SQLDB Rest Bridge Module.
  3. Drop a SQLDBRestDispatcher component on the module.
  4. The Dispatcher property of the module should be set to the SQLDBRestDispatcher component.
  5. Set up the component as required, as in the previous example.

Examples

FPC

Design time view:

Run time view:

Lazarus

There are 2 server examples available, and several client examples. The client examples are all the same, they just use a different kind of TDataset to show the data coming from the server: the buf, json and CSV formats are demonstrated in this way.

Server examples

TBufDataset client example

it also demonstrates how to use the metadata resource of the server to list the available resources

TJSONDataset client example

it shows how to load data from a SQLDB REST bridge server in a TBaseJSONDataset dataset, using the 'csv' format

Like the bufdataset demo, it also demonstrates how to use the metadata resource of the server to list the available resources

TCSVDataset client example

it shows how to load data from a SQLDB REST bridge server in a TCSVDataset dataset, using the 'csv' format

Pas2JS

TODO

The following extensions are still planned:


From the Free Pascal wiki, page "SQLDBRestBridge/ru", as it stood on 2023-09-25 after a change by Zoltanleo, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 3, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.