Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an index limit in SQLAlchemy

I would like to set up a maximum limit for an index within a Column definition or just through the Index constructor but I don't seem to find a way to achieve it.

Basically, I would like to simulate this MySQL behaviour:

CREATE TABLE some_table (
  id int(11) NOT NULL AUTO_INCREMENT,
  some_text varchar(2048) DEFAULT NULL,
  PRIMARY KEY (id),
  KEY some_text (some_text(1024)), # <- this line
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPRESSED;

In SQLAlchemy I would have something like:

class SomeTable(BaseModel):
  __tablename__ = 'some_table'
  __seqname__ = 'some_table_id_seq'

  id = sa.Column(sa.Integer(11), sa.Sequence(__seqname__), primary_key=True)
  some_text = sa.Column(sa.String(2048), index=True) # <- this line

but I can't find anything that would suggest the limit of the index can be customised. Something like:

some_text = sa.Column(sa.String(2048), index=True, index_length=1024)

I guess since this option for the Column constructor is just an alias for the Index constructor, is there a custom param to include in the Index constructor to allow this setting?

Thanks!

like image 433
eberbis Avatar asked Sep 30 '16 11:09

eberbis


People also ask

What is index in SQLAlchemy?

SQLAlchemy Index is used for assigning the identifiers for each of the particular row getting stored inside a table. We can have indexing based on the single column or collection of two or more columns together acting as an index to the table rows.

Does unique constraint create index?

PRIMARY KEY or UNIQUE constraint When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index.

What does DB Drop_all () do?

You delete everything in the database using the db. drop_all() function to add the tags and post_tag tables safely and to avoid any of the common issues related to adding new tables to a database. Then you create all the tables anew using the db. create_all() function.

What does Create_all do in SQLAlchemy?

Sqlalchemy create_all method is used to create a new table into the database. This method will first check whether the table exists in the database or not if suppose it has found an existing table it will not create any table.


1 Answers

I think you can do something like:

class SomeTable(BaseModel):
  __tablename__ = 'some_table'
  __seqname__ = 'some_table_id_seq'
  __table_args__ = (
      sa.Index("idx_some_text", "some_text", mysql_length=1024),
  )
  id = sa.Column(sa.Integer(11), sa.Sequence(__seqname__), primary_key=True)
  some_text = sa.Column(sa.String(2048))

Reference: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#index-length

like image 89
pcalessio Avatar answered Sep 25 '22 15:09

pcalessio