I want to create a person with nick name jd and e-mail john.doe#provider.com in a persistent Apache Jena database.
I wrote following code:
var dataSet:Dataset? = null
val Dir = "data/MyDataSet"
dataSet = TDBFactory.createDataset(Dir)
dataSet.begin(ReadWrite.WRITE)
val model = dataSet.defaultModel
createPerson("john.doe#provider.com", model, "jd")
dataSet.end()
dataSet.close()
private fun createPerson(email: String, model: Model, nick: String) {
val uuid = UUID.randomUUID()
val uri = "http://mycompany.com/data/p-${uuid}"
val person = model.createResource(uri)
person.addProperty(VCARD.EMAIL, email)
person.addProperty(VCARD.N,
model.createResource()
.addProperty(VCARD.NICKNAME, nick))
}
When I run it, I get no errors.
But when I try to read the data from the file (see code below), the query doesn't find anything.
ds.begin(ReadWrite.READ)
val query = QueryFactory.create("""SELECT ?x
WHERE { ?x <http://www.w3.org/2001/vcard-rdf/3.0#EMAIL> "john.doe#provider.com" }""")
val qexec: QueryExecution
try {
qexec = QueryExecutionFactory.create(query, ds.defaultModel)
val rs = qexec.execSelect()
while (rs.hasNext()) {
val solution = rs.nextSolution()
System.out.println("")
}
}
catch (throwable:Throwable) {
logger.error("", throwable)
}
finally {
ds.end()
}
What's wrong with my code?
You should get a warning at end because you have not committed the transaction.
dataSet.begin(ReadWrite.WRITE)
val model = dataSet.defaultModel
createPerson("john.doe#provider.com", model, "jd")
dataSet.commit()
dataSet.end()
Related
i'm trying to extract data from the ANTLR parse tree, but not fully grasping how this should be done correctly
Let's say i have the following two SQL queries:
// language=SQL
val sql3 = """
CREATE TABLE session(
id uuid not null
constraint account_pk
primary key,
created timestamp default now() not null
)
""".trimIndent()
// language=SQL
val sql4 = """
CREATE TABLE IF NOT EXISTS blah(
id uuid not null
constraint account_pk
primary key,
created timestamp default now() not null
)
""".trimIndent()
Now i parse both of them:
val visitor = Visitor()
listOf(sql3, sql4).forEach { sql ->
val lexer = SQLLexer(CharStreams.fromString(sql))
val parser = SQLParser(CommonTokenStream(lexer))
visitor.visit(parser.sql())
println(visitor.tableName)
}
In my visitor if i visit the tableCreateStatement, i get the parse tree, but obviously just grabbing child1 will work for sql3, but not for sql4 since child1 in sql4 is IF NOT EXISTS
class Visitor : SQLParserBaseVisitor<Unit>() {
var tableName = ""
override fun visitCreate_table_statement(ctx: SQLParser.Create_table_statementContext?) {
tableName = ctx?.getChild(1)?.text ?: ""
super.visitCreate_table_statement(ctx)
}
}
Is there a way to find a specific token in the parse tree?
I'm assuming the payload has something to do with it, but since it's of type Any, i'm not sure what to check it against
override fun visitCreate_table_statement(ctx: SQLParser.Create_table_statementContext?) {
ctx?.children?.forEach {
if (it.payload.javaClass == SQLParser::Schema_qualified_nameContext) {
tableName = it.text
}
}
super.visitCreate_table_statement(ctx)
}
EDIT: the .g4 files are from
https://github.com/pgcodekeeper/pgcodekeeper/tree/master/apgdiff/antlr-src
this seems to work
override fun visitCreate_table_statement(ctx: SQLParser.Create_table_statementContext?) {
ctx?.children?.forEach {
if (it.payload.javaClass == Schema_qualified_nameContext::class.java) {
tableName = it.text
}
}
super.visitCreate_table_statement(ctx)
}
For branching trees
fun walkLeaves(
childTree: ParseTree = internalTree,
leave: (childTree: ParseTree) -> Unit) {
if (childTree.childCount == 0) {
if (!childTree.text?.trim().isNullOrBlank()) {
leave(childTree)
}
} else {
for (i in 0 until childTree.childCount) {
walkLeaves(childTree = childTree.getChild(i), leave = leave)
}
}
}
fun extractSQL(
childTree: ParseTree,
tokens: MutableList<String> = mutableListOf()
): String {
walkLeaves(childTree = childTree) { leave ->
tokens.add(leave.text)
}
...
}
SELECT * FROM ReferenceIdentifier WHERE sValue = :sValue and status='ACTIVE
this simple select query taking too mush time
below is my code
#Query("SELECT * FROM ReferenceIdentifier WHERE sValue = :sValue and status='ACTIVE'")
fun getAllReferenceIdentifierBySValue(sValue: String): List<ReferenceIdentifier>
appExecutors.diskIO().execute {
var data = referenceIdentifierDao.getAllReferenceIdentifierBySValue(sValue)
appExecutors.mainThread().execute {
if (data.isNotEmpty()) {
result.value = Resource.success(data)
} else {
result.value = Resource.error("", null)
}
}
}
I'm still learning Ionic and programming in general. I followed a link on the internet and I was able to create the white and read the necessary data, but I am not able to insert data in the created table. Can anyone help me with this?
I follow this tutorial: ionic-sqlite
My code:
getRegiao() { // Regiões //
return new Promise<Regiao[]>((resolve, reject) => {
let sql = "SELECT NOM_REGIAO, ID " +
"FROM TB_REGIAO "
this.executeQuery(sql).then(data => {
let regioes = [];
if (data != undefined)
data.forEach(function (row) {
let regiao: Regiao = { nom_regiao: row[0], id: row[1] }
regioes.push(regiao);
});
resolve(regioes);
}).catch(error => {
console.log(error);
});
});
}
addUser() {
let sql = "INSERT INTO TB_USUARIO (EMAIL) VALUES ('BLITCRANK#HOTMAIL.COM')";
// let sql = "SELECT EMAIL FROM TB_USUARIO";
this.executeQuery(sql);
}
executeQuery(sql: string) {
let db: any;
return new Promise<any>((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', this.dbName, true);
xhr.responseType = 'arraybuffer';
xhr.onload = (e) => {
let uInt8Array = new Uint8Array(xhr.response);
db = new SQL.Database(uInt8Array);
let contents = db.exec(sql);
console.log(contents);
if (contents.length > 0)
resolve(contents[0].values);
else
resolve("query executada sem retorno")
};
xhr.send();
});
}
Please use this plugin , this is the plugin that I am using.
Take note in using execute sql like this db.executeSql('create table danceMoves(name VARCHAR(32))', {})
But rather use this db.executeSql('create table danceMoves(name VARCHAR(32))', [])
I dont know why instead of using object '{}' they replace it as array '[]' I think they forgot to update the documentaion
I have a application which useds TFS JAVA SDK 14.0.3 .
I have a shared query on my tfs , how can i run the shared query and get the response back using TFS SDK 14.0.3
Also I could see that the query url will expire in every 90 days , so any better way to execute the shared query?
Now I have a method to run a query , i want method to run shared query also.
public void getWorkItem(TFSTeamProjectCollection tpc, Project project){
WorkItemClient workItemClient = project.getWorkItemClient();
// Define the WIQL query.
String wiqlQuery = "Select ID, Title,Assigned from WorkItems where (State = 'Active') order by Title";
// Run the query and get the results.
WorkItemCollection workItems = workItemClient.query(wiqlQuery);
System.out.println("Found " + workItems.size() + " work items.");
System.out.println();
// Write out the heading.
System.out.println("ID\tTitle");
// Output the first 20 results of the query, allowing the TFS SDK to
// page
// in data as required
final int maxToPrint = 5;
for (int i = 0; i < workItems.size(); i++) {
if (i >= maxToPrint) {
System.out.println("[...]");
break;
}
WorkItem workItem = workItems.getWorkItem(i);
System.out.println(workItem.getID() + "\t" + workItem.getTitle());
}
}
Shared query is a query which has been run and saved, so what you need should be getting a a shared query, not run a shared query. You could refer to case Access TFS Team Query from Client Object API:
///Handles nested query folders
private static Guid FindQuery(QueryFolder folder, string queryName)
{
foreach (var item in folder)
{
if (item.Name.Equals(queryName, StringComparison.InvariantCultureIgnoreCase))
{
return item.Id;
}
var itemFolder = item as QueryFolder;
if (itemFolder != null)
{
var result = FindQuery(itemFolder, queryName);
if (!result.Equals(Guid.Empty))
{
return result;
}
}
}
return Guid.Empty;
}
static void Main(string[] args)
{
var collectionUri = new Uri("http://TFS/tfs/DefaultCollection");
var server = new TfsTeamProjectCollection(collectionUri);
var workItemStore = server.GetService<WorkItemStore>();
var teamProject = workItemStore.Projects["TeamProjectName"];
var x = teamProject.QueryHierarchy;
var queryId = FindQuery(x, "QueryNameHere");
var queryDefinition = workItemStore.GetQueryDefinition(queryId);
var variables = new Dictionary<string, string>() {{"project", "TeamProjectName"}};
var result = workItemStore.Query(queryDefinition.QueryText,variables);
}
By the way, you could also check the REST API in the following link:
https://learn.microsoft.com/en-us/rest/api/vsts/wit/queries/get
I have the following code, in which I find a resource by its e-mail.
val varn = "x"
val query = createQuery("""SELECT ?${varn}
WHERE { ?x <http://www.w3.org/2001/vcard-rdf/3.0#EMAIL> "${email}" }""")
val qexec = createQueryExecution(ds, query)
val rs = qexec.execSelect()
if (rs.hasNext()) {
val solution = rs.nextSolution()
val rec = solution[varn]
// Here I need to find the value of the property FirstContactTime
}
Now I want to find out whether rec has a property FirstContactTime and if yes, its value.
I tried rec.model.listObjectsOfProperty(ds.defaultModel.createProperty(FirstContactTime)) but it doesn't return anything. The debugger says rec does have a property FirstContactTime.
How can I get the value of FirstContactTime (2017-03-03T10:35:00Z) in my code?
Note that the property in the data is FirstContactDateTime not FirstContactTime.
The SPARQL you're looking for is something like this --
PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#>
PREFIX ex: <http://example.com/schema/person/>
SELECT ?user ?email ?firstcontact
WHERE
{ ?x vcard:EMAIL ?email .
OPTIONAL { ?x ex:firstContactDateTime ?firstcontact }
}