По сути, этот компонент можно использовать в приложении FCL-Web для превращения его в REST-сервер:
Затем сервер примет обычные команды REST GET/POST/PUT/Delete и автоматически переведет их в соответствующую базу данных CRUD (создание/чтение/обновление/удаление).
Его можно использовать просто: одной строки кода достаточно, чтобы таким образом представить полную базу данных.
Или это может быть полностью настроено и точно подкручено: схема может быть полностью определена: все операторы SQL могут быть заданы, могут быть определены списки полей, могут быть заданы псевдонимы, могут быть реализованы бизнес-правила.
Полученный в результате сервер можно использовать в установке клиента/сервера (например, используя pas2js в качестве клиента) для обслуживания данных без необходимости написания всего необходимого сантехнического кода на REST-сервере.
Чтобы использовать данные, обслуживаемые этим компонентом, вам нужно написать клиент.
Нет никаких предположений относительно клиента, за исключением того, что он знает, как выполнять HTTP-запросы, и что он понимает один из доступных форматов данных.
Он не предоставляет объекты в качестве ресурсов REST.
Используя некоторые приемы, это можно сделать, но это не цель проекта.
В конечном итоге все данные попадают в базу данных, и этот компонент использует прямой механизм для достижения этой цели.
Каждый ресурс REST определяется до 4 операторов SQL, соответствующих 4 операциям CRUD.
Операторы CRUD могут быть автоматически сгенерированы на лету на основе имени таблицы и определений полей.
Для каждого поля можно указать псевдоним.
Доступны следующие типы на стороне клиента, автоматически сопоставленные с собственным типом базы данных:
String
64-bit integer
32-bit integer
Boolean
Date, Time, DateTime
Blob (base64-encoded)
Встроена поддержка последовательностей для генерации идентификаторов.
Полный контроль над тем, какие операции (GET, POST, PUT, DELETE) разрешены.
Ресурсы собраны в схему.
К сервису могут быть прикреплены несколько схем.
Могут быть заданы несколько баз данных (соединений).
Схема может быть привязана к одному соединению, или соединения могут совместно использовать схемы (вариант использования: другое соединение для клиента).
Компоненты бизнес-процессоров могут быть подключены к ресурсу, чтобы упростить реализацию бизнес-логики.
Выражения SQL могут содержать параметры, значения для параметров будут взяты из URL запроса.
Поддержка для получения пользовательских наборов данных.
Поддержка клиентских операторов SQL SELECT (необязательно, по умолчанию отключено)
Полная поддержка конфигурации через файл .ini из коробки.
Может быть применен максимальный лимит. Когда операторы SQL поддерживают это, limit и offset переводятся в предложения fetch/offset [языка] SQL.
Порядок сортировки можно указать в URL-адресе запроса, если это позволяет определение ресурса, используя ?Sort=fieldname. Возможность сортировки может быть указана на основе поля. 5
Фильтрация может быть указана на основе поля в URL-адресе запроса, и операция фильтрации преобразуется в SQL-предложение Where:
PopulateResourceFields заполняет определения полей в aRes, проверяя таблицу в соединении с базой данных aConn. Каждое созданное поле получает как минимум aMinFieldOptions в его свойстве Options
PopulateResources создает определение ресурса для каждой таблицы в соединении с базой данных
PopulateResources извлекает список таблиц из aConn, создает определение ресурса для таблицы и вызывает PopulateResourceFields, чтобы заполнить ресурс полями. Если указано aTables, определения будут создаваться только для таблиц в этом списке.
OutputOptions (TRestOutputOptions) Параметры вывода по умолчанию, изменяемые по запросу. Один или несколько из:
ooMetadata отправка метаданных в запросе
ooSparse не отправлять null-значения (если формат позволяет)
ooHumanReadable "человекочитабельная" печать
InputFormat (string) - Имя формата ввода, используемого для всех запросов.
OutputFormat (string) - Имя формата вывода, используемого для всех запросов.
DispatchOptions (TRestDispatcherOptions) - Опции диспетчера. Один или несколько из
rdoConnectionInURL - использовать соединение в качестве элемента пути в URL
rdoExposeMetadata - выставлять URL метаданных
rdoCustomView - разрешить использование пользовательского URL-адреса (выбирается SQL, указанный в запросе)
rdoHandleCORS - обрабатывать предпосылаемый запрос CORS
rdoAccessCheckNeedsDB - эта [опция] контролирует, когда проверка доступа выполняется для ресурсов: до или после установления соединения с базой данных. Если вам необходимо выполнить дополнительные запросы к базе данных, чтобы решить, предоставляется ли доступ (например, проверка ACL в БД), этот параметр должен быть включен
Authenticator (TRestAuthenticator) - аутентификатор для запросов. Если установлено значение OnBasicAuthentication, его можно оставить пустым.
EnforceLimit (Integer) - если больше нуля, установить ограничение на выходные результаты.
CORSAllowedOrigins (String) - Разделенный запятыми список доменов, которым разрешено использовать эту службу REST. Если пусто, в предварительном запросе будет возвращено *.
ExposeDatabase выставляет базу данных в качестве службы REST. Это создаст определение соединения с предоставленными параметрами и вызовет ExposeConnection с этим определением.
The connection gets the name ConnectionN, where N is a unique number, and the schema is named SchemaConnectionN. The Tables and aMinFieldOpt arguments are the same as in the PopulateResources call of TSQLDBRestSchema
ExposeConnection exposes a database (represented by aConnection) as a REST service. This will create a schema with a resource definition.
This class implements HTTP Basic authentication for the SQLDB REST Dispatcher
AuthConnection (TSQLConnection) a SQL connection that will be used to run the SQL. By default the connection of the request is used. Set this if your users are in a separate database.
AuthenticateUserSQL (TStrings) an SQL Statement that will be executed on the connection (AuthConnection or connection of the request). This must contain 2 parameters userName and password and return a single field. This field will be used as UserID (available in the rest of the request flow.
DefaultUserName (UTF8String) a valid username, not in the database.
DefaultPassword (UTF8String) password of a default user.
DefaultUserID (UTF8String) the user ID reported if the default user is authenticated.
AuthenticationRealm : (UTF8String) Real sent in the WWW-Authenticate challenge to the client.
OnBasicAuthentication (event) triggered when basic authentication is requested. Here you can enter custom code to validate the user.
This is a simple TWebModule descendant which is usable in Lazarus IDE. It has a single Dispatcher property which must be set to a TSQLDBRestDispatcher instance.
Fields (TSQLDBRestFieldList) A list of fields that will be included in the output, or can be supplied in the input.
Enabled (Boolean) Is this resource enabled ?
InMetadata (Boolean) Should this resource be shown in the metadata list ?
ConnectionName (UTF8String) Connection name to use for this resource.
TableName (UTF8String) Database table name. This must only be specified if the SQL is auto generated.
ResourceName (UTF8String) Name of this resource as exposed to the outside world.
AllowedOperations (TRestOperations) The operations allowed on this resources (Get/Put/Post/Delete/Options/Head)
SQLSelect (TStrings) SQL select statement for a GET request. Left empty, it is autogenerated based on the table name. The where clause uses the fields with the foInKey flag set for single resources.
SQLInsert (TStrings) SQL INSERT statement for a POST request. Left empty, it is autogenerated based on the table name.
SQLUpdate (TStrings) SQL UPDATE statement for a PUT request. Left empty, it is autogenerated based on the table name. The where clause uses the fields with the foInKey flag set.
SQLDelete (TStrings) SQL DELETE statement for a DELETE request. Left empty, it is autogenerated based on the table name. The where clause uses the fields with the foInKey flag set.
'SQL an array of SQL statements, based on the previous ones.
BusinessProcessor (TSQLDBRestCustomBusinessProcessor) at runtime this contains the business processor for this resource (if any)
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:
Schema : The schema in which the resource resides.
ResourceName The resource for which the business rules are valid.
OnGetDataset : Event called when you want to create a custom dataset. You must free the dataset yourself.
OnCheckParams : Event in which you can verify whether the parameters for insert/update/delete/select queries are OK.
OnAllowResource : Event to decide whether a property is allowed for a request. You can use this e.g. to forbid certain users from accessing a resource.
OnAllowedOperations : Event to decide whether a REST operation is allowed for a request. You can use this to forbid certain users from writing to a resource, but allow them to read.
OnAllowRecord : Called for each record which will be output. This can be used to prevent certain records from being streamed to the output. Note that if Limit is specified, this will not be taken into account, i.e. if the limit is 10, and you forbid 2 records from being streamed at this point, only 8 records will be returned.
All calls get passed a TRestContext instance. This contains 2 properties and a method:
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.
Property UserID : UTF8String
This will be set when calling.
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.
The customView resource is special. Its availability must be enabled using the *Dispatcher'*s Options. When rdoCustomView is included in the options, the
baseURL/customView
URL becomes available. It allows the client to specify an SQL Select statement using the SQL parameter:
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.
(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/
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,
create a directory src below the components/fpweb directory (where the package is located)
copy all files in directory
packages/fcl-web/src/restbridge de
to directory
lazarus/components/fpweb/src
compile the lazsqldbrest.lpk package. It should find the files in the src directory and use them.
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)
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.
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:
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.
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.
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.
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.
The demo/bufclient directory contains a demo that shows how to load data from a SQLDB REST bridge server in a TBUFDataset dataset. It uses the 'buf' format to do so.
it also demonstrates how to use the metadata resource of the server to list the available resources