Skip to main content

Django model describing ChEMBL database.





TL;DR: We have just open sourced our Django ORM Model, which describes the ChEMBL relational database schema. This means you no longer need to write another line of SQL code to interact with ChEMBL database. We think it is pretty cool and we are using it in the ChEMBL group to make our lives easier. Read on to find out more....



It is never a good idea to use SQL code directly in python. Let's see some basic examples explaining why:

import psycopg2
conn=psycopg2.connect("dbname='template1' user='dbuser' password='mypass'")
cur = conn.cursor()
cur.execute("""SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JION Customers
ON Orders.CustomerID=Customers.CustomerID;""")
view raw bad_sql.py hosted with ❤ by GitHub

Can you see what is wrong with the code above? SQL keyword `JOIN` was misspelled as 'JION'. But it's hard to find it quickly because most of code highlighters will apply Python syntax rules and ignore contents of strings. In our case the string is very important as it contains SQL statement.

The problem above can be easily solved using some simple Python SQL wrapper, such as edendb. This wrapper will provide set of functions to perform database operations for example 'select', 'insert', 'delete':

import psycopg2
import edendb
conn=psycopg2.connect("dbname='template1' user='dbuser' password='mypass'")
cur = conn.cursor()
cols = ['name','age','pet']
#insert
db.insert('people', cols, ['paul',102,'cat'])
#delete
db.delete('people', 'age = 10')
#select
rows = db.select(['name','age'], 'people', 'age > 30', iter=True)
view raw edendb.py hosted with ❤ by GitHub

Now it's harder to make a typo in any of SQL keywords because they are exposed to python so IDE should warn you about mistake.

OK, time for something harder, can you find what's wrong here, assuming that this query is executed against chembl_19 schema:

import psycopg2
conn=psycopg2.connect("dbname='template1' user='dbuser' password='mypass'")
cur = conn.cursor()
cur.execute("""SELECT DISTINCT molecule_dictionary.chembl_id,
molecule_synonyms.synonims
FROM molecule_dictionary
LEFT OUTER JOIN molecule_synonyms ON (molecule_dictionary.molregno = molecule_synonims.molregno)
WHERE molecule_dictionary.chembl_id = 'CHEMBL1';""")
view raw schema.py hosted with ❤ by GitHub

Well, there are two errors: first of all `molecule_synonyms` table does not have a `synonims` column. The proper name is `synonyms`. Secondly, there is table name typo  `molecule_synonyms`.

This kind of error is even harder to find because we are dealing with python and SQL code that is syntactically correct. The problem is semantic and in order to find it we need to have a good understanding of the underlying data model, in this case the chembl_19 schema. But the ChEMBL database schema is fairly complicated (341 columns spread over 52 tables), are we really supposed to know it all by heart? Let's leave this rhetorical question and proceed to third example: how to query for compounds containing the substructure represented by 'O=C(Oc1ccccc1C(=O)O)C' SMILES:

For Oracle this would be:

import cx_oracle
conn=cx_oracle.connect("dbname='template1' user='dbuser' password='mypass'")
cur = conn.cursor()
cur.execute("""SELECT *
FROM compound_mols
INNER JOIN molecule_dictionary ON (compound_mols.molregno = molecule_dictionary.molregno)
LEFT OUTER JOIN compound_structures ON (molecule_dictionary.molregno = compound_structures.molregno)
INNER JOIN chembl_id_lookup ON (molecule_dictionary.chembl_id = chembl_id_lookup.chembl_id)
LEFT OUTER JOIN compound_properties ON (molecule_dictionary.molregno = compound_properties.molregno)
WHERE (((sss(ctab,'O=C(Oc1ccccc1C(=O)O)C','ignore=all')=1))
AND compound_structures.molregno IS NOT NULL
AND chembl_id_lookup.entity_type = 'COMPOUND'
AND compound_properties.molregno IS NOT NULL);""")

And for Postgres:

import psycopg2
conn=psycopg2.connect("dbname='template1' user='dbuser' password='mypass'")
cur = conn.cursor()
cur.execute("""SELECT *
FROM rdk.mols
INNER JOIN molecule_dictionary ON (rdk.mols.molregno = molecule_dictionary.molregno)
LEFT OUTER JOIN compound_structures ON (molecule_dictionary.molregno = compound_structures.molregno)
INNER JOIN chembl_id_lookup ON (molecule_dictionary.chembl_id = chembl_id_lookup.chembl_id)
LEFT OUTER JOIN compound_properties ON (molecule_dictionary.molregno = compound_properties.molregno)
WHERE (where m @> 'O=C1OC2=C(C=C1)C1=C(C=CCO1)C=C2'
AND compound_structures.molregno IS NOT NULL
AND chembl_id_lookup.entity_type = 'COMPOUND'
AND compound_properties.molregno IS NOT NULL);""")

As you can see both queries are different, reasons for these differences are:
  1. Differences in Oracle and Postgres dialects
  2. Different chemical cartridges (Accelrys Direct and RDKit)
  3. Different names of auxiliary tables containing binary molecule objects
These queries are also more complicated than the previous examples as they require more table joins and they make calls to the chemical cartridge-specific functions.

The example substructure search queries described above are similar to those used by the ChEMBL web services, which are available on EBI servers (Oracle backend) and in the myChEMBL VM (PostgreSQL backend). Still, the web services work without any change to their code. How?

All of the problems highlighted in this blogpost can be solved by the use of a technique known as Object Relational Mapping (ORM). ORM converts every table from database (for example 'molecule_dictionary') into Python class (MoleculeDictionary). Now it's easy to create a list of all available classes in Python module (by using 'dir' function) and check all available fields in class which corresponds to columns from SQL tables. This makes database programming easier and less error prone. The ORM also allows the code to work in a database agnostic manner and explains how we use the same codebase with Oracle and PostgreSQL backends.

If this blogpost has convinced you to give the ORM approach a try, please take a look at our ChEMBL example also included in myChEMBL:

Comments

Popular posts from this blog

ChEMBL 34 is out!

We are delighted to announce the release of ChEMBL 34, which includes a full update to drug and clinical candidate drug data. This version of the database, prepared on 28/03/2024 contains:         2,431,025 compounds (of which 2,409,270 have mol files)         3,106,257 compound records (non-unique compounds)         20,772,701 activities         1,644,390 assays         15,598 targets         89,892 documents Data can be downloaded from the ChEMBL FTP site:  https://ftp.ebi.ac.uk/pub/databases/chembl/ChEMBLdb/releases/chembl_34/ Please see ChEMBL_34 release notes for full details of all changes in this release:  https://ftp.ebi.ac.uk/pub/databases/chembl/ChEMBLdb/releases/chembl_34/chembl_34_release_notes.txt New Data Sources European Medicines Agency (src_id = 66): European Medicines Agency's data correspond to EMA drugs prior to 20 January 2023 (excluding ...

SureChEMBL gets a facelift

    Dear SureChEMBL users, Over the past year, we’ve introduced several updates to the SureChEMBL platform, focusing on improving functionality while maintaining a clean and intuitive design. Even small changes can have a big impact on your experience, and our goal remains the same: to provide high-quality patent annotation with a simple, effective way to find the data you need. What’s Changed? After careful consideration, we’ve redesigned the landing page to make your navigation smoother and more intuitive. From top to bottom: - Announcements Section: Stay up to date with the latest news and updates directly from this blog. Never miss any update! - Enhanced Search Bar: The main search bar is still your go-to for text searches, still with three pre-filter radio buttons to quickly narrow your results without hassle. - Improved Query Assistant: Our query assistant has been redesigned and upgraded to help you craft more precise queries. It now includes five operator options: E...

Here's a nice Christmas gift - ChEMBL 35 is out!

Use your well-deserved Christmas holidays to spend time with your loved ones and explore the new release of ChEMBL 35!            This fresh release comes with a wealth of new data sets and some new data sources as well. Examples include a total of 14 datasets deposited by by the ASAP ( AI-driven Structure-enabled Antiviral Platform) project, a new NTD data se t by Aberystwyth University on anti-schistosome activity, nine new chemical probe data sets, and seven new data sets for the Chemogenomic library of the EUbOPEN project. We also inlcuded a few new fields that do impr ove the provenance and FAIRness of the data we host in ChEMBL:  1) A CONTACT field has been added to the DOCs table which should contain a contact profile of someone willing to be contacted about details of the dataset (ideally an ORCID ID; up to 3 contacts can be provided). 2) In an effort to provide more detailed information about the source of a deposited dat...

Improvements in SureChEMBL's chemistry search and adoption of RDKit

    Dear SureChEMBL users, If you frequently rely on our "chemistry search" feature, today brings great news! We’ve recently implemented a major update that makes your search experience faster than ever. What's New? Last week, we upgraded our structure search engine by aligning it with the core code base used in ChEMBL . This update allows SureChEMBL to leverage our FPSim2 Python package , returning results in approximately one second. The similarity search relies on 256-bit RDKit -calculated ECFP4 fingerprints, and a single instance requires approximately 1 GB of RAM to run. SureChEMBL’s FPSim2 file is not currently available for download, but we are considering generating it periodicaly and have created it once for you to try in Google Colab ! For substructure searches, we now also use an RDKit -based solution via SubstructLibrary , which returns results several times faster than our previous implementation. Additionally, structure search results are now sorted by...

A python client for accessing ChEMBL web services

Motivation The CheMBL Web Services provide simple reliable programmatic access to the data stored in ChEMBL database. RESTful API approaches are quite easy to master in most languages but still require writing a few lines of code. Additionally, it can be a challenging task to write a nontrivial application using REST without any examples. These factors were the motivation for us to write a small client library for accessing web services from Python. Why Python? We choose this language because Python has become extremely popular (and still growing in use) in scientific applications; there are several Open Source chemical toolkits available in this language, and so the wealth of ChEMBL resources and functionality of those toolkits can be easily combined. Moreover, Python is a very web-friendly language and we wanted to show how easy complex resource acquisition can be expressed in Python. Reinventing the wheel? There are already some libraries providing access to ChEM...