Sign in Join
Wiki copytemporary

SQLDBRestBridge/ru: what changed

Revision 1 to 2. 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
307307` Function GetDataset(aContext : TBaseRestContext; aFieldList : TRestFieldPairArray; aOrderBy : TRestFieldOrderPairArray; aLimit, aOffset : Int64) : TDataset;`
308308
309309Get the custom dataset for this resource.
310310
311311` function GenerateDefaultSQL(aKind: TSQLKind): UTF8String; virtual;`
312312
313313Get the default SQL for this resource if none was specified.
314314
315315` function GetFieldList(aListKind: TFieldListKind): UTF8String;`
316316
317317Return a list of fields as a string, separated by a correct separator token
318318
319319` function GetFieldArray(aListKind: TFieldListKind): TSQLDBRestFieldArray;`
320320
321321Return a list of fields, similar to GetFieldList, but returns the raw fields.
322322
323323` Function GetResolvedSQl(aKind : TSQLKind; Const AWhere : UTF8String; Const aOrderBy : UTF8String = `*`; aLimit : UTF8String =`*`) : UTF8String;`
324324
325325Return the actual SQL Statement that will be executed, with macros
326326
327327` Procedure PopulateFieldsFromFieldDefs(Defs : TFieldDefs; aIndexFields : TStringArray; aProcessIdentifier : TProcessIdentifier; aMinFieldOpts : TRestFieldOptions);`
328328
329329Populate the fields collection from a TFieldDefs collection.
330330
331331### TSQLDBRestField
332332
333333The TSQLDBREstResource has a collection of fields (TSQLDBRestField) that determine the output fields of the REST resource
334334
335335It has the following properties;
336336
337337- FieldName (UTF8String Read FFieldName Write FFieldName;
338338- PublicName (UTF8String Read GetPublicName Write FPublicName;
339339- GeneratorName (String) name of a generator to privide a unique value.
340340- FieldType (TRestFieldType) Data type of the exposed field.One of (the names speak for themselves)
341341 - rftInteger
342342 - rftLargeInt
343343 - rftFloat
344344 - rftDate
345345 - rftTime
346346 - rftDateTime
347347 - rftString
348348 - rftBoolean
349349 - rftBlob (sent as base64-encoded data)
350350- NativeFieldType (TFieldType) Native database field type of this field.
351351- Options (TRestFieldOptions) options for this field. One of more of:
352352 - foInKey This is a key field.
353353 - foInInsert The field can be inserted (if statement is autogenerated)
354354 - foInUpdate The field can be updated (if statement is autogenerated)
355355 - foRequired A field value is required.
356356 - foFilter Filtering is allowed on this field.
357357 - foOrderBy Ordering is allowed on this field.
358358 - foOrderByDesc Ordering (descendent) is allowed on this field.
359359- Filters (TRestFieldFilters) Allowed filter expressions for this field. One or more of:
360360 - rfEqual
361361 - rfLessThan
362362 - rfGreaterThan
363363 - rfLessThanEqual
364364 - rfGreaterThanEqual
365365 - rfNull
366366- MaxLen (integer) for string fields, the maximum allowed length of the field.
367367
368368### TSQLDBRestBusinessProcessor
369369
370370This 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.
371371
372372The following properties and events are available:
373373
374374- **Schema** : The schema in which the resource resides.
375375- **ResourceName** The resource for which the business rules are valid.
376376- **OnGetDataset** : Event called when you want to create a custom dataset. You must free the dataset yourself.
377377- **OnCheckParams** : Event in which you can verify whether the parameters for insert/update/delete/select queries are OK.
378378- **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.
379379- **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.
380380- **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.
381381
382382All calls get passed a TRestContext instance. This contains 2 properties and a method:
383383
384384`  Function GetVariable(Const aName : UTF8String; aSources : TVariableSources; Out aValue : UTF8String) : Boolean;`
385385
386386Call this to get a HTTP Query variable, header,... The function returns true if the variable was found.
387387
388388`  Property UserID : UTF8String`
389389
390390This will be set when calling.
391391
392392`  Property Data : TObject`
393393
394394You 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.
395395
396396## Special Resources
397397
398398### metaData
399399
400400The */baseURL/metaData* resource lists all the resources defined in the schema, together with the allowed operations.
401401
402402The usual formats and parameters are supported.
403403
404404### metaData/resourceName
405405
406406The */baseURL/metaData/resourceName* resource lists all the fields in the **resourceName** resource, together with the properties.
407407
408408The usual formats and parameters are supported for this resource.
409409
410410### customview
411411
412412The customView resource is special. Its availability must be enabled using the *Dispatcher*'s Options. When *rdoCustomView* is included in the options, the
413413
414414` baseURL/customView`
415415
416416URL becomes available. It allows the client to specify an SQL Select statement using the *SQL* parameter:
417417
418418` baseURL/customView?SQL=select count(*) as thecount from person`
419419
420420(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.
421421
422422The 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.
423423
424424### _connection
425425
426426(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.
427427
428428Because 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.
429429
430430Use 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/
431431
432432## Available Output formats
433433
434434### JSON (the default)
435435
436436- A simple JSON object encapsulating data, metadata and possibly error nodes.
437437- rows are exported as JSON objects, field names are property names of the object.
438438- Name: 'json'
439439- Content-type: 'application/json'
440440- Input and output.
441441- Data by default under 'data'
442442- Metadata by default under 'metaData'
443443- Errors reported under 'error'
444444- Property names are configurable in REST dispatcher.
445445
446446### XML (a custom format)
447447
448448- A simple XML document encapsulating data, metadata and possibly error nodes, under a root element 'datapacket'
449449- rows are exported as XML elements (named 'row') , the contents as text in the element.
450450- Name: 'xml'
451451- Content-type: 'text/xml'
452452- Input and output.
453453- Data by default under 'data'
454454- Metadata by default under 'metadata'
455455- Errors reported under 'error'
456456- Element names are configurable in REST dispatcher.
457457
458458### CSV
459459
460460- Simple comma-separated CSV list.
461461- Name: 'csv'
462462- Content-type: 'text/csv'
463463- Input and output.
464464- Separator: Comma
465465- Quotes when needed.
466466- Metadata means first line contains fieldnames.
467467
468468### CDS
469469
470470- XML package using the XMLFormat used by Delphi `TClientDataset`.
471471- Name: 'cds'
472472- Content-type: 'text/csv'
473473- Input and output.
474474
475475A Delphi demo program is provided.
476476
477477### ADO
478478
479479- XML format as used by ADO recordsets (as used by MS Access)
480480- Name: 'ado'
481481- Input and output.
482482
483483## Ini file Support
484484
485485The following classes can load/save their configuration settings from/to an .ini file
486486
487487- TSQLDBRestDispatcher
488488- TRestBasicAuthenticator
489489- TSQLDBRestConnection
490490- TRestStringsConfig
491491
492492The support for this is implemented in 2 units;
493493
494494- the sqldbauthini unit has a type helper for the TRestBasicAuthenticator class.
495495- The sqldbrestini unit has the type helpers for TSQLDBRestDispatcher and TSQLDBRestConnection and TRestStringsConfig.
496496
497497The helpers implement LoadFromFile/SaveToFile methods, as well as LoadFromIni/SaveToIni methods. There are some options to control the level of depth.
498498
499499The 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.
500500
501501## Lazarus Support
502502
503503Lazarus 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:
504504
505-<figure>
506-<img src="sqldbrestcomponents.png" title="sqldbrestcomponents.png" />
507-<figcaption>sqldbrestcomponents.png</figcaption>
508-</figure>
505+![](/wiki-images/d/d6/Sqldbrestcomponents.png)
509506
510507Additionally it registers some component- and property editors:
511508
512509Further 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)
513510
514511Lazarus 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.
515512
516513To this end,
517514
5185151. create a directory **src** below the **components/fpweb directory** (where the package is located)
5195162. copy all files in directory
520517
521518` packages/fcl-web/src/restbridge de`
522519
523520
524521to directory
525522
526523` lazarus/components/fpweb/src`
527524
5285251. compile the lazsqldbrest.lpk package. It should find the files in the src directory and use them.
529526
530527## Pas2JS Support
531528
532529The SQLDB Rest bridge will be integrated in the compile server that comes with pas2JS: This means that pas2js will come with a toll that
533530
534531- Can recompile your web project on the fly
535532- Can serve files on disc
536533- Can act as a REST server.
537534
538535So no actual server is needed during development.
539536
540537## Usage
541538
542539### In a fcl-web application.
543540
544541The rest bridge was designed to be simple to use.
545542
546543#### Expose a single database, no authentication.
547544
548545Simple 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)
549546
550547```delphi
551548FDisp:=TSQLDBRestDispatcher.Create(Self);
552549FDisp.ExposeDatabase(
553550 'postgres','localhost','expensetracker','me','secret'
554551 ,Nil,
555552 [foFilter,foInInsert,foInUpdate,foOrderByDesc]);
556553FDisp.Active:=True;
557554FDisp.SaveToFile('demo.ini');
558555```
559556
560557This 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'
561558
562559The configuration will be saved in a file called 'demo.ini'.\
563560It can be reused to quickly set up a REST dispatcher.
564561
565562#### Expose single database, HTTP Basic authentication.
566563
567564Similar to the previous example, but with HTTP BASIC authentication for a single user:
568565
569566```delphi
570567FAuth:=TRestBasicAuthenticator.Create(Self);
571568FAuth.DefaultUserName:='me';
572569FAuth.DefaultPassword:='secret';
573570FDisp:=TSQLDBRestDispatcher.Create(Self);
574571FDisp.Authenticator:=Fauth;
575572FDisp.ExposeDatabase(
576573 'postgres','localhost','expensetracker','me','secret'
577574 ,Nil,
578575 [foFilter]);
579576FDisp.Active:=True;
580577```
581578
582579This 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.
583580
584581#### Expose single database, HTTP Basic authentication (2)
585582
586583Smilar to the previous example, but with HTTP BASIC authentication, using the database to authenticate a user:
587584
588585```delphi
589586FAuth:=TRestBasicAuthenticator.Create(Self);
590587FAuth.AuthenticateUserSQL.Text:='select uID from users where (uLogin=:UserName) and (uPassword=:Password)';
591588FDisp:=TSQLDBRestDispatcher.Create(Self);
592589FDisp.Authenticator:=Fauth;
593590FDisp.ExposeDatabase(
594591 'postgres','localhost','expensetracker','me','secret'
595592 ,['projects','expenses'],
596593 []);
597594FDisp.Active:=True;
598595```
599596
600597Here only the 'projects' and 'expenses' tables are exposed, read-only.
601598
602599#### Using a Config file and schema files.
603600
604601Start a dispatcher, loading the file demo.ini. The dioSkipReadSchemas tells it not to load schema files, the schemas will be created from the connections.
605602
606603```delphi
607604FDisp:=TSQLDBRestDispatcher.Create(Self);
608605FDisp.LoadFromFile('demo.ini',[dioSkipReadSchemas]);
609606FDisp.Active:=True;
610607```
611608
612609The .ini file can be created using SaveToFile on a configured dispatcher instance.
613610
614611### In the lazarus IDE.
615612
616613To 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.
617614
618615#### Using a datamodule
619616
620617In this approach, a datamodule is created that is in memory throughout the whole lifetime of the application (fcl-web application)
621618
6226191. Create a HTTP server application or FCGI application. (a CGI will also work but is very inefficient)
6236202. Add a plain datamodule to the application.
6246213. Drop a TSQLDBRestSchema class from the 'FCL-Web' tab of the component palette
6256224. Edit the schema (property resources), or import it from file using the component editor context menu
6266235. Drop a TSQLDBRestDispatcher class from the 'FCL-Web' tab of the component palette
6276246. Edit the connections
6286257. Add an item to the Schemas property and point it to the TSQLDBRestSchema added previously
6296268. For HTTP Basic authentication, add a TRESTBAsicAuthenticator class, and set the TSQLDBRestDispatcher instance's Authentocator property to it.
630627
631628The end result should look more or less like this:
632629
633-<figure>
634-<img src="restmodule.png" title="restmodule.png" />
635-<figcaption>restmodule.png</figcaption>
636-</figure>
630+![](/wiki-images/2/2a/Restmodule.png)
637631
638632That's it. The project is ready to run.
639633
640634#### Using a SQLDBRestdatamodule
641635
642636This approach is basically the same as the previous one.
643637
6446381. Create a HTTP application
6456392. Under File - New, create a SQLDB Rest Bridge Module.
6466403. Drop a SQLDBRestDispatcher component on the module.
6476414. The Dispatcher property of the module should be set to the SQLDBRestDispatcher component.
6486425. Set up the component as required, as in the previous example.
649643
650644## Examples
651645
652646### FPC
653647
654648- in FPC Packages, the fcl-web/examples/restbridge directory, there is a small example that serves a expenses tracker database.
655649- The directory (delphiclient) below contains a small Delphi project that shows how to connect a TClientDataset to the SQLDB Rest bridge.
656650
657651
658652Design time view:
659653
660-<figure>
661-<img src="delphirestclientdesign.png" title="delphirestclientdesign.png" />
662-<figcaption>delphirestclientdesign.png</figcaption>
663-</figure>
654+![](/wiki-images/9/9a/Delphirestclientdesign.png)
664655
665656Run time view:
666657
667-<figure>
668-<img src="delphirestclient.png" title="delphirestclient.png" />
669-<figcaption>delphirestclient.png</figcaption>
670-</figure>
658+![](/wiki-images/7/7b/Delphirestclient.png)
671659
672660### Lazarus
673661
674662There 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.
675663
676664#### Server examples
677665
678666- The demo/restbridge directory of Lazarus/Components contains the same example program, using a datamodule.
679667- The demo/restmodule directory of Lazarus/Components contains the same example program, using a SQLDB Rest Web datamodule.
680668
681669#### TBufDataset client example
682670
683671- 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.
684672
685673
686-<figure>
687-<img src="sqldbrestbufclientdata.png" title="sqldbrestbufclientdata.png" />
688-<figcaption>sqldbrestbufclientdata.png</figcaption>
689-</figure>
674+![](/wiki-images/2/2a/Sqldbrestbufclientdata.png)
690675
691676
692-<figure>
693-<img src="sqldbrestbufclientraw.png" title="sqldbrestbufclientraw.png" />
694-<figcaption>sqldbrestbufclientraw.png</figcaption>
695-</figure>
677+![](/wiki-images/2/2c/Sqldbrestbufclientraw.png)
696678
697679it also demonstrates how to use the metadata resource of the server to list the available resources
698680
699681#### TJSONDataset client example
700682
701683- The demo/jsonclient directory contains a demo that is similar to the bufclient demo:
702684
703685
704686it shows how to load data from a SQLDB REST bridge server in a TBaseJSONDataset dataset, using the 'csv' format
705687
706-<figure>
707-<img src="sqldbrestjsonclientdata.png" title="sqldbrestjsonclientdata.png" />
708-<figcaption>sqldbrestjsonclientdata.png</figcaption>
709-</figure>
688+![](/wiki-images/2/29/Sqldbrestjsonclientdata.png)
710689
711690
712-<figure>
713-<img src="sqldbrestjsonclientraw.png" title="sqldbrestjsonclientraw.png" />
714-<figcaption>sqldbrestjsonclientraw.png</figcaption>
715-</figure>
691+![](/wiki-images/3/33/Sqldbrestjsonclientraw.png)
716692
717693Like the bufdataset demo, it also demonstrates how to use the metadata resource of the server to list the available resources
718694
719695#### TCSVDataset client example
720696
721697- The demo/csvclient directory contains a demo that is similar to the bufclient demo:
722698
723699
724700it shows how to load data from a SQLDB REST bridge server in a TCSVDataset dataset, using the 'csv' format
725701
726702### Pas2JS
727703
728704- A similar application to the lazarus bufflien/jsonclient programs exists for pas2JS in demo/restbridge/simple
729705
730706
731-<figure>
732-<img src="sqldbrestbridgepas2js.png" title="sqldbrestbridgepas2js.png" />
733-<figcaption>sqldbrestbridgepas2js.png</figcaption>
734-</figure>
707+![](/wiki-images/c/ca/Sqldbrestbridgepas2js.png)
735708
736709## TODO
737710
738711The following extensions are still planned:
739712
740713- Support for `?q=filterexpression` in URL filters.
741714- Connection management API. (zero-config service)
742715- Use HTTP credentials to connect to the database.
743716- Unknown query params are now ignored. Allow to check for valid query parameters and raise error if unknown query param is encountered.
744717
745718---
746719*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).*
747720Category: Databases/ru
748721Category: Russian

Back to history