Rails table name contains digits - mysql

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.

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/[^/]+$')

SQLAlchemy not converting column with __ character correctly

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)

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.

Characters between angle brackets (<>) stripped out in database?

I want to store mysql regular epxression to mysql database field. Specifically I want to store word boundaries expression into the database. For example:
[[:<:]]my expression here[[:>:]]
If I put this value directly into the database (for example using Sequel Pro) the value is stored correctly.
Problem occur when I want to store this value through Ruby on Rails:
my_instance.sql_expression = "[[:<:]]my expression here[[:>:]]"
my_instance.save
=> true
But value that is actually stored to database looks like this:
my_instance.sql_expression
=> "[[::]]"
It seems that in string Rails ignore everything what is between "<" and ">" including signs itselfs.
The project is in Ruby 1.8.7 and Rails 2.3.5.
This sounds like you're using something like xss_terminate to filter your models before saving them. I'd look in your model definition for something which has a before_save or other hook that might be intrusively doing this.
This is not standard Rails behavior.

Django: How to use float precision instead of double precision in MySQL

models.FloatField creates a double in MySQL.
Is it possible, and how, to create a float precision field instead of double precision?
The justification is similar to that of having SmallIntegerField.
Well there is a better way than that and a much easier one. I also wanted the same thing with my db, when I came across the following db_type() method in django.
First, you need to create a custom Field in django by inheriting the Field class
class customFloatField(models.Field):
def db_type(self,connection):
return 'float'
then you could use this as any other model field in your model class
number = customFloatField(null=True,blank=True)
I tried and this does work for me in MySQL. To change it as per the connection type, you would have to check the connection setting in an if statement and change accordingly.
More about this is mentioned in https://docs.djangoproject.com/en/dev/howto/custom-model-fields/
There are a few options to do this, but I don't understand why you would want to.
Change it in the database, won't work when recreating the tables but Django won't do a manual cast so if the database changes, so do the results.
Create a custom fieldtype (i.e. inherit FloatField and change get_internal_type() so it returns something like SinglePrecisionFloatField. After that you will also need to create your own database backend and add your custom type to creation.DatabaseCreation.data_types (source: http://code.djangoproject.com/browser/django/trunk/django/db/backends/mysql/creation.py)
Change every FloatField to single precision. Like above you would have to create your own database backend and/or change the FloatField implementation in the current one.