query with like clause in scalikejdbc - scalikejdbc

Can anyone please give me a example for how to use like clause in scalikejdbc with dynamic value. I used following query but it did not work
sql"select * from tables_list where lower(TABLE_NAME) like '%$tableName.toLowerCase%'"

scalikejdbc build in prevent sql injection, therefore when you type like '%$tableName.toLowerCase%', it appear as like '%'urValue'%', hence error occur.
I found a way to go ground it, which is
def search(name:String){
val searchName = s"%$name%"
DB readOnly{ implicit session =>
sql"select * from db where name like $searchName".map
...
...
}
I hope this can help you.

Related

SQLALchemy - cannot reflect a SQL Server DB running on Amazon RDS

My code is simple:
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
db.metadata.reflect()
And it throws no errors. However, when I inspect the metadata after this reflection, it returns an empty immutabledict object.
The parameters in my connection string is 100% correct and the code works with non-RDS databases.
It seems to happen to others as well but I can't find a solution.
Also, I have tried to limit the reflection to specific tables using the "only" parameter in the metadata.reflect function, and this is the error I get:
sqlalchemy.exc.InvalidRequestError: Could not reflect: requested table(s) not available in mssql+pyodbc://{connection_string}: (users)
I've fixed it. The reflect() method of the SQLAlchemy class has a parameter named 'schema'. Setting this parameter, to "dbo" in my case, solved it.
I am using Flask-SQLAlchemy, which does not have the said parameter in its reflect() method. You can follow this post to gain access to that parameter and others, such as 'only'.
This error occurs when reflect is called without the schema name provided. For example, this will cause the error to happen:
metadata.reflect(only = [tableName])
It needs to be updated to use the schema of the table you are trying to reflect over like this:
metadata.reflect(schema=schemaName, only = [tableName])
You have to set schema='dbo' in parameter for reflect.
db.Model.metadata.reflect(bind=engine, schema='dbo', only=['User'])
and then create model of your table:
class User(db.Model):
__table__ = Base.metadata.tables['dbo.User']
and to access data from that table:

Difference between Laravel DB::insert() and DB::table()->insert()

I've been trying to figure out which one to use when, and if I should even use both.
Been looking at Laravel docs and they have both in there. From what I can make out of it, DB::insert() provides more "tailored" query than DB::table()->insert() does.
Would anyone be able to clarify what exactly the difference is in the two when it comes to how and when to use which?
DB::insert() for raw sql queries. Example:
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
DB::table()->insert() for query builder. Example:
DB::table('users')->insert(
['email' => 'john#example.com', 'votes' => 0]
);
Query builder compiles conditions to raw sql query, but I am using it because it is much more convenient.
You always try to use query builder as much as possible, it prevents SQL injection.
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings
Query Builder also helps with special chars such as ', " in values. For raw statement, you need to take care of the special chars yourself.
public function addsubEmployee(Request $reqest){
Sub_employee::create([
"se_name"=> $reqest->se_name,
]);
return redirect()->route("subEmployee");
}

Simple.Data LIKE Operator in Where

How can we use LIKE operator in WHEREusing Simple.Data for SQL Server in ASP.Net C#
I need to run this SQL Query
SELECT MAX(regid) FROM reg_course WHERE(regid LIKE '%2013%')
Finally I achieved this task by aliasing the max(regid) column and querying in this fashion.
var cid=db.course_test.All()
.Select(db.course_test.regid.Max().As("maxcourseid"))
.Where(db.course_test.regid.Like(string.Concat("%",DateTime.Now.Year,"%")))
.FirstOrDefault();
Note
cid=db.course_test.All()
.Select(db.course_test.regid.Max().As("maxcourseid"))
.Where(db.course_test.regid.Like(string.Concat("%",DateTime.Now.Year,"%")))
returns the type Simple.Data.SqlQuery
Using FirstOrDefault returns Top result. If you don't want you can iterate in collection without using FirstOrDefault
Any other Better way Suggestions??

Rails 3, ActiveRecord, PostgreSQL - ".uniq" command doesn't work?

I have following query:
Article.joins(:themes => [:users]).where(["articles.user_id != ?", current_user.id]).order("Random()").limit(15).uniq
and gives me the error
PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...s"."user_id" WHERE (articles.user_id != 1) ORDER BY Random() L...
When I update the original query to
Article.joins(:themes => [:users]).where(["articles.user_id != ?", current_user.id]).order("Random()").limit(15)#.uniq
so the error is gone... In MySQL .uniq works, in PostgreSQL not. Exist any alternative?
As the error states for SELECT DISTINCT, ORDER BY expressions must appear in select list.
Therefore, you must explicitly select for the clause you are ordering by.
Here is an example, it is similar to your case but generalize a bit.
Article.select('articles.*, RANDOM()')
.joins(:users)
.where(:column => 'whatever')
.order('Random()')
.uniq
.limit(15)
So, explicitly include your ORDER BY clause (in this case RANDOM()) using .select(). As shown above, in order for your query to return the Article attributes, you must explicitly select them also.
I hope this helps; good luck
Just to enrich the thread with more examples, in case you have nested relations in the query, you can try with the following statement.
Person.find(params[:id]).cars.select('cars.*, lower(cars.name)').order("lower(cars.name) ASC")
In the given example, you're asking all the cars for a given person, ordered by model name (Audi, Ferrari, Porsche)
I don't think this is a better way, but may help to address this kind of situation thinking in objects and collections, instead of a relational (Database) way.
Thanks!
I assume that the .uniq method is translated to a DISTINCT clause on the SQL. PostgreSQL is picky (pickier than MySQL) -- all fields in the select list when using DISTINCT must be present in the ORDER_BY (and GROUP_BY) clauses.
It's a little unclear what you are attempting to do (a random ordering?). In addition to posting the full SQL sent, if you could explain your objective, that might be helpful in finding an alternative.
I just upgraded my 100% working and tested application from 3.1.1 to 3.2.7 and now have this same PG::Error.
I am using Cancan...
#users = User.accessible_by(current_ability).order('lname asc').uniq
Removing the .uniq solves the problem and it was not necessary anyway for this simple query.
Still looking through the change notes between 3.1.1 and 3.2.7 to see what caused this to break.

How to write a query like SQL's SELECT x FROM

I want to write a query that does something like this SQL query:
SELECT name FROM contacts WHERE blah blah
I know I can do something like this:
for contact in Contacts.gql(WHERE_CLAUSE, args).fetch(1000):
print contact.name
but isn't there a way to get name directly from a query without having to loop on the results? would it provide any advantage in performance?
Nope. Can't be done.
A GQL query returns zero or more entities or Keys of the requested
kind. Every GQL query always begins with either SELECT * or SELECT
key. (A GQL query cannot perform a SQL-like "join" query.)
http://code.google.com/appengine/docs/python/datastore/gqlreference.html
But you can create a simple wrapper to do it for you. Something like:
def get_all_of_field(model, field):
for x in model.all():
yield getattr(x, field)
names = get_all_of_field(Contact, 'name')
Performance can't be improved that way as the entire "line" is read by the API no matter what. Either you read the entire "line" or just its key.
You can do this now using Projection queries. For db, see the documentation here:
https://developers.google.com/appengine/docs/python/datastore/projectionqueries
For ndb, see the documentation here:
https://developers.google.com/appengine/docs/python/ndb/queries#projection

Resources