follower_type and followable_type in acts_as_follower gem giving different output in rails console and vs-code terminal - sql

I'm using
gem 'acts_as_follower', github: 'tcocca/acts_as_follower', branch:
'master'
and I have 2 users, user1 is following user2. so, to check wheather user1 is following user2 I'm doing this
u1 = User.find(1) u2 = User.find(2) u1.following?(u2) # should return true
when I run this in rails console it's giving
Follow Count (4.1ms) SELECT COUNT(*) FROM "follows" WHERE "follows"."blocked" = ? AND "follows"."follower_id" = ? AND "follows"."follower_type" = ? AND "follows"."followable_id" = ? AND "follows"."followable_type" = ? [["blocked", 0], ["follower_id", 1], ["follower_type", "User"], ["followable_id", 2], ["followable_type", "User"]]
and in vs-code console it's giving
CACHE Follow Count (0.0ms) SELECT COUNT(*) FROM "follows" WHERE "follows"."blocked" = ? AND "follows"."follower_id" = ? AND "follows"."follower_type" = ? AND "follows"."followable_id" = ? AND "follows"."followable_type" = ? [["blocked", 0], ["follower_id", 1], ["follower_type", "ApplicationRecord"], ["followable_id", 2], ["followable_type", "ApplicationRecord"]]
any solution ?

Related

sqlalchemy join two models, which relate to other 1 model

I'm working on FCM notification and I need to select all my push-tokens from user_notification_tokens table with filtering by other table datetime column, but there is no relation between these two tables, but they have relation with users table.
How can I do it with sqlalchemy?
simplified schema of sqlalchemy models relations:
I've tried to do it like this:
def get_tokens()
db: Session = next(db_service.get_session())
x_minutes_to_event = datetime.now(pytz.utc) + timedelta(minutes=config.MINUTES_TO_PRESCRIPTION)
tokens = [
item[0]
for item in db.query(models.UserNotificationsToken)\
.join(
models.User,
models.User.id == models.UserNotificationsToken.user_id,
)\
.join(
models.UserPrescription,
models.UserPrescription.user_id == models.User.id
)\
.filter(
models.UserPrescription.visiting_at <= x_minutes_to_event,
models.UserPrescription.visiting_at > datetime.now(pytz.utc),
)\
.values(column('token'))
]
# or
tokens = [
item[0]
for item in db.query(models.UserNotificationsToken)\
.join(
models.UserPrescription,
models.UserNotificationsToken.user_id == models.UserPrescription.user_id,
)\
.filter(
models.UserPrescription.visiting_at <= x_minutes_to_event,
models.UserPrescription.visiting_at > datetime.now(pytz.utc),
)\
.values(column('token'))
]
but I got this errors:
sqlalchemy.exc.InvalidRequestError: Don't know how to join to <Mapper at 0x7f0921681fd0; User>. Please use the .select_from() method to establish an explicit left side, as well as providing an explicit ON clause if not present already to help resolve the ambiguity.
# or
sqlalchemy.exc.InvalidRequestError: Don't know how to join to <Mapper at 0x7f54970e4970; UserPrescription>. Please use the .select_from() method to establish an explicit left side, as well as providing an explicit ON clause if not present already to help resolve the ambiguity.
class UserNotificationToken(Base):
__tablename__ = 'user_notification_tokens'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
token = Column(String)
user = relationship('User', back_populates='tokens')
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
tokens = relationship(UserNotificationToken, back_populates='user')
prescriptions = relationship('UserPrescription', back_populates='user')
class UserPrescription(Base):
__tablename__ = 'user_prescriptions'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
visiting_at = Column(DateTime)
user = relationship(User, back_populates='prescriptions')
metadata.create_all(engine)
class Config:
MINUTES_TO_PRESCRIPTION = 60
with Session(engine) as session, session.begin():
now = datetime.now(timezone.utc)
x_minutes_to_event = now + timedelta(minutes=60)
# Example 1 with explicit joins.
query = session.query(
UserNotificationToken.token
).join(
User, UserNotificationToken.user_id == User.id
).join(
UserPrescription, User.id == UserPrescription.user_id
).where(
and_(
UserPrescription.visiting_at <= x_minutes_to_event,
UserPrescription.visiting_at > now))
for (token,) in query.all():
print (token)
# Example 2 with joins inferred from relationships.
query = session.query(
UserNotificationToken.token
).join(
UserNotificationToken.user
).join(
User.prescriptions
).where(
and_(
UserPrescription.visiting_at <= x_minutes_to_event,
UserPrescription.visiting_at > now))
for (token,) in query.all():
print (token)
# Example 3 join directly between tables with user_id FKs, use distinct
query = session.query(
UserNotificationToken.token
).join(
UserPrescription, UserNotificationToken.user_id == UserPrescription.user_id
).where(
and_(
UserPrescription.visiting_at <= x_minutes_to_event,
UserPrescription.visiting_at > now)).distinct()
for (token,) in query.all():
print (token)

Maxima solve function find no solution

I am new to Maxima.
If I do:
solve([x = 2, y = 3], [x, y]);
I get:
[[x = 2, y = 3]]
Which is correct !
If I do:
solve([sin(x) = 1], [x]);
I get:
%pi
[x = ---]
2
Which is also correct !
But if I do:
solve([sin(x) = 1, y = 3], [x, y]);
I get:
[]
Why ?
Thanks for your help.
After load(to_poly_solve); try
to_poly_solve([sin(x)= 1, y = 3], [x,y]);

Syntax error in spatial query?

I wrote a function for found all pois around a track
controller :
def index
#track = Track.friendly.find(params[:track_id])
#tracks = Track.where(way_id: #track.id)
#way = Way.find(1)
#poi_start = Poi.find(#way.point_start)
#pois = #track.pois.sleepsAndtowns
#pois = #way.poi_around_track_from(#poi_start, 50000, #pois)
end
way.rb
def poi_around_track_from(poi, dist, pois)
around_sql = <<-SQL
SELECT
ST_DWithin(
ST_LineSubstring(
way.path,
ST_LineLocatePoint(way.path, pta.lonlat::geometry) + #{dist} / ST_Length(way.path::geography),
ST_LineLocatePoint(way.path, pta.lonlat::geometry) + 100000 / ST_Length(way.path::geography)
),
ptb.lonlat,
2000) is true as pois
FROM ways way, pois pta, pois ptb
WHERE way.id = #{self.id}
and pta.id = #{poi.id}
and ptb.id = #{pois.ids}
SQL
Poi.find_by_sql(around_sql).pois
end
This function return :
syntax error at or near "["
LINE 13: and ptb.id = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
What's wrong, how can I fix it ?
Since you are using standard sql to build the query, (not the ActiveRecord), you will have to use the standard IN clues with where
It looks like pois.ids is returning an array, so, you will have to turn it to a string in the format as below
[1,2] #=> (1,2)
Change,
WHERE way.id = #{self.id}
and pta.id = #{poi.id}
and ptb.id = #{pois.ids}
to
WHERE way.id = #{self.id}
and pta.id = #{poi.id}
and ptb.id IN (#{pois.ids.join(',')})
You can change pois.ids as #semeera207 wrote to string or go another way and compare ptb.id to pois.ids as an array.
WHERE way.id = #{self.id}
and pta.id = #{poi.id}
and array[ptb.id] && #{pois.ids}
To make it faster create gin index
Create index on pois using gin((array[id]));

BigQuery Using arrays in parameterized queries

I need to run parameterized queries using arrays.
Python Client Library for BigQuery API
id_pull = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query = "SELECT column1 FROM `table1` WHERE id = #get_id;"
query_params = [
bigquery.ArrayQueryParameter(
'get_id', 'INT64', id_pull)
]
job_config = bigquery.QueryJobConfig()
job_config.query_parameters = query_params
query_job = client.query(query, location='US', job_config=job_config) #API request-starts query
results = query_job.result() # Waits for job to complete.
I followed instructions from the documentation, however, this error after execution appears:
raise self._exception google.api_core.exceptions.BadRequest: 400 No
matching signature for operator = for argument types: INT64,
ARRAY. Supported signatures: ANY = ANY at [1:67]
Does someone what the problem is and how to fix it?
I think the issue is in your WHERE clause
Instead of
WHERE id = #get_id
it should be something like
WHERE id IN UNNEST(#get_id)

Rails - How to properly escape values in a update_all query

So I have an update_all query that looks like this:
Task.where(...).update_all('position = position - X, parent_id = Y')
I want to replace X and Y with integer values. And I'd like to do it safely: "the rails way".
Any idea of how I can achieve this ?
EDIT: There is no position variable in my rails controller. If X = 1, The final query should literally contain "position=position-1".
Also, The update_all documentation specifies that this method only takes one argument: A string, array, or hash representing the SET part of an SQL statement.
EDIT 2: Alright, I got it working by slightly tweaking Arup Rakshit solution. Here's the final working solution:
Task.update_all(['position = position - ?, parent_id = ?', X, Y])
Write as :
Task.where(...)
.update_all(['position = ?, parent_id = ?', position - X, Y])
Read update_all.
conditions - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro for more info.
Demo:
Loading development environment (Rails 4.2.0)
[1] pry(main)> Person.pluck(:name, :email)
(0.4ms) SELECT "people"."name", "people"."email" FROM "people"
=> [["xxxx", nil], ["xxxx", nil], ["xxxx", nil]]
[3] pry(main)> Person.where(email: nil).update_all ["name = ?, email = ?", "foo", "test#test.com"]
SQL (0.7ms) UPDATE "people" SET name = 'foo', email = 'test#test.com' WHERE "people"."email" IS NULL
=> 3
[4] pry(main)> Person.pluck(:name, :email)
(0.3ms) SELECT "people"."name", "people"."email" FROM "people"
=> [["foo", "test#test.com"], ["foo", "test#test.com"], ["foo", "test#test.com"]]
[5] pry(main)>
Try doing it this way:
Task.where(...).update_all("position = ?, parent_id = ?",position - X, Y )