More and more applications move to Web: today Pas2JS allows to program pascal for the web.
Data 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.
So, an easy way to make data available through a REST service is needed.
The 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.
It is not meant as a general REST API framework, for this other frameworks exist. It is also not a RPC framework.
The design is such that a complete database can be exposed using a single line of code, with reasonable default settings.
Basically, SQLDBRestBridge can be used in a FCL-Web application to turn it into a REST server:
The 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.
It can be used simply: one line of code is enough to expose a complete database in this way.
Or 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.
The 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.
To consume the data served by this component, you need to write a client.
No 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.
This does not expose objects as REST resources.
Using some tricks, this could be done, but this is not a design goal.
Eventually, all data ends up in a database, and this component uses a direct mechanism to achieve that.
A maximum limit can be enforced. When the SQL statements support it, the limit and offset are translated to SQL fetch/offset clauses.
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.
Represents 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.
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.
PopulateResources creates a resource definition for each table in a database connection.
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.
OutputOptions (TRestOutputOptions) default Output options, modifiable by query. One or more of
ooMetadata Send metadata in request
ooSparse Do not send null values (if format allows it)
ooHumanReadable Pretty-print output.
InputFormat (string) Name of Input format to use for all requests.
OutputFormat (string) Name of Output format to use for all requests.
DispatchOptions (TRestDispatcherOptions) Dispatcher options. One or more of
rdoConnectionInURL Use the connection as a path element in the URL.
rdoExposeMetadata Expose the metadata URL.
rdoConnectionResource Expose the connection resource, allowing to manage connections through the REST protocol.
rdoCustomView allow the use of a customview URL (Select SQL specified in request)
rdoEmptyCorsDomainToOrigin if the CORDAllowedOrigins is empty, then the request server will be echoed to the client.
rdoHandleCORS Handle CORS preflight request.
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.
AdminUserIDs A list of user IDs (one per line) which are allowed to use the connection resource. If empty, all users can use it.
LogOptions Logging options. Logging happens through the OnLog event handler. This property controls which events are logged. The following values can be specified:
rloUser Include username in log messages, when available
rloConnection Log database connections (connect to database)
rloAuthentication Log authentication attempt
rloSQL Log SQL statements. (not on user-supplied connection)
rloResultStatus Log result status.
LogSQLOptions SQL Logging options. if rloSQL is specified, this option controls which SQLDB events are logged for new connections.
Authenticator (TRestAuthenticator) Authenticator for requests. If OnBasicAuthentication is set, this can be left empty.
EnforceLimit (Integer) If larger than zero, Enforce a limit on output results.
CORSAllowedOrigins (String) Comma separated list of Domains that are allowed to use this REST service. If empty, * will be returned in preflight request.
CORSMaxAge (Integer) Value for HTTP Access-Control-Max-Age header. If zero, the header is not sent.
CORSAllowCredentials (Boolean) value for HTTP header Access-Control-Allow-Credentials. Set to false not to send the header
ExposeDatabase exposes a database as a REST service. This will creates a connection definition with the provided parameters and calls ExposeConnection with this definition.
The connection gets the name ConnectionN, where N is a unique number, and the schema is named SchemaConnectionN. The Tables and aMinFieldOpt arguments are the same as in the PopulateResources call of TSQLDBRestSchema
ExposeConnection exposes a database (represented by aConnection) as a REST service. This will create a schema with a resource definition.
This class implements HTTP Basic authentication for the SQLDB REST Dispatcher
AuthConnection (TSQLConnection) a SQL connection that will be used to run the SQL. By default the connection of the request is used. Set this if your users are in a separate database.
AuthenticateUserSQL (TStrings) an SQL Statement that will be executed on the connection (AuthConnection or connection of the request). This must contain 2 parameters userName and password and return a single field. This field will be used as UserID (available in the rest of the request flow.
DefaultUserName (UTF8String) a valid username, not in the database.
DefaultPassword (UTF8String) password of a default user.
DefaultUserID (UTF8String) the user ID reported if the default user is authenticated.
AuthenticationRealm : (UTF8String) Real sent in the WWW-Authenticate challenge to the client.
OnBasicAuthentication (event) triggered when basic authentication is requested. Here you can enter custom code to validate the user.
This is a simple TWebModule descendant which is usable in Lazarus IDE. It has a single Dispatcher property which must be set to a TSQLDBRestDispatcher instance.
Fields (TSQLDBRestFieldList) A list of fields that will be included in the output, or can be supplied in the input.
Enabled (Boolean) Is this resource enabled ?
InMetadata (Boolean) Should this resource be shown in the metadata list ?
ConnectionName (UTF8String) Connection name to use for this resource.
TableName (UTF8String) Database table name. This must only be specified if the SQL is auto generated.
ResourceName (UTF8String) Name of this resource as exposed to the outside world.
AllowedOperations (TRestOperations) The operations allowed on this resources (Get/Put/Post/Delete/Options/Head)
SQLSelect (TStrings) SQL select statement for a GET request. Left empty, it is autogenerated based on the table name. The where clause uses the fields with the foInKey flag set for single resources.
SQLInsert (TStrings) SQL INSERT statement for a POST request. Left empty, it is autogenerated based on the table name.
SQLUpdate (TStrings) SQL UPDATE statement for a PUT request. Left empty, it is autogenerated based on the table name. The where clause uses the fields with the foInKey flag set.
SQLDelete (TStrings) SQL DELETE statement for a DELETE request. Left empty, it is autogenerated based on the table name. The where clause uses the fields with the foInKey flag set.
'SQL an array of SQL statements, based on the previous ones.
BusinessProcessor (TSQLDBRestCustomBusinessProcessor) at runtime this contains the business processor for this resource (if any)
This class serves to implement any business rules you want to attach to your rest resource.
You can drop one TSQLDBRestBusinessProcessor instance per resource on a module, set the
schema and resource name (a list of resource names is available in the Object Inspector) and implement the events.
The following properties and events are available:
Schema : The schema in which the resource resides.
ResourceName The resource for which the business rules are valid.
OnGetDataset : Event called when you want to create a custom dataset. You must free the dataset yourself.
OnCheckParams : Event in which you can verify whether the parameters for insert/update/delete/select queries are OK.
OnAllowResource : Event to decide whether a property is allowed for a request. You can use this e.g. to forbid certain users from accessing a resource.
OnAllowedOperations : Event to decide whether a REST operation is allowed for a request. You can use this to forbid certain users from writing to a resource, but allow them to read.
OnAllowRecord : Called for each record which will be output. This can be used to prevent certain records from being streamed to the output. Note that if Limit is specified, this will not be taken into account, i.e. if the limit is 10, and you forbid 2 records from being streamed at this point, only 8 records will be returned.
All calls get passed a TRestContext instance. This contains 2 properties and a method:
Function GetVariable(Const aName : UTF8String; aSources : TVariableSources; Out aValue : UTF8String) : Boolean;
Call this to get a HTTP Query variable, header,... The function returns true if the variable was found.
Property UserID : UTF8String
This will be set when calling.
Property Data : TObject
You can attach data to this if you want to. It will be kept for the duration of the request.
You are responsible for freeing this data, though.
The customView resource is special. Its availability must be enabled using the *Dispatcher'*s Options. When rdoCustomView is included in the options, the
baseURL/customView
URL becomes available. It allows the client to specify an SQL Select statement using the SQL parameter:
baseURL/customView?SQL=select count(*) as thecount from person
(you must encode the sql using the usual URI encoding mechanism, it is omitted for readability reasons here)
The usual parameters for fieldlists, format are supported, but not the limit and offset parameters.
The engine will check that only SELECT statements passed on.
Nevertheless, this is an inherently less safe mechanism which should only be used in case of need.
This is a resource that allows you to manage the connections through REST.
This can be useful in development environments, where you can simply create a single binary that does not need any configuration,
the whole configuration can be done through REST, including the management of the available connections.
Because this is security-wise a dangerous option to enable, it is disabled by default, and must be enabled explicitly with the rdoConnectionResource option of the dispatcher.
Use cases are a development environment where this can be used to confiure the restserver from within the IDE.
When moving to production, the option can be disabled, and only fixed and known connections will be allowed/
Lazarus support for the SQLDB REST Bridge is implemented in 2 packages under the components/sqldbrest directory:
The design/sqldbrestschemadesigner.lpk package.
The lazsqldbrest.lpk package.
The 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.
Additionally it registers some component- and property editors. In particular the GUI schema editor can be called from the TSQLDBRestSchema component context menu.
The GUI schema editor is included in the IDE, it is discussed in a separate page SQLDBRestSchemaEditor
Further 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)
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 components/sqldbrest/src directory.
To this end,
create a directory src below the components/sqldbrest directory (where the package is located)
copy all files in directory
fpc/packages/fcl-web/src/restbridge
to the new src directory
lazarus/components/sqldbrest/src
compile the lazarus/components/sqldbrest/design/sqldbrestschemadesigner.lpk package. It has unitpath ../src, so it should find the files in the src directory.
compile the lazarus/components/sqldbrest/lazsqldbrest.lpk package.
Simple expose of a database. Run the following code in the startup of your program (for example, DoRun of the web application class, or startup code of the program)
This exposes all tables of the database 'expenstracker', allows to filter,update and sort on all fields. The connection will be named 'Connection1', the schema 'SchemaConnection1'
The configuration will be saved in a file called 'demo.ini'.
It can be reused to quickly set up a REST dispatcher.
Expose single database, HTTP Basic authentication.
This exposes all tables of the database 'expenstracker', allows to filter,update and sort on all fields. The connection will be named 'Connection1', the schema 'SchemaConnection1'. No updates are possible: the fields will not be in update/insert statements. Sorting is also not allowed.
Expose single database, HTTP Basic authentication (2)
Smilar to the previous example, but with HTTP BASIC authentication, using the database to authenticate a user:
FAuth:=TRestBasicAuthenticator.Create(Self);FAuth.AuthenticateUserSQL.Text:='select uID from users where (uLogin=:UserName) and (uPassword=:Password)';FDisp:=TSQLDBRestDispatcher.Create(Self);FDisp.Authenticator:=Fauth;FDisp.ExposeDatabase('postgres','localhost','expensetracker','me','secret',['projects','expenses'],[]);FDisp.Active:=True;
Here only the 'projects' and 'expenses' tables are exposed, read-only.
Start a dispatcher, loading the file demo.ini. The dioSkipReadSchemas tells it not to load schema files, the schemas will be created from the connections.
To work in the lazarus IDE with the SQLDB Rest bridge, you must install the lazsqldbrest package, which can be found in the directory components/sqldbrest.
There are 2 server examples available, and several client examples.
The client examples are all the same, they just use a different kind of TDataset to show the data coming from the server: the buf, json and CSV formats are demonstrated in this way.
The 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.
it also demonstrates how to use the metadata resource of the server to list the available resources