SQL Schema Generator#
The SQL generator produces the code or set of SQL statements used to define and modify the structure of the tables in a database.
Let’s generate the SQL code of our Structural model example structural model example. You should create a
SQLGenerator
object, provide the Structural model, and use the generate
method as follows:
from besser.generators.sql import SQLGenerator
generator: SQLGenerator = SQLGenerator(model=library_model)
generator.generate()
The tables.sql
file with the SQL statements will be generated in the <<current_directory>>/output
folder and it will look as follows.
1CREATE TABLE IF NOT EXISTS Book (
2 Book_id SERIAL PRIMARY KEY,
3 pages int,
4 release timestamp,
5 title varchar(100)
6);
7
8CREATE TABLE IF NOT EXISTS Author (
9 Author_id SERIAL PRIMARY KEY,
10 name varchar(100),
11 email varchar(100)
12);
13
14CREATE TABLE IF NOT EXISTS Library (
15 Library_id SERIAL PRIMARY KEY,
16 address varchar(100),
17 name varchar(100)
18);
19
20CREATE TABLE IF NOT EXISTS Author_Book (
21 Author_id INT REFERENCES Author(Author_id),
22 Book_id INT REFERENCES Book(Book_id),
23 PRIMARY KEY (Author_id, Book_id)
24);
25
26ALTER TABLE Book
27ADD COLUMN Library_id INT REFERENCES Library(Library_id);
If you want to use this generator for technology-specific SQL commands such as PostgreSQL, you can use the sql_dialects
parameter in the SQLGenerator
. Currently only postgres
and mysql
are valid values. For example:
from besser.generators.sql import SQLGenerator
generator: SQLGenerator = SQLGenerator(model=library_model, sql_dialects="postgres")
generator.generate()