How to fetch two Properties one with value and another with only property name within same object in ReamDB? - realm

with RealmDB object how to write multiple keys query ?
Schema Part:
StudentSchemaNames.student_data = { classID: int, students:
Students[], noOfPresence: int, noOfabsence: int, noOfLeft: int } ;
StudentScehmaNames.students = {studentid:int, studentfirstName:
string:, studentlastName:string}
I am having an object like;
studentDetails = [{"classID": "001", "students": [Array],
"noOfPresence": 30, "noOfabsence": 2, "noOfLeft": 9}];
currently I am fetching details basic on studentId= 001 ;
studentDetails = await RealmDB.get(StudentSchemaNames.student_DATA,
studentId="${studentId}" AND 'noOfPresence');
here student ID property is passed with value and noOfPresence only property name and no value in query to be executed.
but I wanted to write query like ;
Scenario1: Fetch data basis on student ID with value and NoOfPresence only Property
Scenario2: Fetch data basis on students property only with student id value
Scenario3: Fetch data basis on class Property only with student id value
help me out to write queries for above scenario with RealmDB. Thank you in advance

Related

SQFLite: How to get data when field value is json_encode?

I have data like this when using query final result = await db.query(tablePelajaran); print(result) .
Note: semester value is object i convert to json using json.encode()
[{id_pelajaran: 1, name_pelajaran: pelajran test, semester: {"id_semester":1,"name_semester":"Semester I"}, hari: [{"id_day":1,"name_day":"Senin","code_color":4294013189},{"id_day":2,"name_day":"Selasa","code_color":4291891529},{"id_day":3,"name_day":"Rabu","code_color":4284879090},{"id_day":4,"name_day":"Kamis","code_color":4279930851}], dosen: }, {id_pelajaran: 2, name_pelajaran: Another Pelajaran, semester: {"id_semester":2,"name_semester":"Semester II"}, hari: [{"id_day":1,"name_day":"Senin","code_color":4294013189},{"id_day":5,"name_day":"Jumat","code_color":4290904315}], dosen: }]
But now i want show only data when semester = 1 then i write query like this :
final db = await database();
final result = await db.rawQuery(
'SELECT * FROM $tablePelajaran WHERE semester = ? ',
[1],
);
print(result);
But the result always null , i expected data with id_semester = 1 will show . How can i access id_semester when this id is inside json.encode. I can't do json.decode() because i dont have semester data when query.
How can i access id_semester when this id is inside json.encode. I can't do json.decode() because i dont have semester data when query.
You should split the semester object into 2 other columns to access their values. Since sqflite is a structural database, it only allows fetching value at column level, not possible to go deeper than that. Then you only need to query the semeter_id column value:
final result = await db.rawQuery(
'SELECT * FROM $tablePelajaran WHERE semester_id = ? ',
[1],
);
One other solution if you're not allowed to modify the database structure, is to fetch all data, then parse it to a list of object
final pelajarans = List<Pelajaran>.from(data.map((rawPelajaran)=>Pelajaran.fromJson(rawPelajaran));
where rawPelajaran is each item inside the array you query from database.
Then from here you filter the data:
var _result = pelajarans.where((e) => e.semesterId == 1).toList;
Hope this help!
Here in your json semester value is actually String type. That's why when you want to get the value of id_semester it gives you null value. To get the value of id_semester you need to convert String to map. For that you can use jsonDecode. Here is an example:
final result = await db.query(tablePelajaran);
Map<dynamic, dynamic> map = jsonDecode(result[0]['semester']);
print(map['id_semester']);
var data= await _db.rawQuery('SELECT * FROM $tablePelajaran where json_extract($tablePelajaran.semester,"\$.id_semester") =?',[1]);
By using json_extract you can access any json inside any column...

boto3 resource for querying dynamodb : Query condition missed key schema element

I have a table as : AdvgCountries which has two columns
a. CountryId (String) (Parition Key)
b. CountryName(String) Sort Key
While creating the table , I created with only Partition Key and then later added a Global Secondary Index with Index name as:
CountryName-index
Type : GSI
Partition key : CountryId
Sort Key : CountryName
I am able to retrieve CountryName based upon CountryId but unable to retrieve CountryId based upon CountryName. Based upon my reading I found that there are options to do this by providing indexname but I get the following error:
botocore.exceptions.ClientError: An error occurred
(ValidationException) when calling the Query operation: Query
condition missed key schema element: CountryId
import boto3
import json
import os
from boto3.dynamodb.conditions import Key, Attr
def query_bycountryname(pCountryname, dynamodb=None):
if not dynamodb:
dynamodb = boto3.resource('dynamodb', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")
table = dynamodb.Table('AdvgCountires')
print(f"table")
attributes = table.query(
IndexName="CountryName-index",
KeyConditionExpression=Key('CountryName').eq(pCountryname),
)
if 'Items' in attributes and len(attributes['Items']) == 1:
attributes = attributes['Items'][0]
print(f"before return")
return attributes
if __name__ == '__main__':
CountryName = "India"
print(f"Data for {CountryName}")
countries = query_bycountryname(CountryName)
for country in countries:
print(country['CountryId'], ":", country['CountryName'])
Any help is appreciated.
You can't be able to fetch primary key value based on sort key. DynamoDB does not work like this.
In Dynamodb, each item’s location is determined by the hash value of
its partition key.
The Query operation in Amazon DynamoDB finds items based on primary
key values.
KeyConditionExpression are used to write conditional statements by
using comparison operators that evaluate against a key and limit the
items returned. In other words, you can use special operators to
include, exclude, and match items by their sort key values.

Unique serial number generation - Entity Framework ASp.net MVC

I am developing a complaint management in which I have to generate unique serial number for each complaint like 00001/20 {Serial number/year}.
I am using repository pattern and i am generating this complaint number using the following code snippet but problem is if two user try to lodge a complaint at the same time it will generate a same complaint no and that thrown an error as I am keeping a serial number in a separate table which is also mentioned below for reference. Let me know the best way to achieve this
int serialNo = repository.serialNo.Find(c => c.Year == DateTime.Now.Year).FirstOrDefault().TicketCounter;
string complaintNo = string.Format("{0}", serialNo.ToString().PadLeft(5, '0'));
model.Id = repository.complaintRepo.GetMaxPK(c => c.Id);
I am using repository pattern.
I guess, one of the solutions is to setup the table so that it generates required ID automatically on every new row. This ensures that the ID is always unique.
CREATE SEQUENCE MySequence
AS int
START WITH 1
INCREMENT BY 1;
CREATE TABLE Complaint
(
Id char(8) CONSTRAINT [DF_Complaint_ID]
DEFAULT FORMAT((NEXT VALUE FOR MySequence), '0000#')
+'/'+RIGHT(YEAR(GETDATE()),2),
Foo int,
Bar int,
CONSTRAINT [PK_MyTable] PRIMARY KEY (Id)
);
Demo: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=18a5d0fec80a3985e30cef687d3c8e49
So there will be no need to assign the id manually and your code could look like
var c = repository.Insert(new model
{
Foo = ...
Bar = ...,
...
});
repository.Save();
// you can get id after inserting data in the database
string id = c.Id;

State's Unique Identify in Corda

I want to create State with unique id in database. There is my State code
data class SampleState(
val partyA: Party,
val partyB: Party,
val value: Int,
val id: String,
override val linearId: UniqueIdentifier = UniqueIdentifier(id),
val properties: LCProperties = LCProperties("ABC")) : LinearState {...}
When I commit two similar SampleState, there are two different State in database with two different linearId. So, There are anyone can talk me that how to ensure that the "id" of a object of SampleState in database is unique?
I used same code for catch this case in Flows and Contracts like
val results = builder {
val quantityIndex = SampleSchemaV1.PersistentSample::id.equal(id);
val customCriteria1 = QueryCriteria.VaultCustomQueryCriteria(quantityIndex)
val criteria = generalCriteria.and(customCriteria1);
serviceHub.vaultService.queryBy<SampleState>(criteria)
}
if(results.states.count() > 0)
throw IllegalArgumentException("id $id is exist")
However, it do not work with two commit Sample State Transaction in a near similar time even that in 1s (commit Transaction 1, and after 1 second, commit Transaction 2)
In your state code, it is this line:
override val linearId: UniqueIdentifier = UniqueIdentifier(id)
That creates a unique id for you. The id that you are passing into UniqueIdentifier binds the unique id that is generated to your id. However all equality and comparison are based on the unique ID only.
Take a look at UniqueIdentifier.kt in the source code and you'll see this is the underlying code:
data class UniqueIdentifier(val externalId: String? = null, val id: UUID = UUID.randomUUID()) : Comparable<UniqueIdentifier> {
override fun toString(): String = if (externalId != null) "${externalId}_$id" else id.toString()
This is a good post about how good Java's randomUUID is in ensuring an id is unique
You can also read more about UniqueIdentifier here

how to pass local variable to a linq query

I have the following code in which I am passing a local variable to a linq query for a specific record, after that record I want to check whether there is a record according to that id or not.
First it gives me the error "Cannot implicitly convert type int to bool"
Second if I want to count the rows in this query or want to check whether there is a row or not, how will I do that, here is my code:
int J_Job_ID = Convert.ToInt32(Request.QueryString["J_Job_ID"]);
//Check If this ID exists in the database
var query = from m in JE.J_Posted_Jobs_Tbl
where m.J_Job_ID = Convert.ToInt32(J_Job_ID)
select m;
it should be
where m.J_Job_ID == Convert.ToInt32(J_Job_ID)
as for count
query.Count()

Resources