How to use deadpool_postgres with rocket? - database

Rocket documentation includes only example for sqlx db driver. In particular I'm interested in a step 4 where documentation shows how to use db pool in order to perform a query:
use rocket_db_pools::Connection;
use rocket_db_pools::sqlx::Row;
#[get("/<id>")]
async fn read(mut db: Connection<Logs>, id: i64) -> Option<Log> {
sqlx::query("SELECT content FROM logs WHERE id = ?").bind(id)
.fetch_one(&mut *db).await
.and_then(|r| Ok(Log(r.try_get(0)?)))
.ok()
}
How can I write the same query but with deadpool_postgres driver?

Related

React Native - How to connect to AWS DynamoDB table

I am following this aws tutorial to create my first React Native app which connects to AWS:
aws tutorial
Everything installs fine and my app runs happily with the following imports:
**import Amplify from 'aws-amplify';
import aws_exports from './aws-exports';
Amplify.configure(aws_exports);**
I would now like to connect the app to an existing DynamoDB table called 'Movement' but the tutorial only shows how to create a new table with the NoSQL wizard using: awsmobile database enable --prompt
Could you point me to a (simple) resource that shows me how to connect to an existing DynamoDB table and perform CRUD operations?
These are the steps I have followed:
I have a DynamoDB table called: movement
It has 3 items : hub_id, on_time, message
Hub_id is the primary partition key
on_time is the primary sort key
The table holds sensor data (movement, temperature that sort of thing) in the message item.
I created the app using :
create-react-native-app dbapp
I have then run:
awsmobile configure
aws mobile init
Installed amplify:
npm install aws-amplify --save
I created the project in mobile hub.
I then linked the app to the hub using:
awsmobile init 15c482e2-2c3c-11e8-8692-fblahblahblah3
CLI responded : Successfully linked AWS Mobile Hub project: dbapp-datetime!
So all looks good so far (I hope!)
I then altered app.js to look like this: pastebin
npm start runs just fine with no errors that I can see.
The problem that I currently have is that I don't have a clue about how to query my table and populate variables so that I can use them in the view.
Following the resources suggested (thanks SteveB). I connected to the DynamoDB table, queried it and used the data in my app.
In case you are also stuck, here is an edited version of my code. Apologies to everyone that gets to edit this - I know it is awful. Does work though :)
// Use db to query the dynamoDB table - setup query parameters first //
var params = {
TableName : "myproject-mobilehub-123456789-Sensors",
ProjectionExpression:"hub_id, details.on_time, details.sensor_name,
details.temperature, details.battery",
KeyConditionExpression: "hub_id = :hid AND begins_with(on_time, :d)",
ExpressionAttributeValues: {
":hid":"testdevice01",
":d": today,
},
Limit: 1,
ScanIndexForward: false
};
//Execute db query using params
async getQuery() {
db.query(params, function(err, data) {
if (err) { console.log("Query failed.");
} else {
console.log("Query succeeded.");
};
data.Items.forEach(function(details) {
//display variables
console.log(details.hub_id,details.details.sensor_name,details.details.on_time,
details.details.temperature, details.details.battery,);
//Populate variables
hubid = details.hub_id;
currroom = details.details.sensor_name;
roomtime = details.details.on_time;
roomtemp = details.details.temperature;
roombattery = details.details.battery + "%";
});
}});
//Finally populate text with variables
this.setState({
displayText1: currroom,
displayText2: roombattery,
displayText3: roomtime,
displayText4: roomtemp
});

Ionic 3 I can't call data with SQLite

I am using SQLite on the project. I perform events like insert operations in database operations successfully. But I do not know how to reach the data when it brings the data. I am trying to create a list of the following code fragment. I'm waiting for your help.
GRUPLISTESI : any;
GRUPLAR(){
var sql = "SELECT * FROM 'GRUPLAR'";
this.db.executeSql(sql, {}).then((data)=>{
this.GRUPLISTESI = data["rows"]; //What should I write here?
});
}
You can access the data from your Ionic sqlite database like this:
db.executeSql("SELECT * FROM test")
.then(result => {
console.log(result.rows.item(0).id);
});
So abstract it would look like so: result.rows.item([row]).[column_label].
For some deeper examples on how to use sqlite for Ionic, you can use this repository: https://github.com/didinj/ionic3-angular4-cordova-sqlite-example

Retrieve multiple result sets in sails js

I am using sails js with it sails-mssqlserver adapter. The problem with it is that if my stored procedure returns multiple result sets then I only receive one result set which is the latest of all.
The same stored procedure is working fine with Java and I get to iterate over the relevant result sets.
I need to know if there is some specific way to access all result sets in sails-mssqlserver?
The sails-mssqlserver adapter is a wrapper of the official Microsoft SQL Server client for Node.js available here its dependecy however is not on the latest release.
Option 1:
As per this official documentation of the MsSQL package, you can enable multiple recordsets in queries with the request.multiple = true command.
To enable multiple queries/recordsets in the sails-mssqlserver adapter, a hackish workaround is to open sails-mssqlserver/lib/adapter.js and edit the raw query function. Adding request.multiple = true below var request = new mssql.Request(mssqlConnect). As shown in the example below.
// Raw Query Interface
query: function (connection, collection, query, data, cb) {
if (_.isFunction(data)) {
if (debugging) {
console.log('Data is function. A cb was passed back')
}
cb = data
data = null
}
adapter.connectConnection(connection, function __FIND__ (err, uniqId) {
if (err) {
console.error('Error inside query __FIND__', err)
return cb(err)
}
uniqId = uniqId || false
var mssqlConnect
if (!uniqId) {
mssqlConnect = connections[connection].mssqlConnection
} else {
mssqlConnect = connections[connection].mssqlConnection[uniqId]
}
var request = new mssql.Request(mssqlConnect)
// Add it here
request.multiple = true
request.query(query, function (err, recordset) {
if (err) return cb(err)
if (connections[connection] && !connections[connection].persistent) {
mssqlConnect && mssqlConnect.close()
}
cb(null, recordset)
})
})
},
Now the returned recordset should contain multiple results.
Option 2:
A more sustainable option for use cases where running a stored procedure which returns multiple recordsets, is to use the latest version of the official Microsoft SQL Server client for Node.js. Information on running stored procedures is available here
First install the latest package:
npm install mssql --save
In your code where you would like to run the stored procedure add a connection to the mssql database:
// require the mssql package
const sql = require('mssql')
// make a connection, you can use the values you have already stored in your adapter
const pool = new sql.ConnectionPool({
user: sails.config.connections.<yourMsSQLConnection>.user,
password: sails.config.connections.<yourMsSQLConnection>.password,
server: sails.config.connections.<yourMsSQLConnection>.server,
database: sails.config.connections.<yourMsSQLConnection>.database
})
// connect the pool and test for error
pool.connect(err => {
// ...
})
// run the stored procedure using request
const request = new sql.Request()
request.execute('procedure_name', (err, result) => {
// ... error checks
console.log(result.recordsets.length) // count of recordsets returned by the procedure
console.log(result.recordsets[0].length) // count of rows contained in first recordset
console.log(result.recordset) // first recordset from result.recordsets
console.log(result.returnValue) // procedure return value
console.log(result.output) // key/value collection of output values
console.log(result.rowsAffected) // array of numbers, each number represents the number of rows affected by executed statemens
// ...
})
// you can close the pool using
pool.close()
In cases, where the sails-* database adapter doesn't include all the functionality you require. I find it best to create a sails Service that wraps the additional functionality. It is a really clean solution.

How do I use another database other than default in play-framework?

Up until I was using only one database in my application. So for any sql query, I was just using the default database. Below is given the info about the database.
db.default.driver=org.postgresql.Driver
db.default.url="postgres://user:password#localhost:5439/database_name"
These info are saved in the appliction.conf file. In the code below DB is the default database.
DB.withConnection {
conn =>
{
val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
try {
statement.execute(sql)
}
catch {
case e: Exception => Logger.debug("There is some error with the database")
}
}
}
But I need to use another database. Below is given the info about the database.
db.um.driver=com.mysql.jdbc.Driver
db.um.url="mysql://user:password#localhost:3306/database_name"
These info are also saved in the application.conf file. Now how do I access that database and run an sql command.
The data source called default, as the name suggests, is used as a default value for all connections. You can see that the withConnection() method takes a parameter with a data source name but if nothing is passed, "default" is used instead.
To use your additional data source you have to specify it as a parameter of the withConnection() method.
DB.withConnection("um") { conn =>
// implement your action
}
In case someone is like myself, is looking to use multiple data resources in Play 2.6: This is not the answer.
We need to define the name of the database when we inject the instance of the Database, using #NamedDatabase:
class Customer #Inject()(#NamedDatabase("customer") db: Database){ ??? }

Delphi EMS FireDAC: How to pass parameter from client to server using EMS?

I am working on the simple client server application using EMS (i.e: for future iOS application) in Delphi.
On the client unit, I have EMSProvider and EMSFireDACClient which fetches data from a Database (MSSQL) through a Datasource.
On the server unit, I have FDConnection and TFDQuery which deals with my Database. So far everything is working fine.
Question: Now I need to pass some parameters from client to the server and that fetches the result data. How should I do using EMS? Any functions or procedures available in EMS?
Regarding source code, everything was handled by corresponding components. So coding part is very less.
Thanks in advance.
An EMS call is like a REST call. You can pass further URL parameters both in the path (handled directly) -- see the default implementation of getting items by ID) and as extra query params. Those are in the request object. To pass them, use a custom Endpoint in the client.
Here is some more info:
Server declaration:
[ResourceSuffix('{item}')]
procedure GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
Server implementation:
procedure TNotesResource1.GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
LItem: string;
begin
LItem := ARequest.Params.Values['item'];
...
Client configuration for endpoint:
object BackendEndpointGetNote: TBackendEndpoint
Provider = EMSProvider1
Auth = BackendAuth1
Params = <
item
Kind = pkURLSEGMENT
name = 'item'
Options = [poAutoCreated]
end>
Resource = 'Notes'
ResourceSuffix = '{item}'
end
Client call:
BackendEndpointGetNote.Params.Items[0].Value := AID;
BackendEndpointGetNote.Execute;
Hope this helps.

Resources