SQLAlchemy not converting column with __ character correctly - sqlalchemy

I am trying to query a bigquery dataset with SQLAlchemy in a web application written with Django. The table name is TestBillingAcctLkp and it has a particular column __of_projects (two underscores in front)
I have defined the model object like this:
class TestBillingAcctLkp(Base):
__tablename__ = 'TestBillingAcctLkp'
Billing_account_name = Column(String)
Billing_account_ID = Column(String,primary_key=True)
Parent_account_ID=Column(String)
Status=Column(String)
__of_projects=Column(Integer)
In the views, I use this:
session.query(TestBillingAcctLkp).order_by(text("Billing_account_name asc")).all()
When I query I get the SQL like this:
SELECT `TestBillingAcctLkp`.`Billing_account_name` AS `TestBillingAcctLkp_Billing_account_name`, `TestBillingAcctLkp`.`Billing_account_ID` AS `TestBillingAcctLkp_Billing_account_ID`, `TestBillingAcctLkp`.`Parent_account_ID` AS `TestBillingAcctLkp_Parent_account_ID`, `TestBillingAcctLkp`.`Status` AS `TestBillingAcctLkp_Status`, `TestBillingAcctLkp`.`_TestBillingAcctLkp__of_projects` AS `TestBillingAcctLkp__TestBillingAcctLkp__of_projects` FROM `TestBillingAcctLkp` ORDER BY Billing_account_name asc
I observe that _TestBillingAcctLkp is getting appended to the front of this column __of_projects and it becomes _TestBillingAcctLkp__of_projects in the SQL query translation therefore I get this error:
Exception : (google.cloud.bigquery.dbapi.exceptions.DatabaseError) 400 Name _TestBillingAcctLkp__of_projects not found inside TestBillingAcctLkp at
How can I resolve this?

By default Python will combine class variables with two leading underscores with the class name - this is known as name mangling.
If the column in the database has two leading underscores you can specify it in the column definition, and assign the class variable to a name without leading underscores.
class TestBillingAcctLkp(Base):
__tablename__ = 'TestBillingAcctLkp'
...
of_projects=Column('__of_projects', Integer)

Related

Using MySQL REGEXP to filter string with Django ORM

I have a model which have FileField field and in this model we have millions of records.
class MyModel(models.Model):
media = models.FileField(upload_to=my_function, db_index=True)
...
These media records are stored in database like;
media/some/folder/filename.jpg
media/filename.jpg
media/2021091240-10328.JPG
media/aXay-123.jpeg
media/some/another/folder/202110-12-12.jpeg
etc. and I need to find records which are not have nested path like /some/folder/ or /some/another/folder/ with django orm __iregex lookup.
So, I tried something like;
MyModel.objects.filter(media__iregex=r"^media/[0-9a-zA-Z\-][.][a-zA-Z]")
but it does not match and I do not understand to write proper regex [mysql regexp].
How can I do filter with mysql regexp with using Django orm to get records with only have pattern like; media/filename.extension?
Your regex has no quantifier, and thus will pick exactly one character for the [0-Aa-zA-Z\-] character group.
You can simply filter out elements that contain at least two slashes with:
MyModel.objects.filter(media__iregex=r'^media/[^/]+$')

How to check a string is matching with 2 columns in database - Laravel

Am working on a scenario, where I want to search for a string value from URL is matching 2 columns from the database. For example.. in my project system, there is customer first_name and last_name is there while entering web URL like website.com/nayanachandran
the word "nayanachandran" has to check from the customer database, with laravel queries like the combination of customer first_name and last_name is equal to the string in request param.
currently, I did it in a way like added hi-pen in string
eg: nayana-chandran
and while searching I added query in the repository like:
$publicUrl = explode("-",$this->request->unique_name);
$coach_details = Customer::where('first_name', $publicUrl['0'])->where('last_name', $publicUrl['1'])->first();
Any help ?
It sounds like you're asking how you can take a concatenated string from the url, nayanachandran, and search for that in your DB as a combination of the columns first_name and last_name.
Assuming that's the case, you can use a combination of whereRaw and CONCAT:
Customer::whereRaw("CONCAT(first_name, last_name) = ?", [$this->request->unique_name])->first();
Alright, so a way to do this would be to:
$publicUrl = explode('-', $this->request->unique_name);
list($firstName, $lastName) = $publicUrl;
Which indeed creates an array from the string delimited by '-', and then simply do a:
Customer::where([['first_name', $firstName],['last_name', $lastName]])->first();
Which will return you the Customer object related to that condition.
However, let me recommend you to use query strings instead, and simply have an address like:
https://address.com/example?first_name=james&last_name=smith
Which would render the explode unnecessary since you could access those values directly from the request object:
Customer::where([['first_name', request()->get('first_name')],['last_name', request()->get('last_name')]])->first();

What are the cons of using mysql's reserved keywords as fields with django?

I have a Django model as:
Class DataFile(models.Model):
file = models.FileField(upload_to=get_file_upload_path)
But, file is a reserved keyword in MySQL.
I know that we can use any reserved keyword as column name by wrapping it in ``.
My senior advised me not to use reserved keywords and use something which is nearly meaningful other than just file.
What are the cons?
But, file is a reserved keyword in MySQL.
That is not a problem when you use Django. You can use the db_column=… parameter [Django-doc] to use a different name at the database level.
For example:
class DataFile(models.Model):
file = models.FileField(upload_to=get_file_upload_path, db_column='filepath')
So now you can access the field at the Django level with my_data_file.file, but at the database side, the column is named filepath. Django will make thus queries to the filepath column.

How do I capitalize all text in a column of data in an Access Query while keeping the name of the field the same?

How do I capitalize all text in a column of data in an Access Query while keeping the name of the field the same?
I tried entering "SPEC: StrConv([SPEC],3), but I get an error that I have a circular argument (which, isn't too surprising). So how do I get around this?
Is there a totally different approach to capitalizing in queries?
Given: we have a field named [SPEC].
Problem: need query to grab [SPEC] and convert it to all caps, but
with the same field name
Added: We will call the table that holds the field [SPEC],
[tblTable]
Solution:
What we need to put in the query builder is the following:
SPEC: UCase([tblTable].[SPEC])
That way the machine can figure out that Query.SPEC isn't the same identifier as tblTable.SPEC
Equivalently:
SELECT UCase([tblNames].[FirstName]) AS FirstName
FROM tblNames;
How about using the Ucase function
Ucase(String)

Rails table name contains digits

Is it possible to use a table in rails that contains digits in its name?
I have a table named photo_2014_hierarchies
Its model is saved as photo_2014_hierarchy.rb
and inside I use
class Photo2014Hierarchy < ActiveRecord::Base
which works for other tables in this db
however when I try to use this table in a controller I get
NameError: uninitialized constant Photo2014Hierarchy
The reason why this is not working is the detection of word boundaries in the underscore method:
> "Photo2014Hierarchy".underscore
=> "photo2014_hierarchy"
As you can see, the number is not considered a word to be divided by underscores. In your case this means that your file has to be named photo2014_hierarchy.rb and your table photo2014_hierarchies.
Note: table_name is only required if you can't change the table name accordingly as Rails knows how to pluralize hierarchy.
> "Photo2014Hierarchy".pluralize.underscore
=> "photo2014_hierarchies"
It's possible, yes. I wouldn't go creating dirty model names, but instead consider using table_name in your models if you're having to work with a legacy naming convention.