Sign in Join
Wiki copytemporary

SQLDBRestBridge/ru: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11## Цель
22
33Все больше и больше приложений перемещаются в Интернет: сегодня Pas2JS позволяет программировать паскаль для Интернета.
44
55Данные должны храниться на сервере, и REST сегодня является предпочтительной архитектурой для этого. Чаще всего данные попадают в базу данных.
66
77Поэтому необходим простой способ сделать данные доступными через службу REST.
88
99Модуль `SQLDBRestBridge` предлагает средство для раскрытия любой базы данных, к которой SQLDB может получить доступ, используя REST API.
1010
1111Это не подразумевается как общая структура REST API, для этого существуют другие платформы. Это также не структура RPC.
1212
1313Конструкция такова, что полная база данных может быть представлена с использованием одной строки кода с разумными настройками по умолчанию.
1414
1515### Что компонент делает?
1616
1717По сути, этот компонент можно использовать в приложении FCL-Web для превращения его в REST-сервер:
1818
1919Затем сервер примет обычные команды REST GET/POST/PUT/Delete и автоматически переведет их в соответствующую базу данных CRUD (создание/чтение/обновление/удаление).
2020
2121Его можно использовать просто: одной строки кода достаточно, чтобы таким образом представить полную базу данных.
2222
2323Или это может быть полностью настроено и точно подкручено: схема может быть полностью определена: все операторы SQL могут быть заданы, могут быть определены списки полей, могут быть заданы псевдонимы, могут быть реализованы бизнес-правила.
2424
2525Полученный в результате сервер можно использовать в установке клиента/сервера (например, используя pas2js в качестве клиента) для обслуживания данных без необходимости написания всего необходимого сантехнического кода на REST-сервере.
2626
2727### Чего компонент не делает?
2828
2929- Это технология на стороне сервера.
3030
3131
3232Чтобы использовать данные, обслуживаемые этим компонентом, вам нужно написать клиент.
3333
3434Нет никаких предположений относительно клиента, за исключением того, что он знает, как выполнять HTTP-запросы, и что он понимает один из доступных форматов данных.
3535
3636- Он не предоставляет объекты в качестве ресурсов REST.
3737
3838
3939Используя некоторые приемы, это можно сделать, но это не цель проекта.
4040
4141В конечном итоге все данные попадают в базу данных, и этот компонент использует прямой механизм для достижения этой цели.
4242
4343## Характеристики
4444
4545### На стороне базы данных SQL
4646
47471. Каждый ресурс REST определяется до 4 операторов SQL, соответствующих 4 операциям CRUD.
48482. Операторы CRUD могут быть автоматически сгенерированы на лету на основе имени таблицы и определений полей.
49493. Для каждого поля можно указать псевдоним.
50504. Доступны следующие типы на стороне клиента, автоматически сопоставленные с собственным типом базы данных:
5151 1. String
5252 2. 64-bit integer
5353 3. 32-bit integer
5454 4. Boolean
5555 5. Date, Time, DateTime
5656 6. Blob (base64-encoded)
57575. Встроена поддержка последовательностей для генерации идентификаторов.
58586. Полный контроль над тем, какие операции (GET, POST, PUT, DELETE) разрешены.
59597. Ресурсы собраны в схему.
60608. К сервису могут быть прикреплены несколько схем.
61619. Могут быть заданы несколько баз данных (соединений).
626210. Схема может быть привязана к одному соединению, или соединения могут совместно использовать схемы (вариант использования: другое соединение для клиента).
636311. Компоненты бизнес-процессоров могут быть подключены к ресурсу, чтобы упростить реализацию бизнес-логики.
646412. Выражения SQL могут содержать параметры, значения для параметров будут взяты из URL запроса.
656513. Поддержка для получения пользовательских наборов данных.
666614. Поддержка клиентских операторов SQL SELECT (необязательно, по умолчанию отключено)
676715. Полная поддержка конфигурации через файл `.ini` из коробки.
6868
6969### На стороне HTTP
7070
71711. Аутентификация обрабатывается с использованием протокола HTTP.
72722. Базовая аутентификация включена по умолчанию, но полностью подключаема.
73733. Обычная аутентификация может искать действительных пользователей в базе данных (по умолчанию база данных незащищенная).
74744. Выходной формат может быть зафиксирован или определен для каждого запроса (`?Fmt=format`). Обнаружение по типу контента также доступно.
75755. Список полей для включения в вывод можно указать в URL:\
7676 `fl=field1,field2`
77776. Список полей, исключаемых из вывода, может быть указан в URL:\
7878 `fe=field1,field2`
79797. Различные форматы вывода доступны из коробки
8080 1. JSON (по умолчанию)
8181 2. XML (пользовательский формат)
8282 3. CSV (для ввода и вывода)
8383 4. CDS (Формат, используемый Delphi'йским `TClientDataset`)
8484 5. Запланировано: пакеты данных ADO (как он используется MS Access)
85858. Используется заводской шаблон, новые форматы могут быть добавлены по желанию.
86869. Простые схемы URL. Доступны 2 основные схемы
8787 BASEURL/Resource/
8888 BASEURL/Resource/ID
8989
9090 или используя соединение в качестве префикса:
9191
9292 BASEURL/Connection/Resource/
9393 BASEURL/Connection/Resource/ID
949410. Поддержка самоанализа/обнаружения или метаданных:
9595 BASEURL/metadata/
9696
9797 возвращает список доступных ресурсов и их операций.
9898
9999 BASEURL/metadata/resourcename
100100
101101 возвращает структуру ресурса: поля, типы и т. д.
10210211. параметры `limit` и `offset` для подкачки результатов:
103103 BASEURL/resourcename?limit=10
104104 BASEURL/resourcename?limit=10&Offset=50
105105
106106 Может быть применен максимальный лимит. Когда операторы SQL поддерживают это, `limit` и `offset` переводятся в предложения fetch/offset \[языка\] SQL.
10710712. Порядок сортировки можно указать в URL-адресе запроса, если это позволяет определение ресурса, используя `?Sort=fieldname`. Возможность сортировки может быть указана на основе поля.
108108 BASEURL/resourcename?sort=MyField
109109 BASEURL/resourcename?sort=MyField%20desc
11011013. Фильтрация может быть указана на основе поля в URL-адресе запроса, и операция фильтрации преобразуется в SQL-предложение Where:
111111 BASEURL/resourcename?MyField=10
112112 BASEURL/resourcename?MyField_null=1
113113 BASEURL/resourcename?MyField_null=0
114114 BASEURL/resourcename?MyField_lt=10
115115 BASEURL/resourcename?MyField_lte=10
116116 BASEURL/resourcename?MyField_gt=10
117117 BASEURL/resourcename?MyField_gte=10
118118
119119 переводится в SQL-предложение WHERE:
120120
121121 (MyField=10)
122122 (MyField is null)
123123 (MyField is not null)
124124 (MyField<10)
125125 (MyField_lte<=10)
126126 (MyField>10)
127127 (MyField>=10)
128128
129129 Возможность фильтрации по полю можно указать в схеме для каждого поля.
13013014. Запрос может указать, должны ли метаданные быть включены в ответ:
131131 BASEURL/resourcename?metadata=1
13213215. Запрос может указывать, должен ли результат быть понятным для человека или нет
133133 BASEURL/resourcename?humanreadable=1
134134
135135 Если установлено значение 1, результат запроса будет отформатирован. Не все форматы поддерживают это.
136136
137137## Доступные компоненты
138138
139139### TSQLDBRestSchema
140140
141141Представляет схему REST: список доступных ресурсов с их разрешенными операциями, определения полей, операторы SQL.
142142
143143#### Свойства
144144
145145- **Resources**: коллекция ресурсов. Каждый пункт имеет тип *TSQLDBRestResource*
146146- **ConnectionName**: установите это для имени соединения, если вы хотите, чтобы все ресурсы этой схемы использовали это соединение.
147147
148148#### Методы
149149
150150- **SaveToFile** сохраняет определения ресурса в файл (как JSON)
151151
152152```delphi
153153Procedure SaveToFile(Const aFileName : UTF8String);
154154```
155155
156156- **SaveToFile** сохраняет определения ресурсов в поток (как JSON)
157157
158158```delphi
159159Procedure SaveToStream(Const aStream : TStream);
160160```
161161
162162- **AsJSON** возвращает определения ресурса в виде объекта JSON
163163
164164```delphi
165165function AsJSON(const aPropName: UTF8String=''): TJSONData;
166166```
167167
168168Если указано, **aPropName** - это имя свойства, ниже которого хранятся все определения.
169169
170170- **LoadFromFile** загружает определения ресурсов из файла JSON
171171
172172```delphi
173173Procedure LoadFromFile(Const aFileName : UTF8String);
174174```
175175
176176- **LoadFromStream** загружает определения ресурсов из потока JSON
177177
178178```delphi
179179Procedure LoadFromStream(Const aStream : TStream);
180180```
181181
182182- **FromJSON** загружает определения ресурсов из файла JSON
183183
184184```delphi
185185Procedure FromJSON(aData: TJSONData;const aPropName: UTF8String='');
186186```
187187
188188Если указано, **aPropName** - имя свойства, под которым расположены все определения.
189189
190190- **PopulateResourceFields** создает поля ресурсов на основе имени таблицы
191191
192192```delphi
193193procedure PopulateResourceFields(aConn: TSQLConnection; aRes: TSQLDBRestResource; aMinFieldOpts : TRestFieldOptions = []);
194194```
195195
196196*PopulateResourceFields* заполняет определения полей в *aRes*, проверяя таблицу в соединении с базой данных *aConn*. Каждое созданное поле получает как минимум *aMinFieldOptions* в его свойстве *Options*
197197
198198- **PopulateResources** создает определение ресурса для каждой таблицы в соединении с базой данных
199199
200200```delphi
201201procedure PopulateResources(aConn: TSQLConnection; aTables: array of string; aMinFieldOpts: TRestFieldOptions= []);
202202procedure PopulateResources(aConn : TSQLConnection; aTables : TStrings = Nil; aMinFieldOpts : TRestFieldOptions = []);
203203```
204204
205205- *PopulateResources* извлекает список таблиц из *aConn*, создает определение ресурса для таблицы и вызывает *PopulateResourceFields*, чтобы заполнить ресурс полями. Если указано *aTables*, определения будут создаваться только для таблиц в этом списке.
206206
207207### TSQLDBRestDispatcher
208208
209209#### Свойства
210210
211211- **Active** (Boolean) Регистрирует или отменяет регистрацию HTTP маршрутов
212212- **Connections** (TSQLDBRestConnectionList) Список подключений к базе данных для соединения
213213- **Schemas** (TSQLDBRestSchemaList) Список схем REST для обслуживания
214214- **BasePath** (UTF8String) Базовый URL для REST URL
215215- **DefaultConnection** (UTF8String) Соединение по умолчанию для использования, если ни одно не обнаружено из запроса/схемы
216216- **Strings** (TRestStringsConfig Property) Конфигурации строк ввода/вывода
217217- **OutputOptions** (TRestOutputOptions) Параметры вывода по умолчанию, изменяемые по запросу. Один или несколько из:
218218
2192191. *ooMetadata* отправка метаданных в запросе
2202202. *ooSparse* не отправлять null-значения (если формат позволяет)
2212213. *ooHumanReadable* "человекочитабельная" печать
222222
223223- **InputFormat** (string) - Имя формата ввода, используемого для всех запросов.
224224- **OutputFormat** (string) - Имя формата вывода, используемого для всех запросов.
225225- **DispatchOptions** (TRestDispatcherOptions) - Опции диспетчера. Один или несколько из
226226
2272271. *rdoConnectionInURL* - использовать соединение в качестве элемента пути в URL
2282282. *rdoExposeMetadata* - выставлять URL метаданных
2292293. *rdoCustomView* - разрешить использование пользовательского URL-адреса (выбирается SQL, указанный в запросе)
2302304. *rdoHandleCORS* - обрабатывать предпосылаемый запрос CORS
2312315. *rdoAccessCheckNeedsDB* - эта \[опция\] контролирует, когда проверка доступа выполняется для ресурсов: до или после установления соединения с базой данных. Если вам необходимо выполнить дополнительные запросы к базе данных, чтобы решить, предоставляется ли доступ (например, проверка ACL в БД), этот параметр должен быть включен
232232
233233- **Authenticator** (TRestAuthenticator) - аутентификатор для запросов. Если установлено значение *OnBasicAuthentication*, его можно оставить пустым.
234234- **EnforceLimit** (Integer) - если больше нуля, установить ограничение на выходные результаты.
235235- **CORSAllowedOrigins** (String) - Разделенный запятыми список доменов, которым разрешено использовать эту службу REST. Если пусто, в предварительном запросе будет возвращено *.
236236
237237#### Методы
238238
239239- **ExposeDatabase** выставляет базу данных в качестве службы REST. Это создаст определение соединения с предоставленными параметрами и вызовет **ExposeConnection** с этим определением.
240240 ```delphi
241241 Function ExposeDatabase(Const aType,aHostName,aDatabaseName,aUserName,aPassword : String; aTables : Array of String; aMinFieldOpt)
242242 Function ExposeDatabase(Const aType,aHostName,aDatabaseName,aUserName,aPassword : String; aTables : TStrings = nil; aMinFieldOpt)
243243 ```
244244
245245 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**
246246- **ExposeConnection** exposes a database (represented by *aConnection*) as a REST service. This will create a schema with a resource definition.
247247 ```delphi
248248 Function ExposeConnection(Const aConnection : TSQLDBRestConnection; aTables : TStrings = nil; aMinFieldOpts : TRestFieldOptions
249249 ```
250250
251251 The Tables and aMinFieldOpt arguments are the same as in the *PopulateResources* call of **TSQLDBRestSchema**
252252
253253### TRestBasicAuthenticator
254254
255255This class implements HTTP Basic authentication for the SQLDB REST Dispatcher
256256
257257- 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.
258258- 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.
259259- DefaultUserName (UTF8String) a valid username, not in the database.
260260- DefaultPassword (UTF8String) password of a default user.
261261- DefaultUserID (UTF8String) the user ID reported if the default user is authenticated.
262262- AuthenticationRealm : (UTF8String) Real sent in the **WWW-Authenticate** challenge to the client.
263263- OnBasicAuthentication (event) triggered when basic authentication is requested. Here you can enter custom code to validate the user.
264264
265265### TSQLDBRestModule
266266
267267- 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.
268268
269269### TSQLDBRestResource
270270
271271This is a collection item, found in the 'Resources' property of the **TSQLDBRestSchema**. It represents a single REST resource.
272272
273273#### properties
274274
275275It has the following properties:
276276
277277- **Fields** (TSQLDBRestFieldList) A list of fields that will be included in the output, or can be supplied in the input.
278278- **Enabled** (Boolean) Is this resource enabled ?
279279- **InMetadata** (Boolean) Should this resource be shown in the metadata list ?
280280- **ConnectionName** (UTF8String) Connection name to use for this resource.
281281- **TableName** (UTF8String) Database table name. This must only be specified if the SQL is auto generated.
282282- **ResourceName** (UTF8String) Name of this resource as exposed to the outside world.
283283- **AllowedOperations** (TRestOperations) The operations allowed on this resources (Get/Put/Post/Delete/Options/Head)
284284- **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.
285285- **SQLInsert** (TStrings) SQL INSERT statement for a POST request. Left empty, it is autogenerated based on the table name.
286286- **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.
287287- **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.
288288- *'SQL* an array of SQL statements, based on the previous ones.
289289- **BusinessProcessor** (TSQLDBRestCustomBusinessProcessor) at runtime this contains the business processor for this resource (if any)
290290
291291#### Events
292292
293293The following events are available:
294294
295295- **OnResourceAllowed** (TSQLDBRestAllowResourceEvent) Called to check whether the user is allowed to access this resource.
296296- **OnAllowedOperations** (TSQLDBRestAllowedOperationsEvent) Called to allow to fine-tune the allowed operations for the user.
297297- **OnGetDataset** (TSQLDBRestGetDatasetEvent) You can return a custom dataset for GET operations.
298298- **OnCheckParams** (TSQLDBRestCheckParamsEvent) You can check the INSERT/UPDATE/DELETE SQL Statement parameters in this request/
299299- **OnAllowRecord** (TSQLDBRestAllowRecordEvent) Called for each record, you can ddecide whether the record should be included in the output.
300300
301301Note: when set, the corresponding event in the business processor is not triggered.
302302
303303#### Methods
304304
305305The following methods exist:
306306
307-` Function GetDataset(aContext : TBaseRestContext; aFieldList : TRestFieldPairArray; aOrderBy : TRestFieldOrderPairArray; aLimit, aOffset : Int64) : TDataset;`
307+``` pascal
308+ Function GetDataset(aContext : TBaseRestContext; aFieldList : TRestFieldPairArray; aOrderBy : TRestFieldOrderPairArray; aLimit, aOffset : Int64) : TDataset;
309+```
308310
309311Get the custom dataset for this resource.
310312
311-` function GenerateDefaultSQL(aKind: TSQLKind): UTF8String; virtual;`
313+``` pascal
314+ function GenerateDefaultSQL(aKind: TSQLKind): UTF8String; virtual;
315+```
312316
313317Get the default SQL for this resource if none was specified.
314318
315-` function GetFieldList(aListKind: TFieldListKind): UTF8String;`
319+``` pascal
320+ function GetFieldList(aListKind: TFieldListKind): UTF8String;
321+```
316322
317323Return a list of fields as a string, separated by a correct separator token
318324
319-` function GetFieldArray(aListKind: TFieldListKind): TSQLDBRestFieldArray;`
325+``` pascal
326+ function GetFieldArray(aListKind: TFieldListKind): TSQLDBRestFieldArray;
327+```
320328
321329Return a list of fields, similar to GetFieldList, but returns the raw fields.
322330
323-` Function GetResolvedSQl(aKind : TSQLKind; Const AWhere : UTF8String; Const aOrderBy : UTF8String = `*`; aLimit : UTF8String =`*`) : UTF8String;`
331+``` pascal
332+ Function GetResolvedSQl(aKind : TSQLKind; Const AWhere : UTF8String; Const aOrderBy : UTF8String = ; aLimit : UTF8String = ) : UTF8String;
333+```
324334
325335Return the actual SQL Statement that will be executed, with macros
326336
327-` Procedure PopulateFieldsFromFieldDefs(Defs : TFieldDefs; aIndexFields : TStringArray; aProcessIdentifier : TProcessIdentifier; aMinFieldOpts : TRestFieldOptions);`
337+``` pascal
338+ Procedure PopulateFieldsFromFieldDefs(Defs : TFieldDefs; aIndexFields : TStringArray; aProcessIdentifier : TProcessIdentifier; aMinFieldOpts : TRestFieldOptions);
339+```
328340
329341Populate the fields collection from a TFieldDefs collection.
330342
331343### TSQLDBRestField
332344
333345The TSQLDBREstResource has a collection of fields (TSQLDBRestField) that determine the output fields of the REST resource
334346
335347It has the following properties;
336348
337349- FieldName (UTF8String Read FFieldName Write FFieldName;
338350- PublicName (UTF8String Read GetPublicName Write FPublicName;
339351- GeneratorName (String) name of a generator to privide a unique value.
340352- FieldType (TRestFieldType) Data type of the exposed field.One of (the names speak for themselves)
341353 - rftInteger
342354 - rftLargeInt
343355 - rftFloat
344356 - rftDate
345357 - rftTime
346358 - rftDateTime
347359 - rftString
348360 - rftBoolean
349361 - rftBlob (sent as base64-encoded data)
350362- NativeFieldType (TFieldType) Native database field type of this field.
351363- Options (TRestFieldOptions) options for this field. One of more of:
352364 - foInKey This is a key field.
353365 - foInInsert The field can be inserted (if statement is autogenerated)
354366 - foInUpdate The field can be updated (if statement is autogenerated)
355367 - foRequired A field value is required.
356368 - foFilter Filtering is allowed on this field.
357369 - foOrderBy Ordering is allowed on this field.
358370 - foOrderByDesc Ordering (descendent) is allowed on this field.
359371- Filters (TRestFieldFilters) Allowed filter expressions for this field. One or more of:
360372 - rfEqual
361373 - rfLessThan
362374 - rfGreaterThan
363375 - rfLessThanEqual
364376 - rfGreaterThanEqual
365377 - rfNull
366378- MaxLen (integer) for string fields, the maximum allowed length of the field.
367379
368380### TSQLDBRestBusinessProcessor
369381
370382This 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.
371383
372384The following properties and events are available:
373385
374386- **Schema** : The schema in which the resource resides.
375387- **ResourceName** The resource for which the business rules are valid.
376388- **OnGetDataset** : Event called when you want to create a custom dataset. You must free the dataset yourself.
377389- **OnCheckParams** : Event in which you can verify whether the parameters for insert/update/delete/select queries are OK.
378390- **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.
379391- **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.
380392- **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.
381393
382394All calls get passed a TRestContext instance. This contains 2 properties and a method:
383395
384-`  Function GetVariable(Const aName : UTF8String; aSources : TVariableSources; Out aValue : UTF8String) : Boolean;`
396+``` pascal
397+ Function GetVariable(Const aName : UTF8String; aSources : TVariableSources; Out aValue : UTF8String) : Boolean;
398+```
385399
386400Call this to get a HTTP Query variable, header,... The function returns true if the variable was found.
387401
388-`  Property UserID : UTF8String`
402+```text
403+ Property UserID : UTF8String
404+```
389405
390406This will be set when calling.
391407
392-`  Property Data : TObject`
408+```text
409+ Property Data : TObject
410+```
393411
394412You 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.
395413
396414## Special Resources
397415
398416### metaData
399417
400418The */baseURL/metaData* resource lists all the resources defined in the schema, together with the allowed operations.
401419
402420The usual formats and parameters are supported.
403421
404422### metaData/resourceName
405423
406424The */baseURL/metaData/resourceName* resource lists all the fields in the **resourceName** resource, together with the properties.
407425
408426The usual formats and parameters are supported for this resource.
409427
410428### customview
411429
412430The customView resource is special. Its availability must be enabled using the *Dispatcher*'s Options. When *rdoCustomView* is included in the options, the
413431
414-` baseURL/customView`
432+```text
433+ baseURL/customView
434+```
415435
416436URL becomes available. It allows the client to specify an SQL Select statement using the *SQL* parameter:
417437
418-` baseURL/customView?SQL=select count(*) as thecount from person`
438+```text
439+ baseURL/customView?SQL=select count(*) as thecount from person
440+```
419441
420442(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.
421443
422444The 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.
423445
424446### _connection
425447
426448(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.
427449
428450Because 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.
429451
430452Use 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/
431453
432454## Available Output formats
433455
434456### JSON (the default)
435457
436458- A simple JSON object encapsulating data, metadata and possibly error nodes.
437459- rows are exported as JSON objects, field names are property names of the object.
438460- Name: 'json'
439461- Content-type: 'application/json'
440462- Input and output.
441463- Data by default under 'data'
442464- Metadata by default under 'metaData'
443465- Errors reported under 'error'
444466- Property names are configurable in REST dispatcher.
445467
446468### XML (a custom format)
447469
448470- A simple XML document encapsulating data, metadata and possibly error nodes, under a root element 'datapacket'
449471- rows are exported as XML elements (named 'row') , the contents as text in the element.
450472- Name: 'xml'
451473- Content-type: 'text/xml'
452474- Input and output.
453475- Data by default under 'data'
454476- Metadata by default under 'metadata'
455477- Errors reported under 'error'
456478- Element names are configurable in REST dispatcher.
457479
458480### CSV
459481
460482- Simple comma-separated CSV list.
461483- Name: 'csv'
462484- Content-type: 'text/csv'
463485- Input and output.
464486- Separator: Comma
465487- Quotes when needed.
466488- Metadata means first line contains fieldnames.
467489
468490### CDS
469491
470492- XML package using the XMLFormat used by Delphi `TClientDataset`.
471493- Name: 'cds'
472494- Content-type: 'text/csv'
473495- Input and output.
474496
475497A Delphi demo program is provided.
476498
477499### ADO
478500
479501- XML format as used by ADO recordsets (as used by MS Access)
480502- Name: 'ado'
481503- Input and output.
482504
483505## Ini file Support
484506
485507The following classes can load/save their configuration settings from/to an .ini file
486508
487509- TSQLDBRestDispatcher
488510- TRestBasicAuthenticator
489511- TSQLDBRestConnection
490512- TRestStringsConfig
491513
492514The support for this is implemented in 2 units;
493515
494516- the sqldbauthini unit has a type helper for the TRestBasicAuthenticator class.
495517- The sqldbrestini unit has the type helpers for TSQLDBRestDispatcher and TSQLDBRestConnection and TRestStringsConfig.
496518
497519The helpers implement LoadFromFile/SaveToFile methods, as well as LoadFromIni/SaveToIni methods. There are some options to control the level of depth.
498520
499521The 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.
500522
501523## Lazarus Support
502524
503525Lazarus 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:
504526
505527![](/wiki-images/d/d6/Sqldbrestcomponents.png)
506528
507529Additionally it registers some component- and property editors:
508530
509531Further 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)
510532
511533Lazarus 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.
512534
513535To this end,
514536
5155371. create a directory **src** below the **components/fpweb directory** (where the package is located)
5165382. copy all files in directory
517539
518-` packages/fcl-web/src/restbridge de`
540+```text
541+ packages/fcl-web/src/restbridge de
542+```
519543
520544
521545to directory
522546
523-` lazarus/components/fpweb/src`
547+```text
548+ lazarus/components/fpweb/src
549+```
524550
5255511. compile the lazsqldbrest.lpk package. It should find the files in the src directory and use them.
526552
527553## Pas2JS Support
528554
529555The SQLDB Rest bridge will be integrated in the compile server that comes with pas2JS: This means that pas2js will come with a toll that
530556
531557- Can recompile your web project on the fly
532558- Can serve files on disc
533559- Can act as a REST server.
534560
535561So no actual server is needed during development.
536562
537563## Usage
538564
539565### In a fcl-web application.
540566
541567The rest bridge was designed to be simple to use.
542568
543569#### Expose a single database, no authentication.
544570
545571Simple 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)
546572
547573```delphi
548574FDisp:=TSQLDBRestDispatcher.Create(Self);
549575FDisp.ExposeDatabase(
550576 'postgres','localhost','expensetracker','me','secret'
551577 ,Nil,
552578 [foFilter,foInInsert,foInUpdate,foOrderByDesc]);
553579FDisp.Active:=True;
554580FDisp.SaveToFile('demo.ini');
555581```
556582
557583This 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'
558584
559585The configuration will be saved in a file called 'demo.ini'.\
560586It can be reused to quickly set up a REST dispatcher.
561587
562588#### Expose single database, HTTP Basic authentication.
563589
564590Similar to the previous example, but with HTTP BASIC authentication for a single user:
565591
566592```delphi
567593FAuth:=TRestBasicAuthenticator.Create(Self);
568594FAuth.DefaultUserName:='me';
569595FAuth.DefaultPassword:='secret';
570596FDisp:=TSQLDBRestDispatcher.Create(Self);
571597FDisp.Authenticator:=Fauth;
572598FDisp.ExposeDatabase(
573599 'postgres','localhost','expensetracker','me','secret'
574600 ,Nil,
575601 [foFilter]);
576602FDisp.Active:=True;
577603```
578604
579605This 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.
580606
581607#### Expose single database, HTTP Basic authentication (2)
582608
583609Smilar to the previous example, but with HTTP BASIC authentication, using the database to authenticate a user:
584610
585611```delphi
586612FAuth:=TRestBasicAuthenticator.Create(Self);
587613FAuth.AuthenticateUserSQL.Text:='select uID from users where (uLogin=:UserName) and (uPassword=:Password)';
588614FDisp:=TSQLDBRestDispatcher.Create(Self);
589615FDisp.Authenticator:=Fauth;
590616FDisp.ExposeDatabase(
591617 'postgres','localhost','expensetracker','me','secret'
592618 ,['projects','expenses'],
593619 []);
594620FDisp.Active:=True;
595621```
596622
597623Here only the 'projects' and 'expenses' tables are exposed, read-only.
598624
599625#### Using a Config file and schema files.
600626
601627Start a dispatcher, loading the file demo.ini. The dioSkipReadSchemas tells it not to load schema files, the schemas will be created from the connections.
602628
603629```delphi
604630FDisp:=TSQLDBRestDispatcher.Create(Self);
605631FDisp.LoadFromFile('demo.ini',[dioSkipReadSchemas]);
606632FDisp.Active:=True;
607633```
608634
609635The .ini file can be created using SaveToFile on a configured dispatcher instance.
610636
611637### In the lazarus IDE.
612638
613639To 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.
614640
615641#### Using a datamodule
616642
617643In this approach, a datamodule is created that is in memory throughout the whole lifetime of the application (fcl-web application)
618644
6196451. Create a HTTP server application or FCGI application. (a CGI will also work but is very inefficient)
6206462. Add a plain datamodule to the application.
6216473. Drop a TSQLDBRestSchema class from the 'FCL-Web' tab of the component palette
6226484. Edit the schema (property resources), or import it from file using the component editor context menu
6236495. Drop a TSQLDBRestDispatcher class from the 'FCL-Web' tab of the component palette
6246506. Edit the connections
6256517. Add an item to the Schemas property and point it to the TSQLDBRestSchema added previously
6266528. For HTTP Basic authentication, add a TRESTBAsicAuthenticator class, and set the TSQLDBRestDispatcher instance's Authentocator property to it.
627653
628654The end result should look more or less like this:
629655
630656![](/wiki-images/2/2a/Restmodule.png)
631657
632658That's it. The project is ready to run.
633659
634660#### Using a SQLDBRestdatamodule
635661
636662This approach is basically the same as the previous one.
637663
6386641. Create a HTTP application
6396652. Under File - New, create a SQLDB Rest Bridge Module.
6406663. Drop a SQLDBRestDispatcher component on the module.
6416674. The Dispatcher property of the module should be set to the SQLDBRestDispatcher component.
6426685. Set up the component as required, as in the previous example.
643669
644670## Examples
645671
646672### FPC
647673
648674- in FPC Packages, the fcl-web/examples/restbridge directory, there is a small example that serves a expenses tracker database.
649675- The directory (delphiclient) below contains a small Delphi project that shows how to connect a TClientDataset to the SQLDB Rest bridge.
650676
651677
652678Design time view:
653679
654680![](/wiki-images/9/9a/Delphirestclientdesign.png)
655681
656682Run time view:
657683
658684![](/wiki-images/7/7b/Delphirestclient.png)
659685
660686### Lazarus
661687
662688There 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.
663689
664690#### Server examples
665691
666692- The demo/restbridge directory of Lazarus/Components contains the same example program, using a datamodule.
667693- The demo/restmodule directory of Lazarus/Components contains the same example program, using a SQLDB Rest Web datamodule.
668694
669695#### TBufDataset client example
670696
671697- 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.
672698
673699
674700![](/wiki-images/2/2a/Sqldbrestbufclientdata.png)
675701
676702
677703![](/wiki-images/2/2c/Sqldbrestbufclientraw.png)
678704
679705it also demonstrates how to use the metadata resource of the server to list the available resources
680706
681707#### TJSONDataset client example
682708
683709- The demo/jsonclient directory contains a demo that is similar to the bufclient demo:
684710
685711
686712it shows how to load data from a SQLDB REST bridge server in a TBaseJSONDataset dataset, using the 'csv' format
687713
688714![](/wiki-images/2/29/Sqldbrestjsonclientdata.png)
689715
690716
691717![](/wiki-images/3/33/Sqldbrestjsonclientraw.png)
692718
693719Like the bufdataset demo, it also demonstrates how to use the metadata resource of the server to list the available resources
694720
695721#### TCSVDataset client example
696722
697723- The demo/csvclient directory contains a demo that is similar to the bufclient demo:
698724
699725
700726it shows how to load data from a SQLDB REST bridge server in a TCSVDataset dataset, using the 'csv' format
701727
702728### Pas2JS
703729
704730- A similar application to the lazarus bufflien/jsonclient programs exists for pas2JS in demo/restbridge/simple
705731
706732
707733![](/wiki-images/c/ca/Sqldbrestbridgepas2js.png)
708734
709735## TODO
710736
711737The following extensions are still planned:
712738
713739- Support for `?q=filterexpression` in URL filters.
714740- Connection management API. (zero-config service)
715741- Use HTTP credentials to connect to the database.
716742- Unknown query params are now ignored. Allow to check for valid query parameters and raise error if unknown query param is encountered.
717743
718744---
719745*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](/wiki-contact).*
720746Category: Databases/ru
721747Category: Russian

Back to history