Sign in Join
Wiki copytemporary

SQLDBRestBridge: what changed

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

OldNewLine
11## Purpose
22
33More and more applications move to Web: today Pas2JS allows to program pascal for the web.
44
55Data needs to be stored on a server, and REST is the architecture of choice these days for doing so. Most often, the data ends up in a database.
66
77So, an easy way to make data available through a REST service is needed.
88
99The `SQLDBRestBridge` unit in *fpc/packages/fcl-web/src/restbridge/sqldbrestbridge.pp* offers a means to expose any database that can be accessed by SQLDB using a REST API.
1010
1111It is not meant as a general REST API framework, for this other frameworks exist. It is also not a RPC framework.
1212
1313The design is such that a complete database can be exposed using a single line of code, with reasonable default settings.
1414
1515### What does it do ?
1616
1717Basically, `SQLDBRestBridge` can be used in a FCL-Web application to turn it into a REST server:
1818
1919The server will then accept the usual REST GET/POST/PUT/Delete commands and automatically translate these to the appropriate database CRUD (Create/Read/Update/Delete) statements.
2020
2121It can be used simply: one line of code is enough to expose a complete database in this way.
2222
2323Or it can be completely customized and fine tuned: The schema can be completely specified: all SQL statements can be specified, field lists can be defined, aliases can be given, business rules can be implemented.
2424
2525The resulting server can be used in a client/server setup (using pas2js as a client, for example) to serve data without needing to writing all the plumbing code needed in a REST server.
2626
2727### What it does not do ?
2828
2929- This is a server-side technology.
3030
3131
3232To consume the data served by this component, you need to write a client.
3333
3434No assumptions are made about the client, except that it knows how to execute HTTP requests, and that it understands one of the available data formats.
3535
3636- This does not expose objects as REST resources.
3737
3838
3939Using some tricks, this could be done, but this is not a design goal.
4040
4141Eventually, all data ends up in a database, and this component uses a direct mechanism to achieve that.
4242
4343## Features
4444
4545### SQL Database side.
4646
47471. Every REST resource is defined by up to 4 SQL statements, corresponding to the 4 CRUD operations.
48482. The CRUD Statements can be auto generated on the fly, based on a table name and field definitions.
49493. For every field, an alias can be provided.
50504. The following client-side types are available, automatically mapped from the native database type:
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. Support for a sequence to generate IDs is built-in.
58586. Full control over which operations (GET,POST,PUT,DELETE) are allowed.
59597. Resources are collected in a schema.
60608. Multiple schemas can be attached to the service.
61619. Multiple databases (connections) can be defined.
626210. A schema can be tied to a single connection, or connections can share a schemas (use case: a different connection per client).
636311. Business processor components can be hooked to a resource, to make it easier to implement business logic.
646412. SQL Statements can contain parameters, values for the parameters will be picked up from the request URL.
656513. Support to get custom datasets.
666614. Support for client-side provided SQL SELECT statements (optional, disabled by default)
676715. Full support for configuration through an `.ini` file out of the box.
6868
6969### HTTP side
7070
71711. Authentication is handled using the HTTP protocol.
72722. Basic authentication is included by default, but is completely pluggable.
73733. Basic authentication can look up valid users in a database (by default the database being exposed)
74744. Output format can be fixed or detected per request (`?fmt=format`). Detection based on content-type is also available.
75755. list of fields to include in output can be specified in the URL:\
7676 `fl=field1,field2`
77776. Field list of fields to exclude from output can be specified in the URL:\
7878 `fe=field1,field2`
79797. Various output formats are available out of the box
8080 1. JSON (the default)
8181 2. XML (a custom format)
8282 3. CSV (for in and output)
8383 4. CDS (Format used by Delphi `TClientDataset`)
8484 5. Planned: ADO data packets (as used by MS Access)
85858. A factory pattern is used, new formats can be added at will.
86869. Simple URL schemes. 2 basic schemes are available
8787 BASEURL/Resource/
8888 BASEURL/Resource/ID
8989
9090 or using the connection as prefix:
9191
9292 BASEURL/Connection/Resource/
9393 BASEURL/Connection/Resource/ID
949410. Support for introspection/discovery or metadata:
9595 BASEURL/metadata/
9696
9797 returns the list of available resources and their operation.
9898
9999 BASEURL/metadata/resourcename
100100
101101 returns the structure of the resource: fields, types, etc.
10210211. `limit` and `offset` parameters for paging of results:
103103 BASEURL/resourcename?limit=10
104104 BASEURL/resourcename?limit=10&Offset=50
105105
106106 A maximum limit can be enforced. When the SQL statements support it, the limit and offset are translated to SQL fetch/offset clauses.
10710712. Sort order can be specified in the request URL, if the resource definition allows it, using `?sort=fieldname`. The ability to sort can be specified on a field basis.
108108 BASEURL/resourcename?sort=MyField
109109 BASEURL/resourcename?sort=MyField%20desc
110110
111111 Multiple sort fields can be specified, separated by a comma.
11211213. Filtering can be specified on a field basis in the request URL, and the filter operation is translated to SQL Where:
113113 BASEURL/resourcename?MyField=10
114114 BASEURL/resourcename?MyField_null=1
115115 BASEURL/resourcename?MyField_null=0
116116 BASEURL/resourcename?MyField_lt=10
117117 BASEURL/resourcename?MyField_lte=10
118118 BASEURL/resourcename?MyField_gt=10
119119 BASEURL/resourcename?MyField_gte=10
120120
121121 is translated to a SQL where clause:
122122
123123 (MyField=10)
124124 (MyField is null)
125125 (MyField is not null)
126126 (MyField<10)
127127 (MyField_lte<=10)
128128 (MyField>10)
129129 (MyField>=10)
130130
131131 The ability to filter on a field can be specified in the schema for each field.
13213214. The request can specify whether metadata should be included in the response:
133133 BASEURL/resourcename?metadata=1
13413415. The request can specify whether the result should be human-readable or not
135135 BASEURL/resourcename?humanreadable=1
136136
137137 If set to 1, the request result will be formatted. Not all formats support this.
138138
139139## Available Components
140140
141141### TSQLDBRestSchema
142142
143143Unit: *fpc/packages/fcl-web/src/restbridge/sqldbrestschema.pp*
144144
145145Represents a REST schema : a list of available resources, with their allowed operations, fields definitions, SQL statements. A schema can be designed visually using a [[SQLDBRestSchemaEditor]] in a separate application or in the lazarus IDE.
146146
147147#### Properties
148148
149149- **Resources** A collection of resources. Each item is of type *TSQLDBRestResource*
150150- **ConnectionName** Set this to a connection name if you want all resources of this schema to use this connection.
151151
152152#### Methods
153153
154154- **SaveToFile** save the resource definitions to file (as JSON)
155155
156156```delphi
157157Procedure SaveToFile(Const aFileName : UTF8String);
158158```
159159
160160- **SaveToStream** save the resource definitions to stream (as JSON).
161161
162162```delphi
163163Procedure SaveToStream(Const aStream : TStream);
164164```
165165
166166- **AsJSON** return the resource definitions as a JSON object.
167167
168168```delphi
169169function AsJSON(const aPropName: UTF8String=''): TJSONData;
170170```
171171
172172If specified, **aPropName** is the name of the property below which all definitions are stored.
173173
174174- **LoadFromFile** Load the resource definitions from a JSON file.
175175
176176```delphi
177177Procedure LoadFromFile(Const aFileName : UTF8String);
178178```
179179
180180- **LoadFromStream** Load the resource definitions from a JSON file.
181181
182182```delphi
183183Procedure LoadFromStream(Const aStream : TStream);
184184```
185185
186186- **FromJSON** Load the resource definitions from a JSON file.
187187
188188```delphi
189189Procedure FromJSON(aData: TJSONData;const aPropName: UTF8String='');
190190```
191191
192192If specified, **aPropName** is the name of the property below which all definitions are located.
193193
194194- **PopulateResourceFields** create resource fields based on table name.
195195
196196```delphi
197197procedure PopulateResourceFields(aConn: TSQLConnection; aRes: TSQLDBRestResource; aMinFieldOpts : TRestFieldOptions = []);
198198```
199199
200200*PopulateResourceFields* populates the field definitions in *aRes* by checking the table in database connection *aConn*. Every created field gets at least *aMinFieldOptions* in its *Options* property.
201201
202202- **PopulateResources** creates a resource definition for each table in a database connection.
203203
204204```delphi
205205procedure PopulateResources(aConn: TSQLConnection; aTables: array of string; aMinFieldOpts: TRestFieldOptions= []);
206206Procedure PopulateResources(aConn : TSQLConnection; aTables : TStrings = Nil; aMinFieldOpts : TRestFieldOptions = []);
207207```
208208
209209- *PopulateResources* retrieves the list of tables from *aConn*, creates a resource definition for the table and calls *PopulateResourceFields* to fill the resource with fields. If *aTables* is specified, definitions will only be created for the tables in that list.
210210
211211### TSQLDBRestDispatcher
212212
213213Unit: *fpc/packages/fcl-web/src/restbridge/sqldbrestbridge.pp*
214214
215215#### Properties
216216
217217- **Active** (Boolean) Register or unregister HTTP routes.
218218- **Connections** (TSQLDBRestConnectionList) List of database connections to connect to.
219219- **Schemas** (TSQLDBRestSchemaList) List of REST schemas to serve
220220- **BasePath** (UTF8String) Base URL for REST URLS.
221221- **DefaultConnection** (UTF8String) Default connection to use if none is detected from request/schema
222222- **Strings** (TRestStringsConfig Property) Input/Output strings configurations
223223- **OutputOptions** (TRestOutputOptions) default Output options, modifiable by query. One or more of
224224
2252251. *ooMetadata* Send metadata in request
2262262. *ooSparse* Do not send null values (if format allows it)
2272273. *ooHumanReadable* Pretty-print output.
228228
229229- **InputFormat** (string) Name of Input format to use for all requests.
230230- **OutputFormat** (string) Name of Output format to use for all requests.
231231- **DispatchOptions** (TRestDispatcherOptions) Dispatcher options. One or more of
232232
2332331. *rdoConnectionInURL* Use the connection as a path element in the URL.
2342342. *rdoExposeMetadata* Expose the metadata URL.
2352353. *rdoConnectionResource* Expose the connection resource, allowing to manage connections through the REST protocol.
2362364. *rdoCustomView* allow the use of a customview URL (Select SQL specified in request)
2372375. *rdoEmptyCorsDomainToOrigin* if the CORDAllowedOrigins is empty, then the request server will be echoed to the client.
2382386. *rdoHandleCORS* Handle CORS preflight request.
2392397. *rdoAccessCheckNeedsDB* This controls when the access check is done for resources: before or after a connection with the database is made. If you need to make additional queries on a database to decide whether access is granted (such as checking ACLs in the Db) then this option should be enabled.
240240
241241- **AdminUserIDs** A list of user IDs (one per line) which are allowed to use the connection resource. If empty, all users can use it.
242242- **LogOptions** Logging options. Logging happens through the OnLog event handler. This property controls which events are logged. The following values can be specified:
243243
2442441. *rloUser* Include username in log messages, when available
2452452. *rtloHTTP* Log HTTP request (remote, URL)
2462463. *rloResource* Log resource requests (operation, resource)
2472474. *rloConnection* Log database connections (connect to database)
2482485. *rloAuthentication* Log authentication attempt
2492496. *rloSQL* Log SQL statements. (not on user-supplied connection)
2502507. *rloResultStatus* Log result status.
251251
252252- **LogSQLOptions** SQL Logging options. if rloSQL is specified, this option controls which SQLDB events are logged for new connections.
253253- **Authenticator** (TRestAuthenticator) Authenticator for requests. If *OnBasicAuthentication* is set, this can be left empty.
254254- **EnforceLimit** (Integer) If larger than zero, Enforce a limit on output results.
255255- **CORSAllowedOrigins** (String) Comma separated list of Domains that are allowed to use this REST service. If empty, * will be returned in preflight request.
256256- **CORSMaxAge** (Integer) Value for HTTP *Access-Control-Max-Age* header. If zero, the header is not sent.
257257- **CORSAllowCredentials** (Boolean) value for HTTP header *Access-Control-Allow-Credentials*. Set to false not to send the header
258258
259259#### Methods
260260
261261- **ExposeDatabase** exposes a database as a REST service. This will creates a connection definition with the provided parameters and calls **ExposeConnection** with this definition.
262262 ```delphi
263263 Function ExposeDatabase(Const aType,aHostName,aDatabaseName,aUserName,aPassword : String; aTables : Array of String; aMinFieldOp
264264 Function ExposeDatabase(Const aType,aHostName,aDatabaseName,aUserName,aPassword : String; aTables : TStrings = nil; aMinFieldOpt
265265 ```
266266
267267 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**
268268- **ExposeConnection** exposes a database (represented by *aConnection*) as a REST service. This will create a schema with a resource definition.
269269 ```delphi
270270 Function ExposeConnection(Const aConnection : TSQLDBRestConnection; aTables : TStrings = nil; aMinFieldOpts : TRestFieldOptions
271271 ```
272272
273273 The Tables and aMinFieldOpt arguments are the same as in the *PopulateResources* call of **TSQLDBRestSchema**
274274
275275### TRestBasicAuthenticator
276276
277277Unit: *fpc/packages/fcl-web/src/restbridge/sqldbrestauth.pp*
278278
279279This class implements HTTP Basic authentication for the SQLDB REST Dispatcher
280280
281281- 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.
282282- 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.
283283- DefaultUserName (UTF8String) a valid username, not in the database.
284284- DefaultPassword (UTF8String) password of a default user.
285285- DefaultUserID (UTF8String) the user ID reported if the default user is authenticated.
286286- AuthenticationRealm : (UTF8String) Real sent in the **WWW-Authenticate** challenge to the client.
287287- OnBasicAuthentication (event) triggered when basic authentication is requested. Here you can enter custom code to validate the user.
288288
289289### TSQLDBRestModule
290290
291291Unit: *fpc/packages/fcl-web/src/restbridge/sqldbrestmodule.pp*
292292
293293- 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.
294294
295295### TSQLDBRestResource
296296
297297Unit: *fpc/packages/fcl-web/src/restbridge/sqldbrestschema.pp*
298298
299299This is a collection item, found in the 'Resources' property of the **TSQLDBRestSchema**. It represents a single REST resource.
300300
301301#### properties
302302
303303It has the following properties:
304304
305305- **Fields** (TSQLDBRestFieldList) A list of fields that will be included in the output, or can be supplied in the input.
306306- **Enabled** (Boolean) Is this resource enabled ?
307307- **InMetadata** (Boolean) Should this resource be shown in the metadata list ?
308308- **ConnectionName** (UTF8String) Connection name to use for this resource.
309309- **TableName** (UTF8String) Database table name. This must only be specified if the SQL is auto generated.
310310- **ResourceName** (UTF8String) Name of this resource as exposed to the outside world.
311311- **AllowedOperations** (TRestOperations) The operations allowed on this resources (Get/Put/Post/Delete/Options/Head)
312312- **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.
313313- **SQLInsert** (TStrings) SQL INSERT statement for a POST request. Left empty, it is autogenerated based on the table name.
314314- **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.
315315- **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.
316316- *'SQL* an array of SQL statements, based on the previous ones.
317317- **BusinessProcessor** (TSQLDBRestCustomBusinessProcessor) at runtime this contains the business processor for this resource (if any)
318318
319319#### Events
320320
321321The following events are available:
322322
323323- **OnResourceAllowed** (TSQLDBRestAllowResourceEvent) Called to check whether the user is allowed to access this resource.
324324- **OnAllowedOperations** (TSQLDBRestAllowedOperationsEvent) Called to allow to fine-tune the allowed operations for the user.
325325- **OnGetDataset** (TSQLDBRestGetDatasetEvent) You can return a custom dataset for GET operations.
326326- **OnCheckParams** (TSQLDBRestCheckParamsEvent) You can check the INSERT/UPDATE/DELETE SQL Statement parameters in this request/
327327- **OnAllowRecord** (TSQLDBRestAllowRecordEvent) Called for each record, you can ddecide whether the record should be included in the output.
328328
329329Note: when set, the corresponding event in the business processor is not triggered.
330330
331331#### Methods
332332
333333The following methods exist:
334334
335335` Function GetDataset(aContext : TBaseRestContext; aFieldList : TRestFieldPairArray; aOrderBy : TRestFieldOrderPairArray; aLimit, aOffset : Int64) : TDataset;`
336336
337337Get the custom dataset for this resource.
338338
339339` function GenerateDefaultSQL(aKind: TSQLKind): UTF8String; virtual;`
340340
341341Get the default SQL for this resource if none was specified.
342342
343343` function GetFieldList(aListKind: TFieldListKind): UTF8String;`
344344
345345Return a list of fields as a string, separated by a correct separator token
346346
347347` function GetFieldArray(aListKind: TFieldListKind): TSQLDBRestFieldArray;`
348348
349349Return a list of fields, similar to GetFieldList, but returns the raw fields.
350350
351351` Function GetResolvedSQl(aKind : TSQLKind; Const AWhere : UTF8String; Const aOrderBy : UTF8String = `*`; aLimit : UTF8String =`*`) : UTF8String;`
352352
353353Return the actual SQL Statement that will be executed, with macros
354354
355355` Procedure PopulateFieldsFromFieldDefs(Defs : TFieldDefs; aIndexFields : TStringArray; aProcessIdentifier : TProcessIdentifier; aMinFieldOpts : TRestFieldOptions);`
356356
357357Populate the fields collection from a TFieldDefs collection.
358358
359359### TSQLDBRestField
360360
361361Unit: *fpc/packages/fcl-web/src/restbridge/sqldbrestschema.pp*
362362
363363The TSQLDBREstResource has a collection of fields (TSQLDBRestField) that determine the output fields of the REST resource
364364
365365It has the following properties;
366366
367367- FieldName (UTF8String Read FFieldName Write FFieldName;
368368- PublicName (UTF8String Read GetPublicName Write FPublicName;
369369- GeneratorName (String) name of a generator to privide a unique value.
370370- FieldType (TRestFieldType) Data type of the exposed field.One of (the names speak for themselves)
371371 - rftInteger
372372 - rftLargeInt
373373 - rftFloat
374374 - rftDate
375375 - rftTime
376376 - rftDateTime
377377 - rftString
378378 - rftBoolean
379379 - rftBlob (sent as base64-encoded data)
380380- NativeFieldType (TFieldType) Native database field type of this field.
381381- Options (TRestFieldOptions) options for this field. One of more of:
382382 - foInKey This is a key field.
383383 - foInInsert The field can be inserted (if statement is autogenerated)
384384 - foInUpdate The field can be updated (if statement is autogenerated)
385385 - foRequired A field value is required.
386386 - foFilter Filtering is allowed on this field.
387387 - foOrderBy Ordering is allowed on this field.
388388 - foOrderByDesc Ordering (descendent) is allowed on this field.
389389- Filters (TRestFieldFilters) Allowed filter expressions for this field. One or more of:
390390 - rfEqual
391391 - rfLessThan
392392 - rfGreaterThan
393393 - rfLessThanEqual
394394 - rfGreaterThanEqual
395395 - rfNull
396396- MaxLen (integer) for string fields, the maximum allowed length of the field.
397397
398398### TSQLDBRestBusinessProcessor
399399
400400Unit: *fpc/packages/fcl-web/src/restbridge/sqldbrestschema.pp*
401401
402402This 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.
403403
404404The following properties and events are available:
405405
406406- **Schema** : The schema in which the resource resides.
407407- **ResourceName** The resource for which the business rules are valid.
408408- **OnGetDataset** : Event called when you want to create a custom dataset. You must free the dataset yourself.
409409- **OnCheckParams** : Event in which you can verify whether the parameters for insert/update/delete/select queries are OK.
410410- **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.
411411- **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.
412412- **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.
413413
414414All calls get passed a TRestContext instance. This contains 2 properties and a method:
415415
416416`  Function GetVariable(Const aName : UTF8String; aSources : TVariableSources; Out aValue : UTF8String) : Boolean;`
417417
418418Call this to get a HTTP Query variable, header,... The function returns true if the variable was found.
419419
420420`  Property UserID : UTF8String`
421421
422422This will be set when calling.
423423
424424`  Property Data : TObject`
425425
426426You 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.
427427
428428## Special Resources
429429
430430### metaData
431431
432432The */baseURL/metaData* resource lists all the resources defined in the schema, together with the allowed operations.
433433
434434The usual formats and parameters are supported.
435435
436436### metaData/resourceName
437437
438438The */baseURL/metaData/resourceName* resource lists all the fields in the **resourceName** resource, together with the properties.
439439
440440The usual formats and parameters are supported for this resource.
441441
442442### customview
443443
444444The customView resource is special. Its availability must be enabled using the *Dispatcher*'s Options. When *rdoCustomView* is included in the options, the
445445
446446` baseURL/customView`
447447
448448URL becomes available. It allows the client to specify an SQL Select statement using the *SQL* parameter:
449449
450450` baseURL/customView?SQL=select count(*) as thecount from person`
451451
452452(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.
453453
454454The 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.
455455
456456### _connection
457457
458458This 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.
459459
460460Because 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.
461461
462462Use 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/
463463
464464## Available Output formats
465465
466466### JSON (the default)
467467
468468- A simple JSON object encapsulating data, metadata and possibly error nodes.
469469- rows are exported as JSON objects, field names are property names of the object.
470470- Name: 'json'
471471- Content-type: 'application/json'
472472- Input and output.
473473- Data by default under 'data'
474474- Metadata by default under 'metaData'
475475- Errors reported under 'error'
476476- Property names are configurable in REST dispatcher.
477477
478478### XML (a custom format)
479479
480480- A simple XML document encapsulating data, metadata and possibly error nodes, under a root element 'datapacket'
481481- rows are exported as XML elements (named 'row') , the contents as text in the element.
482482- Name: 'xml'
483483- Content-type: 'text/xml'
484484- Input and output.
485485- Data by default under 'data'
486486- Metadata by default under 'metadata'
487487- Errors reported under 'error'
488488- Element names are configurable in REST dispatcher.
489489
490490### CSV
491491
492492- Simple comma-separated CSV list.
493493- Name: 'csv'
494494- Content-type: 'text/csv'
495495- Input and output.
496496- Separator: Comma
497497- Quotes when needed.
498498- Metadata means first line contains fieldnames.
499499
500500### CDS
501501
502502- XML package using the XMLFormat used by Delphi `TClientDataset`.
503503- Name: 'cds'
504504- Content-type: 'text/csv'
505505- Input and output.
506506
507507A Delphi demo program is provided.
508508
509509### ADO
510510
511511- XML format as used by ADO recordsets (as used by MS Access)
512512- Name: 'ado'
513513- Input and output.
514514
515515## Ini file Support
516516
517517The following classes can load/save their configuration settings from/to an .ini file
518518
519519- TSQLDBRestDispatcher
520520- TRestBasicAuthenticator
521521- TSQLDBRestConnection
522522- TRestStringsConfig
523523
524524The support for this is implemented in 2 units;
525525
526526- the sqldbauthini unit has a type helper for the TRestBasicAuthenticator class.
527527- The sqldbrestini unit has the type helpers for TSQLDBRestDispatcher and TSQLDBRestConnection and TRestStringsConfig.
528528
529529The helpers implement LoadFromFile/SaveToFile methods, as well as LoadFromIni/SaveToIni methods. There are some options to control the level of depth.
530530
531531The 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.
532532
533533## Lazarus Support
534534
535535Requires Lazarus 2.1+
536536
537537Lazarus support for the SQLDB REST Bridge is implemented in 2 packages under the **components/sqldbrest** directory:
538538
5395391. The design/sqldbrestschemadesigner.lpk package.
5405402. The lazsqldbrest.lpk package.
541541
542542The latter package registers the **TSQLDBRestDispatcher**, **TSQLDBRestSchema** and **TRestBasicAuthenticator** components on the component palette: The former includes the schema editor. They should be compiled and installed in the order presented here.
543543
544-<figure>
545-<img src="sqldbrestcomponents.png" title="sqldbrestcomponents.png" />
546-<figcaption>sqldbrestcomponents.png</figcaption>
547-</figure>
544+![](/wiki-images/d/d6/Sqldbrestcomponents.png)
548545
549546Additionally it registers some component- and property editors. In particular the GUI schema editor can be called from the **TSQLDBRestSchema** component context menu.
550547
551548The GUI schema editor is included in the IDE, it is discussed in a separate page [[SQLDBRestSchemaEditor]]
552549
553550Further integration with Lazarus is planned: 1. Let the IDE act as a REST server. (alternatively, add a tool with a menu entry under tools for easy configuration)
554551
555552Lazarus 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 components/sqldbrest/src directory.
556553
557554To this end,
558555
5595561. create a directory **src** below the **components/sqldbrest directory** (where the package is located)
5605572. copy all files in directory
561558
562559` fpc/packages/fcl-web/src/restbridge`
563560
564561
565562to the new *src* directory
566563
567564` lazarus/components/sqldbrest/src`
568565
5695661. compile the **lazarus/components/sqldbrest/design/sqldbrestschemadesigner.lpk** package. It has unitpath ../src, so it should find the files in the *src* directory.
5705672. compile the **lazarus/components/sqldbrest/lazsqldbrest.lpk** package.
571568
572569## Pas2JS Support
573570
574571The SQLDB Rest bridge will be integrated in the compile server that comes with pas2JS: This means that pas2js will come with a toll that
575572
576573- Can recompile your web project on the fly
577574- Can serve files on disc
578575- Can act as a REST server.
579576
580577So no actual server is needed during development.
581578
582579## Usage
583580
584581### In a fcl-web application.
585582
586583The rest bridge was designed to be simple to use.
587584
588585#### Expose a single database, no authentication.
589586
590587Simple 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)
591588
592589```delphi
593590FDisp:=TSQLDBRestDispatcher.Create(Self);
594591FDisp.ExposeDatabase(
595592 'postgres','localhost','expensetracker','me','secret'
596593 ,Nil,
597594 [foFilter,foInInsert,foInUpdate,foOrderByDesc]);
598595FDisp.Active:=True;
599596FDisp.SaveToFile('demo.ini');
600597```
601598
602599This 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'
603600
604601The configuration will be saved in a file called 'demo.ini'.\
605602It can be reused to quickly set up a REST dispatcher.
606603
607604#### Expose single database, HTTP Basic authentication.
608605
609606Similar to the previous example, but with HTTP BASIC authentication for a single user:
610607
611608```delphi
612609FAuth:=TRestBasicAuthenticator.Create(Self);
613610FAuth.DefaultUserName:='me';
614611FAuth.DefaultPassword:='secret';
615612FDisp:=TSQLDBRestDispatcher.Create(Self);
616613FDisp.Authenticator:=Fauth;
617614FDisp.ExposeDatabase(
618615 'postgres','localhost','expensetracker','me','secret'
619616 ,Nil,
620617 [foFilter]);
621618FDisp.Active:=True;
622619```
623620
624621This 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.
625622
626623#### Expose single database, HTTP Basic authentication (2)
627624
628625Smilar to the previous example, but with HTTP BASIC authentication, using the database to authenticate a user:
629626
630627```delphi
631628FAuth:=TRestBasicAuthenticator.Create(Self);
632629FAuth.AuthenticateUserSQL.Text:='select uID from users where (uLogin=:UserName) and (uPassword=:Password)';
633630FDisp:=TSQLDBRestDispatcher.Create(Self);
634631FDisp.Authenticator:=Fauth;
635632FDisp.ExposeDatabase(
636633 'postgres','localhost','expensetracker','me','secret'
637634 ,['projects','expenses'],
638635 []);
639636FDisp.Active:=True;
640637```
641638
642639Here only the 'projects' and 'expenses' tables are exposed, read-only.
643640
644641#### Using a Config file and schema files.
645642
646643Start a dispatcher, loading the file demo.ini. The dioSkipReadSchemas tells it not to load schema files, the schemas will be created from the connections.
647644
648645```delphi
649646FDisp:=TSQLDBRestDispatcher.Create(Self);
650647FDisp.LoadFromFile('demo.ini',[dioSkipReadSchemas]);
651648FDisp.Active:=True;
652649```
653650
654651The .ini file can be created using SaveToFile on a configured dispatcher instance.
655652
656653### In the lazarus IDE.
657654
658655To work in the lazarus IDE with the SQLDB Rest bridge, you must install the **lazsqldbrest** package, which can be found in the directory components/sqldbrest.
659656
660657#### Using a datamodule
661658
662659In this approach, a datamodule is created that is in memory throughout the whole lifetime of the application (fcl-web application)
663660
6646611. Create a HTTP server application or FCGI application. (a CGI will also work but is very inefficient)
6656622. Add a plain datamodule to the application.
6666633. Drop a TSQLDBRestSchema class from the 'FCL-Web' tab of the component palette
6676644. Edit the schema (property resources), or import it from file using the component editor context menu
6686655. Drop a TSQLDBRestDispatcher class from the 'FCL-Web' tab of the component palette
6696666. Edit the connections
6706677. Add an item to the Schemas property and point it to the TSQLDBRestSchema added previously
6716688. For HTTP Basic authentication, add a TRESTBAsicAuthenticator class, and set the TSQLDBRestDispatcher instance's Authentocator property to it.
672669
673670The end result should look more or less like this:
674671
675-<figure>
676-<img src="restmodule.png" title="restmodule.png" />
677-<figcaption>restmodule.png</figcaption>
678-</figure>
672+![](/wiki-images/2/2a/Restmodule.png)
679673
680674That's it. The project is ready to run.
681675
682676#### Using a SQLDBRestdatamodule
683677
684678This approach is basically the same as the previous one.
685679
6866801. Create a HTTP application
6876812. Under File - New, create a SQLDB Rest Bridge Module.
6886823. Drop a SQLDBRestDispatcher component on the module.
6896834. The Dispatcher property of the module should be set to the SQLDBRestDispatcher component.
6906845. Set up the component as required, as in the previous example.
691685
692686## Examples
693687
694688### FPC
695689
696690- in FPC Packages, the fcl-web/examples/restbridge directory, there is a small example that serves a expenses tracker database.
697691- The directory (delphiclient) below contains a small Delphi project that shows how to connect a TClientDataset to the SQLDB Rest bridge.
698692
699693
700694Design time view:
701695
702-<figure>
703-<img src="delphirestclientdesign.png" title="delphirestclientdesign.png" />
704-<figcaption>delphirestclientdesign.png</figcaption>
705-</figure>
696+![](/wiki-images/9/9a/Delphirestclientdesign.png)
706697
707698Run time view:
708699
709-<figure>
710-<img src="delphirestclient.png" title="delphirestclient.png" />
711-<figcaption>delphirestclient.png</figcaption>
712-</figure>
700+![](/wiki-images/7/7b/Delphirestclient.png)
713701
714702### Lazarus
715703
716704Requires Lazarus 2.1+
717705
718706There 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.
719707
720708#### Server examples
721709
722710- The lazarus/components/sqldbrest/demo/restbridge directory contains the same example program restserver.lpi, using a datamodule.
723711- The lazarus/components/sqldbrest/demo/restmodule directory contains the same example program demorestmodule.lpi, using a SQLDB Rest Web datamodule.
724712
725713#### TBufDataset client example
726714
727715- The lazarus/components/sqldbrest/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.
728716
729717
730-<figure>
731-<img src="sqldbrestbufclientdata.png" title="sqldbrestbufclientdata.png" />
732-<figcaption>sqldbrestbufclientdata.png</figcaption>
733-</figure>
718+![](/wiki-images/2/2a/Sqldbrestbufclientdata.png)
734719
735720
736-<figure>
737-<img src="sqldbrestbufclientraw.png" title="sqldbrestbufclientraw.png" />
738-<figcaption>sqldbrestbufclientraw.png</figcaption>
739-</figure>
721+![](/wiki-images/2/2c/Sqldbrestbufclientraw.png)
740722
741723it also demonstrates how to use the metadata resource of the server to list the available resources
742724
743725#### TJSONDataset client example
744726
745727- The lazarus/components/sqldbrest/demo/jsonclient directory contains a demo that is similar to the bufclient demo:
746728
747729
748730it shows how to load data from a SQLDB REST bridge server in a TBaseJSONDataset dataset, using the 'csv' format
749731
750-<figure>
751-<img src="sqldbrestjsonclientdata.png" title="sqldbrestjsonclientdata.png" />
752-<figcaption>sqldbrestjsonclientdata.png</figcaption>
753-</figure>
732+![](/wiki-images/2/29/Sqldbrestjsonclientdata.png)
754733
755734
756-<figure>
757-<img src="sqldbrestjsonclientraw.png" title="sqldbrestjsonclientraw.png" />
758-<figcaption>sqldbrestjsonclientraw.png</figcaption>
759-</figure>
735+![](/wiki-images/3/33/Sqldbrestjsonclientraw.png)
760736
761737Like the bufdataset demo, it also demonstrates how to use the metadata resource of the server to list the available resources
762738
763739#### TCSVDataset client example
764740
765741- The lazarus/components/sqldbrest/demo/csvclient directory contains a demo that is similar to the bufclient demo:
766742
767743
768744it shows how to load data from a SQLDB REST bridge server in a TCSVDataset dataset, using the 'csv' format
769745
770746### Pas2JS
771747
772748Requires pas2js 1.5+
773749
774750- A similar application to the lazarus buffclient/jsonclient programs exists for pas2JS in pas2js/demo/restbridge/simple/restbridgeclient.lpi
775751
776752
777-<figure>
778-<img src="sqldbrestbridgepas2js.png" title="sqldbrestbridgepas2js.png" />
779-<figcaption>sqldbrestbridgepas2js.png</figcaption>
780-</figure>
753+![](/wiki-images/c/ca/Sqldbrestbridgepas2js.png)
781754
782755## TODO
783756
784757The following extensions are still planned:
785758
786759- Support for `?q=filterexpression` in URL filters.
787760- Connection management API. (zero-config service)
788761- Use HTTP credentials to connect to the database.
789762- Unknown query params are now ignored. Allow to check for valid query parameters and raise error if unknown query param is encountered.
790763
791764---
792765*From the Free Pascal wiki, page "SQLDBRestBridge", as it stood on 2023-03-01 after a change by Michael, 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).*
793766Category: Databases

Back to history