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_dialect="sqlite")
generator.generate()
Parameters¶
model: The input B-UML structural model.sql_dialect: The target SQL dialect for the generated statements (default:"sqlite").output_dir: Optional output directory (default:output/in the current directory).
Supported Dialects¶
Dialect |
Description |
|---|---|
|
Default. Generates SQLite-compatible DDL statements. |
|
PostgreSQL DDL with |
|
MySQL DDL with |
|
Microsoft SQL Server DDL. |
|
MariaDB DDL (similar to MySQL). |
|
Oracle DDL with |
The generator handles enumeration types differently depending on the dialect: PostgreSQL
uses CREATE TYPE ... AS ENUM, MySQL/MariaDB use inline ENUM() column types, and
Oracle uses CHECK constraints.
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;