Hardcoded Query in PetaPoco ORM - asp.net-mvc

We are planning to use PetaPoco in our project. As it is tiny ORM with performance benefit, one of the thing worried me a lot is hard coded queries.
Due to that, whenever our column changes (added/removed), we have issue to find out same in all the queries.
Can we generate Columnname in tt file and use that in place of hard coded query something like:
"Select * from " + Tables.Customer + " Where " + CustomerTable.CustomerId + " = 1"

Related

Adwords Scripts - access keywords search terms

I'm trying to access the keywords search terms report, and apply query on it by "Add/Exclude" column, cost, etc.
Couldn't find it in the docs, there is any way to get the report?
Thanks
Edit:
There is an existing option to save to search report and scheduled it, so if there is a chance to access the reports sections it would be great either.
Take a look at this solution.
You're able to acquire the data from the search query report through an AWQL query. Example as used in the linked solution:
var report = AdWordsApp.report(
"SELECT Query,Clicks,Cost,Ctr,ConversionRate,CostPerConversion,Conversions,CampaignId,AdGroupId " +
" FROM SEARCH_QUERY_PERFORMANCE_REPORT " +
" WHERE " +
" Conversions > 0" +
" AND Impressions > " + IMPRESSIONS_THRESHOLD +
" AND AverageCpc > " + AVERAGE_CPC_THRESHOLD +
" DURING LAST_7_DAYS");

How to use Dependency Injection when developing Stored Procedures?

In database Stored Procedures are often used to handle business logic. (There is a debate that where the logic should be, but it's not the topic here)
When more and more SP are written, the system becomes very complex. The main reason I think is the dependencies (SP1 depends on SP2, SP2 depends on SP3 ...)
In OO world, there is the Dependency Injection pattern and also many IoC containers (such as Spring) to solve the dependency problem.
In SP world, can this patten be applied? How? Any tools?
Dependency injection mostly makes sense in an environment that supports polymorphism: you have an interface which can have one of many implementations, and you offload the discovery of proper implementation to a certain framework.
In SQL, there is no distance between Stored Procedure interface and its implementation -- you define the interface with the procedure. It is hard to think of a case when you actually define multiple procedures as interchangeable within a common signature.
Practically speaking, for dependency injection you would also need some key to tell the system what is it that you want to have injected. In OOP languages, very often the interface is a key. But you probably do not want SP signature as a key. And if you look up procedure by name, then how is it different from just executing it directly?
There is a reason why OOP exists and why it is a popular way to manage complexity. Dependency injection builds upon its core concepts and does not seem to be well-applicable to procedural environment.
Although it's not recommended. There is a way to use Dependency Injection in a SQL environment (with stored procedures, functions, views, and even tables). It involves a lot of Dynamic SQL, Triggers, and gets very messy after a while. But, just for the sake of answering the question, here goes:
First, you have to decide what kind of dependency you are injecting, and how it is accessed. Let's say, for this example, it is a Company ID, and you want to execute different objects based on the company, while remaining agnostic in higher-level procedures and follow D.R.Y (don't-repeat-yourself).
So you need a way to store this company ID in a way that can always be retrievable regardless of where you are and what is passed in. You don't want to always have to pass in the Company ID to the SQL object, so you use CONTEXT_INFO. This is a value that is constant through a thread, and is unique to that thread.
SET #Context = CAST(15 AS VARBINARY(128))
SET CONTEXT_INFO #Context;
Now you can access the context like this:
SELECT #Context = CONTEXT_INFO();
SET #CompanyID = CAST(#Context AS INT)
Are you with me so far?
This is where it starts to get really messy.
Create a table for yourself with the names of the company-specific objects.
CREATE TABLE CompanyObjectRegistry (ObjectSchema VARCHAR(100), ObjectName VARCHAR(100), CompanyID)
Store your objects here:
INSERT CompanyObjectRegistry
VALUES ('CompanyFifteen', 'DoSomethingCool', 15),
('CompanyTwelve', 'DoSomethingCool', 12);
Then you create the top-level procedure:
CREATE PROCEDURE DoSomethingCool (#Data VARCHAR(10), #Param2 INT)
AS
DECLARE #CompanyID INT = CAST(CONTEXT_INFO() AS INT),
#SQL NVARCHAR(MAX) = '
EXEC [SCHEMA].DoSomethingCool ''' + #Data + ''', '
+ CAST(Param2 AS VARCHAR(10)) + ';'
SET
SELECT #SQL = REPLACE(#SQL, '[SCHEMA]', ObjectSchema)
FROM CompanyObjectRegistry
WHERE CompanyID = #CompanyID
EXEC(#SQL)
This has a small overhead because of the DSQL, and the fact that it can't be compiled. You can remove some of this overhead by using a "generate" procedure which generates this "base" procedure automatically from the contents of CompanyObjectRegistry and uses IF statements.
If you need to, you can have a trigger add to CompanyObjectRegistry and generate the base object when one of the underlying objects is edited/added. You would use a DDL trigger for this.
Here's how you would do this for tables:
DECLARE #TableName VARCHAR(100) = 'DoSomethingCool';
SET #SQL = 'CREATE VIEW ' + #TableName + ' AS '
+ (SELECT '
SELECT * FROM ' + ObjectSchema + '.' + ObjectName + '
WHERE ' + CAST(CompanyID AS VARCHAR(10)) + ' = #CompanyID
UNION ALL ' -- You would have to remove the last 10 characters from the result
FROM CompanyObjectRegistry
WHERE ObjectName = #TableName
FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)')
EXEC (#SQL)
Views can be injected in the same way, just select * from each view.
Functions are very hard to do because you can't do either of the above approaches. You have to use the header of the function and generate the body.
It will take a lot of time. So if you have a choice... don't.

How to QUERY Neo4J using .NET Client WithParms instead of injections?

I want to avoid using injection of parms in the query statement. Therefore we used the following instructions from the NEO4J .NET client class:
var queryClassRelationshipsNodes = client.Cypher
.Start("a", (NodeReference)sourceReference.Id)
.Match("a-[Rel: ***{relationshipType***} ]->foundClass")
.Where("Rel.RelationStartNode =" + "\'" + relationshipStart + "\'")
.AndWhere("Rel.RelationDomainNode =" + "\'" + relationshipDomain + "\'")
.AndWhere("Rel.RelationClassNode =" + "\'" + relationshipClass + "\'")
.WithParam("relationshipType", relationshipType)
.Return<Node<Dictionary<string, string>>>("foundClass")
.Results;
However this code does not work once executed by the server. For some reason the PARM: relationshipType is not connected with the variable which we put in between {}.
Can someone please help us debug the problem with this code? We would prefer to use WithParms rather than injecting variables inside the statement.
Thanks a lot!
Can someone please help us debug the problem with this code?
There's a section on https://bitbucket.org/Readify/neo4jclient/wiki/cypher titled "Debugging" which describes how to do this.
As for your core problem though, your approach is hitting a Cypher restriction. Parameters are for parts of the query that aren't compiled into the query plan. The match clause is however.
From the Neo4j documentation:
Parameters can be used for literals and expressions in the WHERE clause, for the index key and index value in the START clause, index queries, and finally for node/relationship ids. Parameters can not be used as for property names, since property notation is part of query structure that is compiled into a query plan.
You could do something like:
.Match("a-[Rel:]->foundClass")
.Where("type(Rel) = {relationshipType}")
.WithParam("relationshipType", relationshipType)
(Disclaimer: I've just typed that here. I haven't tested it at all.)
That will likely be slower though, because you need to retrieve all relationships, then test their types. You should test this. There's a reason why the match clause is compiled into the query plan.

How to count tag-to-tag relationships without having it explode?

I'm using neo4j, storing a simple "content has-many tags" data structure.
I'd like to find out "what tags co-exist with what other tags the most?"
I've got around 500K content-to-tag relationships, so unfortunately, that works out to 0.5M^2 posible coexist relationships, and then you need to count how many each type of relationship happens! Or do you? Am I doing this the long way?
It never seems to return, and my CPU is pegged out for quite some time now.
final ExecutionResult result = engine.execute(
"START metag=node(*)\n"
+ "MATCH metag<-[:HAS_TAG]-content-[:HAS_TAG]->othertag\n"
+ "WHERE metag.name>othertag.name\n"
+ "RETURN metag.name, othertag.name, count(content)\n"
+ "ORDER BY count(content) DESC");
for (Map<String, Object> row : result) {
System.out.println(row.get("metag.name") + "\t" + row.get("othertag.name") + "\t" + row.get("count(content)"));
}
You should try to decrease your bound points to make the traversal faster. I assume your graph will always have more tags than content so you should make the content your bound points. Something like
start
content = node:node_auto_index(' type:"CONTENT" ')
match
metatag<-[:HAS_CONTENT]-content-[:HAS_CONTENT]->othertag
where
metatag<>othertag
return
metatag.name, othertag.name, count(content)

Concatenating two fields in a collect

Rails 2.3.5
I'm not having any luck searching for an answer on this. I know I could just write out a manual sql statement with a concat in it, but I thought I'd ask:
To load a select, I'm running a query of shift records. I'm trying to make the value in the select be shift date followed by a space and then the shift name. I can't figure out the syntax for doing a concat of two fields in a collect. The Ruby docs make it looks like plus signs and double quotes should work in a collect but everything I try gets a "expected numeric" error from Rails.
#shift_list = [a find query].collect{|s| [s.shift_date + " " + s.shift_name, s.id]}
Thanks for any help - much appreciated.
Hard to say without knowing what s is going to be or what type s.shift_date and s.shift_name are but maybe you're looking for this:
collect{|s| ["#{s.shift_date} #{s.shift_name}", s.id]}
That is pretty much the same as:
collect{|s| [s.shift_date.to_s + ' ' + s.shift_name.to_s, s.id]}
but less noisy.

Resources