Erlang ets:select sublist - datatables

Is there a way in Erlang to create a select query on ets table, which will get all the elements that contains the searched text?
ets:select(Table,
[{ %% Match spec for select query
{'_', #movie_data{genre = "Drama" ++ '_' , _ = '_'}}, % Match pattern
[], % Guard
['$_'] % Result
}]) ;
This code gives me only the data that started (=prefix) with the required text (text = "Drama"), but the problem is I need also the the results that contain the data, like this example:
#movie_data{genre = "Action, Drama" }
I tried to change the guard to something like that -
{'_', #movie_data{genre = '$1', _='_'}}, [string:str('$1', "Drama") > 0] ...
But the problem is that it isn't a qualified guard expression.
Thanks for the help!!

It's not possible. You need to design your data structure to be searchable by the guard expressions, for example:
-record(movie_data, {genre, name}).
-record(genre, {comedy, drama, action}).
example() ->
Table = ets:new('test', [{keypos,2}]),
ets:insert(Table, #movie_data{name = "Bean",
genre = #genre{comedy = true}}),
ets:insert(Table, #movie_data{name = "Magnolia",
genre = #genre{drama = true}}),
ets:insert(Table, #movie_data{name = "Fight Club",
genre = #genre{drama = true, action = true}}),
ets:select(Table,
[{#movie_data{genre = #genre{drama = true, _ = '_'}, _ = '_'},
[],
['$_']
}]).

Related

Dynamic column search in multiple tables with gorm golang

My scenario is i have a grid with search option where user can select the column and can do the search, the grid data is coming from various tables. I have attached a sample screen of grid.
User Screen
So i'm trying to create a dynamic query for search but the problem is i can able to search only in main table (schema.Robot) not in Preload tables. whenever i trying to search data data from Preload tables let say from RobotModel table that time getting below error
pq: missing FROM-clause entry for table "robot_models"
Here is my go code
func (r *RobotsRepository) GetRobotsSummary(listParams viewmodel.ListParams, companyID uint) ([]*schema.Robot, int, error) {
mrobots := []*schema.Robot{}
var count int
var order string
if listParams.SortColumn == "" {
listParams.SortColumn = "id"
listParams.SortOrder = 1
} else {
listParams.SortColumn = util.Underscore(listParams.SortColumn)
}
if listParams.SortOrder == 0 {
order = "ASC"
} else {
order = "DESC"
}
var searchQuery string
if listParams.SearchText != "" {
switch listParams.SearchColumn {
case "Robot":
listParams.SearchColumn = "name"
case "Model":
listParams.SearchColumn = "robot_models.name"
}
searchQuery = listParams.SearchColumn +" LIKE '%"+ listParams.SearchText +"%' and Company_ID = " + fmt.Sprint(companyID)
}else{
searchQuery = "Company_ID = " + fmt.Sprint(companyID)
}
orderBy := fmt.Sprintf("%s %s", listParams.SortColumn, order)
err := r.Conn.
Preload("RobotModel", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Name")
}).
Preload("Task", func(db *gorm.DB) *gorm.DB {
return db.Where("Task_Status in ('In-Progress','Pending')").Select("ID, Task_Status")
}).
Preload("CreatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Preload("UpdatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Where(searchQuery).
Order(orderBy).
Offset(listParams.PageSize * (listParams.PageNo - 1)).
Limit(listParams.PageSize).
Find(&mrobots).Error
r.Conn.Model(&schema.Robot{}).Where(searchQuery).Count(&count)
return mrobots, count, err
}
In searchQuery variable i'm storing my dynamic query.
My question is how can i search data for preload table columns
Here is the sql query which i'm trying to achieve using gorm
SELECT robots.id,robots.name,robot_models.name as
model_name,count(tasks.task_status) as task_on_hand,
robots.updated_at,users.user_name as updated_by
FROM rfm.robots as robots
left join rfm.tasks as tasks on tasks.robot_id = robots.id and
tasks.task_status in ('In-Progress','Pending')
left join rfm.robot_models as robot_models on robot_models.id =
robots.robot_model_id
left join rfm.users as users on users.id = robots.updated_by
WHERE robot_models.name::varchar like '%RNR%' and robots.deleted_at is null
GROUP BY robots.id,robot_models.name,users.user_name
ORDER BY task_on_hand DESC LIMIT 2 OFFSET 0
and sorry for bad English!
Even though you are preloading, you are still required to explicitly use joins when filtering and ordering on columns on other tables. Preloading is used to eagerly load the data to map into your models, not to join tables.
Chain on something like this:
.Joins("LEFT JOIN rfm.robot_models AS robot_models ON robot_models.id = robots.robot_model_id")
I'm not positive if you can use the AS keyword using this technique, but if not, it should be easy enough to adjust your query accordingly.

Save array in DB when checked more than one checkbox

I have a problem greatest!! I guess that really want Array, look my console when I checked just one:
{"value_solve"=>["", "", "333", ""], "contract_number"=>["33"]}
-----
SQL (317.5ms) UPDATE "authorizations" SET "value_solve" = '', "situation" = 2 WHERE "authorizations"."contract_number" = ? [["contract_number", "33"]]
After, when I checked just one, the first:
{"value_solve"=>["111", "", "", ""], "contract_number"=>["11"]}
-----
SQL (317.5ms) UPDATE "authorizations" SET "value_solve" = '111 ', "situation" = 2 WHERE "authorizations"."contract_number" = ? [["contract_number", "11"]]
And, for last, when I just more then one:
{"contract_number"=>["11", "44"], "value_solve"=>["111", "", "", "444"]}
-----
SQL (297.7ms) UPDATE "authorizations" SET "value_solve" = '111', "situation" = 2 WHERE "authorizations"."contract_number" = ? [["contract_number", "11"]]
SQL (121.9ms) UPDATE "authorizations" SET "value_solve" = '', "situation" = 2 WHERE "authorizations"."contract_number" = ? [["contract_number", "44"]]
And this is my controller:
#selected_ids = params[:authorization][:contract_number]
#authorizations = Authorization.where("contract_number in (?)", #selected_ids)
auth_params = params[:authorization]
auth_params[:contract_number].zip(auth_params[:value_solve]).each do |contract_number, value_solve|
Authorization.where(contract_number: contract_number).update_all(value_solve: value_solve, situation: 2)
end
Just save the first value on DB, how I can save more then one value? Thanks!
As I understood, you want the contract_number with id 44 to be “associated” with value_solve == "444". If this is correct, you should remove blanks from your value_solve array:
auth_params[:contract_number].zip(auth_params[:value_solve].reject(&:blank?))...
Now 44 is being updated with the second element of value_solve, which is apparently an empty string.
See Array#zip for more details.

Node-postgres: named parameters query (nodejs)

I used to name my parameters in my SQL query when preparing it for practical reasons like in php with PDO.
So can I use named parameters with node-postgres module?
For now, I saw many examples and docs on internet showing queries like so:
client.query("SELECT * FROM foo WHERE id = $1 AND color = $2", [22, 'blue']);
But is this also correct?
client.query("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'});
or this
client.query("SELECT * FROM foo WHERE id = ? AND color = ?", [22, 'blue']);
I'm asking this because of the numbered parameter $n that doesn't help me in the case of queries built dynamically.
There is a library for what you are trying to do. Here's how:
var sql = require('yesql').pg
client.query(sql("SELECT * FROM foo WHERE id = :id AND color = :color")({id: 22, color: 'blue'}));
QueryConvert to the rescue. It will take a parameterized sql string and an object and converts it to pg conforming query config.
type QueryReducerArray = [string, any[], number];
export function queryConvert(parameterizedSql: string, params: Dict<any>) {
const [text, values] = Object.entries(params).reduce(
([sql, array, index], [key, value]) => [sql.replace(`:${key}`, `$${index}`), [...array, value], index + 1] as QueryReducerArray,
[parameterizedSql, [], 1] as QueryReducerArray
);
return { text, values };
}
Usage would be as follows:
client.query(queryConvert("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'}));
Not exactly what the OP is asking for. But you could also use:
import SQL from 'sql-template-strings';
client.query(SQL`SELECT * FROM unicorn WHERE color = ${colorName}`)
It uses tag functions in combination with template literals to embed the values
I have been working with nodejs and postgres. I usually execute queries like this:
client.query("DELETE FROM vehiculo WHERE vehiculo_id= $1", [id], function (err, result){ //Delete a record in de db
if(err){
client.end();//Close de data base conection
//Error code here
}
else{
client.end();
//Some code here
}
});

(web2py) add extra fields auth_user that reference another field

I am using Web2py and I would like to add extra fields in the auth_user. some of these fields are reference to other table. for example:
auth.settings.extra_fields['auth_user']= [
Field('country', 'reference countries')]
db.define_table(
'countries',
Field('name'),
format = '%(name)s'
)
but I receive this issue:
cannot resolve reference countries in auth_user definition
can any one help me what should I do? how can I link auth_user table with another table???
All the Best
you need to make sure your db.define_table is created before your the auth tables
like this :
db.define_table('bank',
Field('name'),
format = '%(name)s')
auth.settings.extra_fields['auth_user'] =
[Field('bank', 'reference bank',
label = T('Bank'),
notnull = True,
required = True,
requires = IS_IN_DB(db, db.bank.id, '%(name)s') ),
]
auth.define_tables(username = True, signature = True)
custom_auth_table = db[auth.settings.table_user_name]
auth.settings.table_user = custom_auth_table

Getting greater count result in raven index statistics

I have an index, with a transformation:
docs.FeedPosts
.SelectMany(doc => (doc.Labels).DefaultIfEmpty(), (doc, docLabelsItem1) => new {AnnouncementGuid = doc.AnnouncementGuid, CreationDateUtc = doc.CreationWhenAndWhere.Time, FeedOwner = doc.FeedOwner, Key = doc.Key, Labels_Text = doc.Labels
.Select(label => label.Text), SequentialId = ((long)doc.SequentialId), SubjectGuid = doc.SubjectGuid, SubjectId = doc.SubjectId})
(transform)
results
.Select(doc => new {doc = doc, tags = Database.Load(doc.Key)})
.Select(__h__TransparentIdentifier1 => new {AnnouncementGuid = __h__TransparentIdentifier1.tags.AnnouncementGuid, AreCommentsLocked = __h__TransparentIdentifier1.tags.AreCommentsLocked, Author = __h__TransparentIdentifier1.tags.Author, Comments = __h__TransparentIdentifier1.tags.Comments, CreationWhenAndWhere = __h__TransparentIdentifier1.tags.CreationWhenAndWhere, FeedOwner = __h__TransparentIdentifier1.tags.FeedOwner, Key = __h__TransparentIdentifier1.tags.Key, Labels = __h__TransparentIdentifier1.tags.Labels, MessageBody = __h__TransparentIdentifier1.tags.MessageBody, SequentialId = __h__TransparentIdentifier1.tags.SequentialId, SubjectGuid = __h__TransparentIdentifier1.tags.SubjectGuid, SubjectId = __h__TransparentIdentifier1.tags.SubjectId})
Which works for QUERYING the data. But if I then request statistics, I get back the wrong document count! (I Limit the query to 0 results, and request raven statistics).
It seem that because my document looks like this:
{
Labels: [
{ Text: "label 1" }
{ Text: "label 2" }
]
}
Raven generates TWO index entries for this one document - If I look in the raven query tool, the first index contains the actual index data, the second index document is just completely empty.
If I have 3 labels in a document, it generates 3 index results... and my 'count' is 3 times what it should be.
Whats going on?
Thanks
I translated your index to the query syntax, because that is easier to look at:
from doc in docs.FeedPosts
from NOT_USING_THIS in doc.labels
select new
{
AnnouncementGuid = doc.AnnouncementGuid,
CreationDateUtc = doc.CreationWhenAndWhere.Time,
FeedOwner = doc.FeedOwner,
Key = doc.Key,
Labels_Text = doc.Labels.Select(label => label.Text),
SequentialId = ((long)doc.SequentialId),
SubjectGuid = doc.SubjectGuid,
SubjectId = doc.SubjectId}
}
The second from clause is the SelectMany() in your index, whose value you are not using
If you'll remove that and work on top of the root object, you won't have this issue.
The docs for this are:
http://ravendb.net/docs/faq/skipped-results