Sign in Join
Wiki copytemporary

SQLDBRestBridge/ru: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: SQLDBRestBridge/ru

OldNewLine
1+## Цель
2+
3+Все больше и больше приложений перемещаются в Интернет: сегодня Pas2JS позволяет программировать паскаль для Интернета.
4+
5+Данные должны храниться на сервере, и REST сегодня является предпочтительной архитектурой для этого. Чаще всего данные попадают в базу данных.
6+
7+Поэтому необходим простой способ сделать данные доступными через службу REST.
8+
9+Модуль `SQLDBRestBridge` предлагает средство для раскрытия любой базы данных, к которой SQLDB может получить доступ, используя REST API.
10+
11+Это не подразумевается как общая структура REST API, для этого существуют другие платформы. Это также не структура RPC.
12+
13+Конструкция такова, что полная база данных может быть представлена с использованием одной строки кода с разумными настройками по умолчанию.
14+
15+### Что компонент делает?
16+
17+По сути, этот компонент можно использовать в приложении FCL-Web для превращения его в REST-сервер:
18+
19+Затем сервер примет обычные команды REST GET/POST/PUT/Delete и автоматически переведет их в соответствующую базу данных CRUD (создание/чтение/обновление/удаление).
20+
21+Его можно использовать просто: одной строки кода достаточно, чтобы таким образом представить полную базу данных.
22+
23+Или это может быть полностью настроено и точно подкручено: схема может быть полностью определена: все операторы SQL могут быть заданы, могут быть определены списки полей, могут быть заданы псевдонимы, могут быть реализованы бизнес-правила.
24+
25+Полученный в результате сервер можно использовать в установке клиента/сервера (например, используя pas2js в качестве клиента) для обслуживания данных без необходимости написания всего необходимого сантехнического кода на REST-сервере.
26+
27+### Чего компонент не делает?
28+
29+- Это технология на стороне сервера.
30+
31+
32+Чтобы использовать данные, обслуживаемые этим компонентом, вам нужно написать клиент.
33+
34+Нет никаких предположений относительно клиента, за исключением того, что он знает, как выполнять HTTP-запросы, и что он понимает один из доступных форматов данных.
35+
36+- Он не предоставляет объекты в качестве ресурсов REST.
37+
38+
39+Используя некоторые приемы, это можно сделать, но это не цель проекта.
40+
41+В конечном итоге все данные попадают в базу данных, и этот компонент использует прямой механизм для достижения этой цели.
42+
43+## Характеристики
44+
45+### На стороне базы данных SQL
46+
47+1. Каждый ресурс REST определяется до 4 операторов SQL, соответствующих 4 операциям CRUD.
48+2. Операторы CRUD могут быть автоматически сгенерированы на лету на основе имени таблицы и определений полей.
49+3. Для каждого поля можно указать псевдоним.
50+4. Доступны следующие типы на стороне клиента, автоматически сопоставленные с собственным типом базы данных:
51+ 1. String
52+ 2. 64-bit integer
53+ 3. 32-bit integer
54+ 4. Boolean
55+ 5. Date, Time, DateTime
56+ 6. Blob (base64-encoded)
57+5. Встроена поддержка последовательностей для генерации идентификаторов.
58+6. Полный контроль над тем, какие операции (GET, POST, PUT, DELETE) разрешены.
59+7. Ресурсы собраны в схему.
60+8. К сервису могут быть прикреплены несколько схем.
61+9. Могут быть заданы несколько баз данных (соединений).
62+10. Схема может быть привязана к одному соединению, или соединения могут совместно использовать схемы (вариант использования: другое соединение для клиента).
63+11. Компоненты бизнес-процессоров могут быть подключены к ресурсу, чтобы упростить реализацию бизнес-логики.
64+12. Выражения SQL могут содержать параметры, значения для параметров будут взяты из URL запроса.
65+13. Поддержка для получения пользовательских наборов данных.
66+14. Поддержка клиентских операторов SQL SELECT (необязательно, по умолчанию отключено)
67+15. Полная поддержка конфигурации через файл `.ini` из коробки.
68+
69+### На стороне HTTP
70+
71+1. Аутентификация обрабатывается с использованием протокола HTTP.
72+2. Базовая аутентификация включена по умолчанию, но полностью подключаема.
73+3. Обычная аутентификация может искать действительных пользователей в базе данных (по умолчанию база данных незащищенная).
74+4. Выходной формат может быть зафиксирован или определен для каждого запроса (`?Fmt=format`). Обнаружение по типу контента также доступно.
75+5. Список полей для включения в вывод можно указать в URL:\
76+ `fl=field1,field2`
77+6. Список полей, исключаемых из вывода, может быть указан в URL:\
78+ `fe=field1,field2`
79+7. Различные форматы вывода доступны из коробки
80+ 1. JSON (по умолчанию)
81+ 2. XML (пользовательский формат)
82+ 3. CSV (для ввода и вывода)
83+ 4. CDS (Формат, используемый Delphi'йским `TClientDataset`)
84+ 5. Запланировано: пакеты данных ADO (как он используется MS Access)
85+8. Используется заводской шаблон, новые форматы могут быть добавлены по желанию.
86+9. Простые схемы URL. Доступны 2 основные схемы
87+ BASEURL/Resource/
88+ BASEURL/Resource/ID
89+
90+ или используя соединение в качестве префикса:
91+
92+ BASEURL/Connection/Resource/
93+ BASEURL/Connection/Resource/ID
94+10. Поддержка самоанализа/обнаружения или метаданных:
95+ BASEURL/metadata/
96+
97+ возвращает список доступных ресурсов и их операций.
98+
99+ BASEURL/metadata/resourcename
100+
101+ возвращает структуру ресурса: поля, типы и т. д.
102+11. параметры `limit` и `offset` для подкачки результатов:
103+ BASEURL/resourcename?limit=10
104+ BASEURL/resourcename?limit=10&Offset=50
105+
106+ Может быть применен максимальный лимит. Когда операторы SQL поддерживают это, `limit` и `offset` переводятся в предложения fetch/offset \[языка\] SQL.
107+12. Порядок сортировки можно указать в URL-адресе запроса, если это позволяет определение ресурса, используя `?Sort=fieldname`. Возможность сортировки может быть указана на основе поля.
108+ BASEURL/resourcename?sort=MyField
109+ BASEURL/resourcename?sort=MyField%20desc
110+13. Фильтрация может быть указана на основе поля в URL-адресе запроса, и операция фильтрации преобразуется в SQL-предложение Where:
111+ BASEURL/resourcename?MyField=10
112+ BASEURL/resourcename?MyField_null=1
113+ BASEURL/resourcename?MyField_null=0
114+ BASEURL/resourcename?MyField_lt=10
115+ BASEURL/resourcename?MyField_lte=10
116+ BASEURL/resourcename?MyField_gt=10
117+ BASEURL/resourcename?MyField_gte=10
118+
119+ переводится в SQL-предложение WHERE:
120+
121+ (MyField=10)
122+ (MyField is null)
123+ (MyField is not null)
124+ (MyField<10)
125+ (MyField_lte<=10)
126+ (MyField>10)
127+ (MyField>=10)
128+
129+ Возможность фильтрации по полю можно указать в схеме для каждого поля.
130+14. Запрос может указать, должны ли метаданные быть включены в ответ:
131+ BASEURL/resourcename?metadata=1
132+15. Запрос может указывать, должен ли результат быть понятным для человека или нет
133+ BASEURL/resourcename?humanreadable=1
134+
135+ Если установлено значение 1, результат запроса будет отформатирован. Не все форматы поддерживают это.
136+
137+## Доступные компоненты
138+
139+### TSQLDBRestSchema
140+
141+Представляет схему REST: список доступных ресурсов с их разрешенными операциями, определения полей, операторы SQL.
142+
143+#### Свойства
144+
145+- **Resources**: коллекция ресурсов. Каждый пункт имеет тип *TSQLDBRestResource*
146+- **ConnectionName**: установите это для имени соединения, если вы хотите, чтобы все ресурсы этой схемы использовали это соединение.
147+
148+#### Методы
149+
150+- **SaveToFile** сохраняет определения ресурса в файл (как JSON)
151+
152+```delphi
153+Procedure SaveToFile(Const aFileName : UTF8String);
154+```
155+
156+- **SaveToFile** сохраняет определения ресурсов в поток (как JSON)
157+
158+```delphi
159+Procedure SaveToStream(Const aStream : TStream);
160+```
161+
162+- **AsJSON** возвращает определения ресурса в виде объекта JSON
163+
164+```delphi
165+function AsJSON(const aPropName: UTF8String=''): TJSONData;
166+```
167+
168+Если указано, **aPropName** - это имя свойства, ниже которого хранятся все определения.
169+
170+- **LoadFromFile** загружает определения ресурсов из файла JSON
171+
172+```delphi
173+Procedure LoadFromFile(Const aFileName : UTF8String);
174+```
175+
176+- **LoadFromStream** загружает определения ресурсов из потока JSON
177+
178+```delphi
179+Procedure LoadFromStream(Const aStream : TStream);
180+```
181+
182+- **FromJSON** загружает определения ресурсов из файла JSON
183+
184+```delphi
185+Procedure FromJSON(aData: TJSONData;const aPropName: UTF8String='');
186+```
187+
188+Если указано, **aPropName** - имя свойства, под которым расположены все определения.
189+
190+- **PopulateResourceFields** создает поля ресурсов на основе имени таблицы
191+
192+```delphi
193+procedure PopulateResourceFields(aConn: TSQLConnection; aRes: TSQLDBRestResource; aMinFieldOpts : TRestFieldOptions = []);
194+```
195+
196+*PopulateResourceFields* заполняет определения полей в *aRes*, проверяя таблицу в соединении с базой данных *aConn*. Каждое созданное поле получает как минимум *aMinFieldOptions* в его свойстве *Options*
197+
198+- **PopulateResources** создает определение ресурса для каждой таблицы в соединении с базой данных
199+
200+```delphi
201+procedure PopulateResources(aConn: TSQLConnection; aTables: array of string; aMinFieldOpts: TRestFieldOptions= []);
202+procedure PopulateResources(aConn : TSQLConnection; aTables : TStrings = Nil; aMinFieldOpts : TRestFieldOptions = []);
203+```
204+
205+- *PopulateResources* извлекает список таблиц из *aConn*, создает определение ресурса для таблицы и вызывает *PopulateResourceFields*, чтобы заполнить ресурс полями. Если указано *aTables*, определения будут создаваться только для таблиц в этом списке.
206+
207+### TSQLDBRestDispatcher
208+
209+#### Свойства
210+
211+- **Active** (Boolean) Регистрирует или отменяет регистрацию HTTP маршрутов
212+- **Connections** (TSQLDBRestConnectionList) Список подключений к базе данных для соединения
213+- **Schemas** (TSQLDBRestSchemaList) Список схем REST для обслуживания
214+- **BasePath** (UTF8String) Базовый URL для REST URL
215+- **DefaultConnection** (UTF8String) Соединение по умолчанию для использования, если ни одно не обнаружено из запроса/схемы
216+- **Strings** (TRestStringsConfig Property) Конфигурации строк ввода/вывода
217+- **OutputOptions** (TRestOutputOptions) Параметры вывода по умолчанию, изменяемые по запросу. Один или несколько из:
218+
219+1. *ooMetadata* отправка метаданных в запросе
220+2. *ooSparse* не отправлять null-значения (если формат позволяет)
221+3. *ooHumanReadable* "человекочитабельная" печать
222+
223+- **InputFormat** (string) - Имя формата ввода, используемого для всех запросов.
224+- **OutputFormat** (string) - Имя формата вывода, используемого для всех запросов.
225+- **DispatchOptions** (TRestDispatcherOptions) - Опции диспетчера. Один или несколько из
226+
227+1. *rdoConnectionInURL* - использовать соединение в качестве элемента пути в URL
228+2. *rdoExposeMetadata* - выставлять URL метаданных
229+3. *rdoCustomView* - разрешить использование пользовательского URL-адреса (выбирается SQL, указанный в запросе)
230+4. *rdoHandleCORS* - обрабатывать предпосылаемый запрос CORS
231+5. *rdoAccessCheckNeedsDB* - эта \[опция\] контролирует, когда проверка доступа выполняется для ресурсов: до или после установления соединения с базой данных. Если вам необходимо выполнить дополнительные запросы к базе данных, чтобы решить, предоставляется ли доступ (например, проверка ACL в БД), этот параметр должен быть включен
232+
233+- **Authenticator** (TRestAuthenticator) - аутентификатор для запросов. Если установлено значение *OnBasicAuthentication*, его можно оставить пустым.
234+- **EnforceLimit** (Integer) - если больше нуля, установить ограничение на выходные результаты.
235+- **CORSAllowedOrigins** (String) - Разделенный запятыми список доменов, которым разрешено использовать эту службу REST. Если пусто, в предварительном запросе будет возвращено *.
236+
237+#### Методы
238+
239+- **ExposeDatabase** выставляет базу данных в качестве службы REST. Это создаст определение соединения с предоставленными параметрами и вызовет **ExposeConnection** с этим определением.
240+ ```delphi
241+ Function ExposeDatabase(Const aType,aHostName,aDatabaseName,aUserName,aPassword : String; aTables : Array of String; aMinFieldOpt)
242+ Function ExposeDatabase(Const aType,aHostName,aDatabaseName,aUserName,aPassword : String; aTables : TStrings = nil; aMinFieldOpt)
243+ ```
244+
245+ 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**
246+- **ExposeConnection** exposes a database (represented by *aConnection*) as a REST service. This will create a schema with a resource definition.
247+ ```delphi
248+ Function ExposeConnection(Const aConnection : TSQLDBRestConnection; aTables : TStrings = nil; aMinFieldOpts : TRestFieldOptions
249+ ```
250+
251+ The Tables and aMinFieldOpt arguments are the same as in the *PopulateResources* call of **TSQLDBRestSchema**
252+
253+### TRestBasicAuthenticator
254+
255+This class implements HTTP Basic authentication for the SQLDB REST Dispatcher
256+
257+- 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.
258+- 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.
259+- DefaultUserName (UTF8String) a valid username, not in the database.
260+- DefaultPassword (UTF8String) password of a default user.
261+- DefaultUserID (UTF8String) the user ID reported if the default user is authenticated.
262+- AuthenticationRealm : (UTF8String) Real sent in the **WWW-Authenticate** challenge to the client.
263+- OnBasicAuthentication (event) triggered when basic authentication is requested. Here you can enter custom code to validate the user.
264+
265+### TSQLDBRestModule
266+
267+- 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.
268+
269+### TSQLDBRestResource
270+
271+This is a collection item, found in the 'Resources' property of the **TSQLDBRestSchema**. It represents a single REST resource.
272+
273+#### properties
274+
275+It has the following properties:
276+
277+- **Fields** (TSQLDBRestFieldList) A list of fields that will be included in the output, or can be supplied in the input.
278+- **Enabled** (Boolean) Is this resource enabled ?
279+- **InMetadata** (Boolean) Should this resource be shown in the metadata list ?
280+- **ConnectionName** (UTF8String) Connection name to use for this resource.
281+- **TableName** (UTF8String) Database table name. This must only be specified if the SQL is auto generated.
282+- **ResourceName** (UTF8String) Name of this resource as exposed to the outside world.
283+- **AllowedOperations** (TRestOperations) The operations allowed on this resources (Get/Put/Post/Delete/Options/Head)
284+- **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.
285+- **SQLInsert** (TStrings) SQL INSERT statement for a POST request. Left empty, it is autogenerated based on the table name.
286+- **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.
287+- **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.
288+- *'SQL* an array of SQL statements, based on the previous ones.
289+- **BusinessProcessor** (TSQLDBRestCustomBusinessProcessor) at runtime this contains the business processor for this resource (if any)
290+
291+#### Events
292+
293+The following events are available:
294+
295+- **OnResourceAllowed** (TSQLDBRestAllowResourceEvent) Called to check whether the user is allowed to access this resource.
296+- **OnAllowedOperations** (TSQLDBRestAllowedOperationsEvent) Called to allow to fine-tune the allowed operations for the user.
297+- **OnGetDataset** (TSQLDBRestGetDatasetEvent) You can return a custom dataset for GET operations.
298+- **OnCheckParams** (TSQLDBRestCheckParamsEvent) You can check the INSERT/UPDATE/DELETE SQL Statement parameters in this request/
299+- **OnAllowRecord** (TSQLDBRestAllowRecordEvent) Called for each record, you can ddecide whether the record should be included in the output.
300+
301+Note: when set, the corresponding event in the business processor is not triggered.
302+
303+#### Methods
304+
305+The following methods exist:
306+
307+` Function GetDataset(aContext : TBaseRestContext; aFieldList : TRestFieldPairArray; aOrderBy : TRestFieldOrderPairArray; aLimit, aOffset : Int64) : TDataset;`
308+
309+Get the custom dataset for this resource.
310+
311+` function GenerateDefaultSQL(aKind: TSQLKind): UTF8String; virtual;`
312+
313+Get the default SQL for this resource if none was specified.
314+
315+` function GetFieldList(aListKind: TFieldListKind): UTF8String;`
316+
317+Return a list of fields as a string, separated by a correct separator token
318+
319+` function GetFieldArray(aListKind: TFieldListKind): TSQLDBRestFieldArray;`
320+
321+Return a list of fields, similar to GetFieldList, but returns the raw fields.
322+
323+` Function GetResolvedSQl(aKind : TSQLKind; Const AWhere : UTF8String; Const aOrderBy : UTF8String = `*`; aLimit : UTF8String =`*`) : UTF8String;`
324+
325+Return the actual SQL Statement that will be executed, with macros
326+
327+` Procedure PopulateFieldsFromFieldDefs(Defs : TFieldDefs; aIndexFields : TStringArray; aProcessIdentifier : TProcessIdentifier; aMinFieldOpts : TRestFieldOptions);`
328+
329+Populate the fields collection from a TFieldDefs collection.
330+
331+### TSQLDBRestField
332+
333+The TSQLDBREstResource has a collection of fields (TSQLDBRestField) that determine the output fields of the REST resource
334+
335+It has the following properties;
336+
337+- FieldName (UTF8String Read FFieldName Write FFieldName;
338+- PublicName (UTF8String Read GetPublicName Write FPublicName;
339+- GeneratorName (String) name of a generator to privide a unique value.
340+- FieldType (TRestFieldType) Data type of the exposed field.One of (the names speak for themselves)
341+ - rftInteger
342+ - rftLargeInt
343+ - rftFloat
344+ - rftDate
345+ - rftTime
346+ - rftDateTime
347+ - rftString
348+ - rftBoolean
349+ - rftBlob (sent as base64-encoded data)
350+- NativeFieldType (TFieldType) Native database field type of this field.
351+- Options (TRestFieldOptions) options for this field. One of more of:
352+ - foInKey This is a key field.
353+ - foInInsert The field can be inserted (if statement is autogenerated)
354+ - foInUpdate The field can be updated (if statement is autogenerated)
355+ - foRequired A field value is required.
356+ - foFilter Filtering is allowed on this field.
357+ - foOrderBy Ordering is allowed on this field.
358+ - foOrderByDesc Ordering (descendent) is allowed on this field.
359+- Filters (TRestFieldFilters) Allowed filter expressions for this field. One or more of:
360+ - rfEqual
361+ - rfLessThan
362+ - rfGreaterThan
363+ - rfLessThanEqual
364+ - rfGreaterThanEqual
365+ - rfNull
366+- MaxLen (integer) for string fields, the maximum allowed length of the field.
367+
368+### TSQLDBRestBusinessProcessor
369+
370+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.
371+
372+The following properties and events are available:
373+
374+- **Schema** : The schema in which the resource resides.
375+- **ResourceName** The resource for which the business rules are valid.
376+- **OnGetDataset** : Event called when you want to create a custom dataset. You must free the dataset yourself.
377+- **OnCheckParams** : Event in which you can verify whether the parameters for insert/update/delete/select queries are OK.
378+- **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.
379+- **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.
380+- **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.
381+
382+All calls get passed a TRestContext instance. This contains 2 properties and a method:
383+
384+`  Function GetVariable(Const aName : UTF8String; aSources : TVariableSources; Out aValue : UTF8String) : Boolean;`
385+
386+Call this to get a HTTP Query variable, header,... The function returns true if the variable was found.
387+
388+`  Property UserID : UTF8String`
389+
390+This will be set when calling.
391+
392+`  Property Data : TObject`
393+
394+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.
395+
396+## Special Resources
397+
398+### metaData
399+
400+The */baseURL/metaData* resource lists all the resources defined in the schema, together with the allowed operations.
401+
402+The usual formats and parameters are supported.
403+
404+### metaData/resourceName
405+
406+The */baseURL/metaData/resourceName* resource lists all the fields in the **resourceName** resource, together with the properties.
407+
408+The usual formats and parameters are supported for this resource.
409+
410+### customview
411+
412+The customView resource is special. Its availability must be enabled using the *Dispatcher*'s Options. When *rdoCustomView* is included in the options, the
413+
414+` baseURL/customView`
415+
416+URL becomes available. It allows the client to specify an SQL Select statement using the *SQL* parameter:
417+
418+` baseURL/customView?SQL=select count(*) as thecount from person`
419+
420+(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.
421+
422+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.
423+
424+### _connection
425+
426+(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.
427+
428+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.
429+
430+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/
431+
432+## Available Output formats
433+
434+### JSON (the default)
435+
436+- A simple JSON object encapsulating data, metadata and possibly error nodes.
437+- rows are exported as JSON objects, field names are property names of the object.
438+- Name: 'json'
439+- Content-type: 'application/json'
440+- Input and output.
441+- Data by default under 'data'
442+- Metadata by default under 'metaData'
443+- Errors reported under 'error'
444+- Property names are configurable in REST dispatcher.
445+
446+### XML (a custom format)
447+
448+- A simple XML document encapsulating data, metadata and possibly error nodes, under a root element 'datapacket'
449+- rows are exported as XML elements (named 'row') , the contents as text in the element.
450+- Name: 'xml'
451+- Content-type: 'text/xml'
452+- Input and output.
453+- Data by default under 'data'
454+- Metadata by default under 'metadata'
455+- Errors reported under 'error'
456+- Element names are configurable in REST dispatcher.
457+
458+### CSV
459+
460+- Simple comma-separated CSV list.
461+- Name: 'csv'
462+- Content-type: 'text/csv'
463+- Input and output.
464+- Separator: Comma
465+- Quotes when needed.
466+- Metadata means first line contains fieldnames.
467+
468+### CDS
469+
470+- XML package using the XMLFormat used by Delphi `TClientDataset`.
471+- Name: 'cds'
472+- Content-type: 'text/csv'
473+- Input and output.
474+
475+A Delphi demo program is provided.
476+
477+### ADO
478+
479+- XML format as used by ADO recordsets (as used by MS Access)
480+- Name: 'ado'
481+- Input and output.
482+
483+## Ini file Support
484+
485+The following classes can load/save their configuration settings from/to an .ini file
486+
487+- TSQLDBRestDispatcher
488+- TRestBasicAuthenticator
489+- TSQLDBRestConnection
490+- TRestStringsConfig
491+
492+The support for this is implemented in 2 units;
493+
494+- the sqldbauthini unit has a type helper for the TRestBasicAuthenticator class.
495+- The sqldbrestini unit has the type helpers for TSQLDBRestDispatcher and TSQLDBRestConnection and TRestStringsConfig.
496+
497+The helpers implement LoadFromFile/SaveToFile methods, as well as LoadFromIni/SaveToIni methods. There are some options to control the level of depth.
498+
499+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.
500+
501+## Lazarus Support
502+
503+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:
504+
505+<figure>
506+<img src="sqldbrestcomponents.png" title="sqldbrestcomponents.png" />
507+<figcaption>sqldbrestcomponents.png</figcaption>
508+</figure>
509+
510+Additionally it registers some component- and property editors:
511+
512+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)
513+
514+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.
515+
516+To this end,
517+
518+1. create a directory **src** below the **components/fpweb directory** (where the package is located)
519+2. copy all files in directory
520+
521+` packages/fcl-web/src/restbridge de`
522+
523+
524+to directory
525+
526+` lazarus/components/fpweb/src`
527+
528+1. compile the lazsqldbrest.lpk package. It should find the files in the src directory and use them.
529+
530+## Pas2JS Support
531+
532+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
533+
534+- Can recompile your web project on the fly
535+- Can serve files on disc
536+- Can act as a REST server.
537+
538+So no actual server is needed during development.
539+
540+## Usage
541+
542+### In a fcl-web application.
543+
544+The rest bridge was designed to be simple to use.
545+
546+#### Expose a single database, no authentication.
547+
548+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)
549+
550+```delphi
551+FDisp:=TSQLDBRestDispatcher.Create(Self);
552+FDisp.ExposeDatabase(
553+ 'postgres','localhost','expensetracker','me','secret'
554+ ,Nil,
555+ [foFilter,foInInsert,foInUpdate,foOrderByDesc]);
556+FDisp.Active:=True;
557+FDisp.SaveToFile('demo.ini');
558+```
559+
560+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'
561+
562+The configuration will be saved in a file called 'demo.ini'.\
563+It can be reused to quickly set up a REST dispatcher.
564+
565+#### Expose single database, HTTP Basic authentication.
566+
567+Similar to the previous example, but with HTTP BASIC authentication for a single user:
568+
569+```delphi
570+FAuth:=TRestBasicAuthenticator.Create(Self);
571+FAuth.DefaultUserName:='me';
572+FAuth.DefaultPassword:='secret';
573+FDisp:=TSQLDBRestDispatcher.Create(Self);
574+FDisp.Authenticator:=Fauth;
575+FDisp.ExposeDatabase(
576+ 'postgres','localhost','expensetracker','me','secret'
577+ ,Nil,
578+ [foFilter]);
579+FDisp.Active:=True;
580+```
581+
582+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.
583+
584+#### Expose single database, HTTP Basic authentication (2)
585+
586+Smilar to the previous example, but with HTTP BASIC authentication, using the database to authenticate a user:
587+
588+```delphi
589+FAuth:=TRestBasicAuthenticator.Create(Self);
590+FAuth.AuthenticateUserSQL.Text:='select uID from users where (uLogin=:UserName) and (uPassword=:Password)';
591+FDisp:=TSQLDBRestDispatcher.Create(Self);
592+FDisp.Authenticator:=Fauth;
593+FDisp.ExposeDatabase(
594+ 'postgres','localhost','expensetracker','me','secret'
595+ ,['projects','expenses'],
596+ []);
597+FDisp.Active:=True;
598+```
599+
600+Here only the 'projects' and 'expenses' tables are exposed, read-only.
601+
602+#### Using a Config file and schema files.
603+
604+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.
605+
606+```delphi
607+FDisp:=TSQLDBRestDispatcher.Create(Self);
608+FDisp.LoadFromFile('demo.ini',[dioSkipReadSchemas]);
609+FDisp.Active:=True;
610+```
611+
612+The .ini file can be created using SaveToFile on a configured dispatcher instance.
613+
614+### In the lazarus IDE.
615+
616+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.
617+
618+#### Using a datamodule
619+
620+In this approach, a datamodule is created that is in memory throughout the whole lifetime of the application (fcl-web application)
621+
622+1. Create a HTTP server application or FCGI application. (a CGI will also work but is very inefficient)
623+2. Add a plain datamodule to the application.
624+3. Drop a TSQLDBRestSchema class from the 'FCL-Web' tab of the component palette
625+4. Edit the schema (property resources), or import it from file using the component editor context menu
626+5. Drop a TSQLDBRestDispatcher class from the 'FCL-Web' tab of the component palette
627+6. Edit the connections
628+7. Add an item to the Schemas property and point it to the TSQLDBRestSchema added previously
629+8. For HTTP Basic authentication, add a TRESTBAsicAuthenticator class, and set the TSQLDBRestDispatcher instance's Authentocator property to it.
630+
631+The end result should look more or less like this:
632+
633+<figure>
634+<img src="restmodule.png" title="restmodule.png" />
635+<figcaption>restmodule.png</figcaption>
636+</figure>
637+
638+That's it. The project is ready to run.
639+
640+#### Using a SQLDBRestdatamodule
641+
642+This approach is basically the same as the previous one.
643+
644+1. Create a HTTP application
645+2. Under File - New, create a SQLDB Rest Bridge Module.
646+3. Drop a SQLDBRestDispatcher component on the module.
647+4. The Dispatcher property of the module should be set to the SQLDBRestDispatcher component.
648+5. Set up the component as required, as in the previous example.
649+
650+## Examples
651+
652+### FPC
653+
654+- in FPC Packages, the fcl-web/examples/restbridge directory, there is a small example that serves a expenses tracker database.
655+- The directory (delphiclient) below contains a small Delphi project that shows how to connect a TClientDataset to the SQLDB Rest bridge.
656+
657+
658+Design time view:
659+
660+<figure>
661+<img src="delphirestclientdesign.png" title="delphirestclientdesign.png" />
662+<figcaption>delphirestclientdesign.png</figcaption>
663+</figure>
664+
665+Run time view:
666+
667+<figure>
668+<img src="delphirestclient.png" title="delphirestclient.png" />
669+<figcaption>delphirestclient.png</figcaption>
670+</figure>
671+
672+### Lazarus
673+
674+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.
675+
676+#### Server examples
677+
678+- The demo/restbridge directory of Lazarus/Components contains the same example program, using a datamodule.
679+- The demo/restmodule directory of Lazarus/Components contains the same example program, using a SQLDB Rest Web datamodule.
680+
681+#### TBufDataset client example
682+
683+- 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.
684+
685+
686+<figure>
687+<img src="sqldbrestbufclientdata.png" title="sqldbrestbufclientdata.png" />
688+<figcaption>sqldbrestbufclientdata.png</figcaption>
689+</figure>
690+
691+
692+<figure>
693+<img src="sqldbrestbufclientraw.png" title="sqldbrestbufclientraw.png" />
694+<figcaption>sqldbrestbufclientraw.png</figcaption>
695+</figure>
696+
697+it also demonstrates how to use the metadata resource of the server to list the available resources
698+
699+#### TJSONDataset client example
700+
701+- The demo/jsonclient directory contains a demo that is similar to the bufclient demo:
702+
703+
704+it shows how to load data from a SQLDB REST bridge server in a TBaseJSONDataset dataset, using the 'csv' format
705+
706+<figure>
707+<img src="sqldbrestjsonclientdata.png" title="sqldbrestjsonclientdata.png" />
708+<figcaption>sqldbrestjsonclientdata.png</figcaption>
709+</figure>
710+
711+
712+<figure>
713+<img src="sqldbrestjsonclientraw.png" title="sqldbrestjsonclientraw.png" />
714+<figcaption>sqldbrestjsonclientraw.png</figcaption>
715+</figure>
716+
717+Like the bufdataset demo, it also demonstrates how to use the metadata resource of the server to list the available resources
718+
719+#### TCSVDataset client example
720+
721+- The demo/csvclient directory contains a demo that is similar to the bufclient demo:
722+
723+
724+it shows how to load data from a SQLDB REST bridge server in a TCSVDataset dataset, using the 'csv' format
725+
726+### Pas2JS
727+
728+- A similar application to the lazarus bufflien/jsonclient programs exists for pas2JS in demo/restbridge/simple
729+
730+
731+<figure>
732+<img src="sqldbrestbridgepas2js.png" title="sqldbrestbridgepas2js.png" />
733+<figcaption>sqldbrestbridgepas2js.png</figcaption>
734+</figure>
735+
736+## TODO
737+
738+The following extensions are still planned:
739+
740+- Support for `?q=filterexpression` in URL filters.
741+- Connection management API. (zero-config service)
742+- Use HTTP credentials to connect to the database.
743+- Unknown query params are now ignored. Allow to check for valid query parameters and raise error if unknown query param is encountered.
744+
745+---
746+*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).*
747+Category: Databases/ru
748+Category: Russian

Back to history