SQLAlchemy Generator¶
BESSER provides a code generator that creates SQLAlchemy models to define the structure of a relational database. This structure (known as Declarative Mapping) defines the database metadata (using a Python object model) that will represent the input structural B-UML model.
Now, let’s generate the code for SQLAlchemy of our Structural model example.
For this, you should create the generator, provide the Structural model, and use
the generate method as follows:
from besser.generators.sql_alchemy import SQLAlchemyGenerator
generator: SQLAlchemyGenerator = SQLAlchemyGenerator(model=library_model)
generator.generate(dbms="sqlite")
The dbms parameter specifies the target database management system.
In this example, we use sqlite, but you can also specify postgresql, mysql, mssql, mariadb, or oracle.
Generated Output¶
The sql_alchemy.py file will be generated inside the <<current_directory>>/output
folder and it will look as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
Creating the Database¶
The generated code contains the SQLAlchemy classes that represent the database metadata. If you are using SQLite as DBMS, you can create the database and the tables by running the file as follows:
python sql_alchemy.py
This will create a SQLite database named Librarymodel.db in the same directory where the file is executed. The database
looks like this:
Note
Note that for DBMS different to SQLite, such as postgresql or mysql, you should change the connection string in the
generated code, providing the necessary information to connect to the database: username, password, host, port, and database name.
Warning
By default, inheritance is implemented using the Joined Table Inheritance. Other strategies like Concrete Table Inheritance is implemented only when you mark a parent class as abstract in the B-UML model, but there are limitations in Concrete inheritance, for example: the definition of relationships involving abstract classes are not supported. So only if the abstract class does not have relationships, it will be treated as a concrete parent class, otherwise, it will be treated as a parent class using Joined Table Inheritance.