How do I prevent the conversion of my STRING datatype into INT in sqflite? (flutter) - flutter

onCreate: (db, version) {
// Run the CREATE TABLE statement on the database.
return db.execute(
'CREATE TABLE favourites(id STRING PRIMARY KEY, stop STRING, stop_name STRING, bus STRING)',
);
//id shall consist of both stop and bus numbers
},
This is a segment of my code I used to create the table.
Future<List<Favourite>> getFavourites() async {
// Get a reference to the database.
final db = await database();
// Query the table for all The Dogs.
final List<Map<String, dynamic>> maps = await db.query('favourites');
print('maps line 165: $maps');
// Convert the List<Map<String, dynamic> into a List<Dog>.
return List.generate(maps.length, (i) {
return Favourite(
id: maps[i]['id'],
stop: maps[i]['stop'],
stopName: maps[i]['stopName'],
bus: maps[i]['bus'],
);
});
}
This function above is what I used to retrieve my data. However I got this error instead.
"Unhandled Exception: type 'int' is not a subtype of type 'String'". This means that the numbers that I had inserted into the table as String were converted to int. For example, stop = "09038" would be converted to 9038 as an int.
All my objects were in String.
String id = '0';
String stop = '0';
String stopName = '0';
String bus = '0';
Any solution to this?

There is no STRING data type in SQLite but it is allowed to be used because SQLite allows anything to be used as a data type.
When you define a column as STRING it is actually considered to have NUMERIC affinity as it is described in Determination Of Column Affinity.
From Type Affinity:
A column with NUMERIC affinity may contain values using all five
storage classes. When text data is inserted into a NUMERIC column,
the storage class of the text is converted to INTEGER or REAL (in order
of preference) if the text is a well-formed integer or real literal,
respectively.....
See a simplified demo.
All you have to do is define the columns that you want to behave as strings with the proper data type which is TEXT:
CREATE TABLE favourites(
id TEXT PRIMARY KEY,
stop TEXT,
stop_name TEXT,
bus TEXT
);

Related

This row does not contain values for that table

I'm using Drift(moor).
When trying to get a sample of data using leftOuterJoin, the following situation happens:
The table that I join via leftOuterJoin returns null as a value.
I.e. leftOuterJoin itself works correctly but values from joined table are not read and return null.
As a result, I get a row where 1 or 2 columns have null values (depending on what table I join)
No one with such a situation is not faced?
final rows = await (select(favoritePlaces).join(
[
leftOuterJoin(
cachedPlaces, cachedPlaces.id.equalsExp(favoritePlaces.placeId)),
],
)).get();
parsedExpressions
Remove ".get()" from the last line.
Add below lines after your code:
final result = await rows.get();
return result.map((resultRow) {
return FavoritePlacesWithcachedPlaces(
resultRow.readTable(favoritePlaces),
resultRow.readTableOrNull(cachedPlaces),
);
}).toList();
where FavoritePlacesWithcachedPlaces object is something like:
class FavoritePlacesWithcachedPlaces {
final FavoritePlaces favoritePlaces;
final CachedPlaces? cachedPlaces;
FavoritePlacesWithcachedPlaces (this.favoritePlaces,
this.cachedPlaces);}
The key point is using "readTableOrNull".

Call jsonb_contains function (postgres) using JPA criteria and JsonBinaryType

I have a JPA/Hibernate entity which has a JSONB column (using https://github.com/vladmihalcea/hibernate-types ) for storing a list of strings. This works fine so far.
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
#Type(type = "jsonb")
#Column(name = "TAGS", columnDefinition = "jsonb")
private List<String> tags;
Now I want to check if another string is contained in the list of strings.
I can do this by writing a native query and use the #> operator from Postgres. Because of other reasons (the query is more complex) I do not want to go in that direction. My current approach is calling the jsonb_contains method in a Spring Data specification (since the operator is just alias to this function), e.g. jsonb_contains('["tag1", "tag2", "tag3"]','["tag1"]'). What I am struggling with is, getting the second parameter right.
My initial approach is to also use a List of Strings.
public static Specification<MyEntity> hasTag(String tag) {
return (root, query, cb) -> {
if (StringUtils.isEmpty(tag)) {
return criteriaBuilder.conjunction();
}
Expression<Boolean> expression = criteriaBuilder.function("jsonb_contains",
Boolean.class,
root.get("tags"),
criteriaBuilder.literal(List.of(tag)));
return criteriaBuilder.isTrue(expression);
};
}
This results in the following error.
Caused by: org.postgresql.util.PSQLException: ERROR: function jsonb_contains(jsonb, character varying) does not exist
Hinweis: No function matches the given name and argument types. You might need to add explicit type casts.
Position: 375
It does know that root.get("tags") is mapped to JSONB but for the second parameter it does not. How can I get this right? Is this actually possible?
jsonb_contains(jsob, jsonb) parameters must be jsonb type.
You can not pass a Java String as a parameter to the function.
You can not do casting in Postgresql via JPA Criteria.
Using JSONObject or whatever does not help because Postgresql sees it as
bytea type.
There are 2 possible solutions:
Solution 1
Create jsonb with jsonb_build_object(text[]) function and send it to jsonb_contains(jsonb, jsonb) function:
public static Specification<MyEntity> hasTag(String tag) {
// get List of key-value: [key1, value1, key2, value2...]
List<Object> tags = List.of(tag);
// create jsonb from array list
Expression<?> jsonb = criteriaBuilder.function(
"jsonb_build_object",
Object.class,
cb.literal(tags)
);
Expression<Boolean> expression = criteriaBuilder.function(
"jsonb_contains",
Boolean.class,
root.get("tags"),
jsonb
);
return criteriaBuilder.isTrue(expression);
}
Solution 2
Create custom function in your Postgresql and use it in Java:
SQL:
CREATE FUNCTION jsonb_contains_as_text(a jsonb, b text)
RETURNS BOOLEAN AS $$
SELECT CASE
WHEN a #> b::jsonb THEN TRUE
ELSE FALSE
END;$$
LANGUAGE SQL IMMUTABLE STRICT;
Java Code:
public static Specification<MyEntity> hasTag(String tag) {
Expression<Boolean> expression = criteriaBuilder.function(
"jsonb_contains_as_text",
Boolean.class,
root.get("tags"),
criteriaBuilder.literal(tag)
);
return criteriaBuilder.isTrue(expression);
}
I think that the reason is that you pass the varchar as the second param. jsonb_contains() requires two jsonb params.
To check a jsonb array contains all/any values from a string array you need to use another operators: ?& or ?|.
The methods bindings for them in PSQL 9.4 are: jsonb_exists_all and jsonb_exists_any correspondingly.
In your PSQL version, you could check it by the following command:
select * from pg_operator where oprname = '?&'

Using the Dart/Flutter Postgres Package to store dates and null dates needs two separate commands

I am using the Postgres Package (On the pub.dev site) to UPDATE records in a very simple database. It has two fields: a Text field prime key named number, and a Date field named date_of_birth.
If the date_of_birth is a valid DateTime string then all is well (as can be seen from the code below). But if date_of_birth is unknown (so I set to null) the UPDATE fails:
import 'package:postgres/postgres.dart';
void main() async {
final conn = PostgreSQLConnection(
'localhost',
XXXXX,
'XXXXX',
username: 'XXXXX',
password: 'XXXXX',
);
await conn.open();
DateTime dob = DateTime.now();
var results;
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
await conn.close();
}
If I set:
dob = null;
The program fails with the error:
Unhandled exception:
PostgreSQLSeverity.error 22007: invalid input syntax for type date: "null"
So I need to include a check on the dob field and the program now looks like this:
DateTime dob = DateTime.now();
dob = null;
var results;
if (dob == null) {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = null
WHERE number = '123123'
''');
} else {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
}
That works fine for my simple database, but in my real App. I have a number of date fields in one table. So I have to do a check for each possible combination of those date values - writing a code block for each!
Can anyone tell me how I can UPDATE both null and a valid date using a single statement please?
You are quoting the query parameters yourself. NEVER do this. In addition to the sort of problem you have just seen it also leaves you open to a trivial SQL injection attack.
The library you are using will have some way of putting placeholders into the query text and passing variables when executing the query. Use that.

how to convert map<anydata> to json

In my CRUD Rest Service I do an insert into a DB and want to respond to the caller with the created new record. I am looking for a nice way to convert the map to json.
I am running on ballerina 0.991.0 and using a postgreSQL.
The return of the Update ("INSERT ...") is a map.
I tried with convert and stamp but i did not work for me.
import ballerinax/jdbc;
...
jdbc:Client certificateDB = new({
url: "jdbc:postgresql://localhost:5432/certificatedb",
username: "USER",
password: "PASS",
poolOptions: { maximumPoolSize: 5 },
dbOptions: { useSSL: false }
}); ...
var ret = certificateDB->update("INSERT INTO certificates(certificate, typ, scope_) VALUES (?, ?, ?)", certificate, typ, scope_);
// here is the data, it is map<anydata>
ret.generatedKeys
map should know which data type it is, right?
then it should be easy to convert it to json like this:
{"certificate":"{certificate:
"-----BEGIN
CERTIFICATE-----\nMIIFJjCCA...tox36A7HFmlYDQ1ozh+tLI=\n-----END
CERTIFICATE-----", typ: "mqttCertificate", scope_: "QARC", id_:
223}"}
Right now i do a foreach an build the json manually. Quite ugly. Maybe somebody has some tips to do this in a nice way.
It cannot be excluded that it is due to my lack of programming skills :-)
The return value of JDBC update remote function is sql:UpdateResult|error.
The sql:UpdateResult is a record with two fields. (Refer https://ballerina.io/learn/api-docs/ballerina/sql.html#UpdateResult)
UpdatedRowCount of type int- The number of rows which got affected/updated due to the given statement execution
generatedKeys of type map - This contains a map of auto generated column values due to the update operation (only if the corresponding table has auto generated columns). The data is given as key value pairs of column name and column value. So this map contains only the auto generated column values.
But your requirement is to get the entire row which is inserted by the given update function. It can’t be returned with the update operation if self. To get that you have to execute the jdbc select operation with the matching criteria. The select operation will return a table or an error. That table can be converted to a json easily using convert() function.
For example: Lets say the certificates table has a auto generated primary key column name ‘cert_id’. Then you can retrieve that id value using below code.
int generatedID = <int>updateRet.generatedKeys.CERT_ID;
Then use that generated id to query the data.
var ret = certificateDB->select(“SELECT certificate, typ, scope_ FROM certificates where id = ?”, (), generatedID);
json convertedJson = {};
if (ret is table<record {}>) {
var jsonConversionResult = json.convert(ret);
if (jsonConversionResult is json) {
convertedJson = jsonConversionResult;
}
}
Refer the example https://ballerina.io/learn/by-example/jdbc-client-crud-operations.html for more details.?

Node pg-promise, bind multiple values with type casting

I'm currently using the pg-promise library to insert multiple values into a database in the format:
const cs = new pgp.helpers.ColumnSet(['booking_id', {name:'timeslot', cast:'timestamp'}], {table: 'booking'});
// data input values:
const values = [];
bookings.forEach(slot => {
values.push({booking_id: booking_id, timeslot: slot});
});
Where I need timeslot to be a timestamp. However it comes into the API as value like
1515586500.0
Using the above cast property my query gets resolved like so
insert into "booking"("booking_id","timeslot") values(1,'1515586500.0'::timestamp)
however this throws an error of cannot cast type numeric to timestamp without time zone
If I use the to_timestamp function however this works how I need it to e.g
insert into "booking"("booking_id","timeslot") values(1,to_timestamp('1515586500.0'));
Is there any way I can get pg-promise to use to_timestamp rather than the ::timestamp notation?
Change the column definition to this one:
{
name: 'timeslot',
mod: ':raw',
init: c => pgp.as.format('to_timestamp($1)', c.value)
}
or
{
name: 'timeslot',
mod: ':raw',
init: c => pgp.as.format('to_timestamp(${value})', c)
}
...as per the Column type documentation.
Or you can use Custom Type Formatting on the type, to self-format automatically.
Also, you do not need to remap values to suit the ColumnSet object, you use ColumnSet object to fit the data instead. So if the value for column timeslot is in property slot, you just use prop: 'slot' within your column definition to change where the value is coming from.