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 for the 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, sql_dialects="sqlite")
generator.generate()

The model parameter specifies the input B-UML structural model, while the sql_dialects parameter specifies the target SQL dialect for the generated statements. In this example, we use sqlite, but you can also specify postgres, mysql, mssql, or mariadb.

Output#

The generated SQL script, tables_sqlite.sql, will be saved in the output/ folder inside your current working directory. You can customize the output directory by setting the output_dir parameter in the generator (see the API docs for details). The generated output for this example is shown below.

 1CREATE TABLE author (
 2	id INTEGER NOT NULL, 
 3	name VARCHAR(100) NOT NULL, 
 4	email VARCHAR(100) NOT NULL, 
 5	PRIMARY KEY (id)
 6)
 7
 8;
 9
10
11CREATE TABLE library (
12	id INTEGER NOT NULL, 
13	name VARCHAR(100) NOT NULL, 
14	address VARCHAR(100) NOT NULL, 
15	PRIMARY KEY (id)
16)
17
18;
19
20
21CREATE TABLE book (
22	id INTEGER NOT NULL, 
23	title VARCHAR(100) NOT NULL, 
24	pages INTEGER NOT NULL, 
25	release DATE NOT NULL, 
26	"locatedIn_id" INTEGER NOT NULL, 
27	PRIMARY KEY (id), 
28	FOREIGN KEY("locatedIn_id") REFERENCES library (id)
29)
30
31;
32
33
34CREATE TABLE book_author_assoc (
35	"writtenBy" INTEGER NOT NULL, 
36	publishes INTEGER NOT NULL, 
37	PRIMARY KEY ("writtenBy", publishes), 
38	FOREIGN KEY("writtenBy") REFERENCES author (id), 
39	FOREIGN KEY(publishes) REFERENCES book (id)
40)
41
42;