test-db-builder-python 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import (
4
+ ABC,
5
+ abstractmethod,
6
+ )
7
+ from typing import TYPE_CHECKING
8
+
9
+ from exasol.tdbp.dialects.exasol.exasol_identifier import ExasolIdentifier
10
+
11
+ if TYPE_CHECKING:
12
+ from exasol.tdbp.database_object_listener import DatabaseObjectListener
13
+
14
+
15
+ class DatabaseObject(ABC):
16
+ """
17
+ Abstract base class for database objects.
18
+
19
+ This class serves as a blueprint for defining database objects with a name
20
+ and an associated listener that observes events.
21
+
22
+ Attributes:
23
+ listener (DatabaseObjectListener): The listener that observes this database object.
24
+ name (str): The name of the database object.
25
+ """
26
+
27
+ def __init__(self, listener: DatabaseObjectListener, name: str):
28
+ self.listener = listener
29
+ self.identifier = ExasolIdentifier.of(name)
30
+
31
+ @abstractmethod
32
+ def fully_qualified_name(self) -> str:
33
+ """
34
+ Retrieves the fully qualified name representation of an entity.
35
+
36
+ Returns:
37
+ str: The fully qualified name representation of the entity.
38
+ """
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import (
4
+ ABC,
5
+ abstractmethod,
6
+ )
7
+ from typing import TYPE_CHECKING
8
+
9
+ from exasol.tdbp.table import Table
10
+
11
+ if TYPE_CHECKING:
12
+ from exasol.tdbp.database_object import DatabaseObject
13
+
14
+
15
+ class DatabaseObjectListener(ABC):
16
+ """
17
+ Abstract Base Class for listening to database object events.
18
+
19
+ This class serves as a base class for defining listeners that monitor various
20
+ events on database objects, such as object creation or data insertion. It acts
21
+ as a blueprint for implementing specific behaviors during these events.
22
+
23
+ The main purpose is to allow different strategies for writing database objects,
24
+ for example, immediately or in batches.
25
+ """
26
+
27
+ @abstractmethod
28
+ def purge_user_objects(self) -> None:
29
+ """
30
+ Abstract method to purge user-related objects.
31
+
32
+ It is intended to clean up or remove user-specific objects or related data
33
+ to ensure provide a clean database for testing.
34
+ """
35
+
36
+ @abstractmethod
37
+ def on_create(self, database_object: DatabaseObject) -> None:
38
+ """
39
+ Handles database object creation events.
40
+
41
+ Args:
42
+ database_object: The database object that was created.
43
+ """
44
+
45
+ @abstractmethod
46
+ def on_insert(self, table: Table, values: list):
47
+ """
48
+ Handles the event triggered when a new record is inserted into the table.
49
+
50
+ Args:
51
+ table (Table): The table where the record is being inserted.
52
+ values (list): A list containing the values of the new record.
53
+ """
54
+ pass
55
+
56
+ @abstractmethod
57
+ def on_insert_all(self, table: Table, values: list[list]):
58
+ """
59
+ Handles bulk insertion of data into a table.
60
+
61
+ Args:
62
+ table (Table): The table into which the data will be inserted.
63
+ values (list[list]): A list of lists containing the rows of data to
64
+ be inserted.
65
+ """
File without changes
@@ -0,0 +1,39 @@
1
+ from exasol.tdbp.database_object_listener import DatabaseObjectListener
2
+ from exasol.tdbp.schema import Schema
3
+
4
+
5
+ class DatabaseObjectFactory:
6
+ """
7
+ Factory class for creating database objects.
8
+
9
+ This class provides a way to construct various database objects, such
10
+ as schemas, and ensures proper event notifications are sent when these
11
+ objects are created.
12
+
13
+ The purpose of the injected listeners is to write objects to the database
14
+ with different strategies. Depending on the injected listener, the objects
15
+ are written immediately or in batches.
16
+
17
+ Args:
18
+ name (str): The name of the factory instance.
19
+ listener (DatabaseObjectListener): A listener to handle events triggered
20
+ during the creation of database objects.
21
+ """
22
+
23
+ def __init__(self, name: str, listener: DatabaseObjectListener):
24
+ self.name = name
25
+ self.listener = listener
26
+
27
+ def create_schema(self, name: str) -> Schema:
28
+ """
29
+ Creates a new schema with the given name and triggers the creation listener.
30
+
31
+ Args:
32
+ name: The name of the schema to be created.
33
+
34
+ Returns:
35
+ A Schema instance representing the newly created schema.
36
+ """
37
+ schema = Schema(self.listener, name)
38
+ self.listener.on_create(schema)
39
+ return schema
File without changes
@@ -0,0 +1,59 @@
1
+ import regex
2
+
3
+
4
+ class ExasolIdentifier:
5
+ """
6
+ Represents an Exasol identifier.
7
+
8
+ This class provides functionality to validate and create Exasol-compatible
9
+ identifiers. Identifiers are validated against a specific pattern that defines
10
+ valid Exasol identifier strings. The class ensures that only valid identifiers
11
+ can be instantiated.
12
+
13
+ The main purpose is to prevent SQL injection attacks by ensuring that
14
+ user-provided identifiers are valid.
15
+
16
+ See Also:
17
+ https://docs.exasol.com/db/latest/sql_references/basiclanguageelements.htm#SQLidentifier
18
+ """
19
+
20
+ __IDENTIFIER_PATTERN = (
21
+ r"^[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}]"
22
+ r"[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}\u00B7]*$"
23
+ )
24
+
25
+ def __init__(self, identifier: str):
26
+ self.identifier = identifier
27
+
28
+ def __str__(self):
29
+ return self.identifier
30
+
31
+ @staticmethod
32
+ def of(identifier: str):
33
+ """
34
+ Creates an instance of ExasolIdentifier when the provided identifier is valid according to the Exasol SQL
35
+ identifier specification.
36
+
37
+ The method validates the identifier string against the Exasol identifier rules, ensuring it starts with a Unicode
38
+ letter or letter number and only includes valid characters. Raises a ValueError for invalid identifiers.
39
+
40
+ Args:
41
+ identifier (str): The string representing the identifier to be validated and converted
42
+ into an ExasolIdentifier instance.
43
+
44
+ Returns:
45
+ ExasolIdentifier: An ExasolIdentifier instance when the given identifier is valid.
46
+
47
+ Raises:
48
+ ValueError: If the provided identifier does not comply with the Exasol identifier pattern.
49
+ """
50
+ if (identifier is not None) and regex.match(
51
+ ExasolIdentifier.__IDENTIFIER_PATTERN, identifier, regex.UNICODE
52
+ ):
53
+ return ExasolIdentifier(identifier)
54
+ else:
55
+ raise ValueError(
56
+ f"Invalid Exasol identifier '{identifier}'. Identifiers must start with a Unicode letter or letter "
57
+ "number and can only contain letters, numbers, marks, connectors, formatting codes or the middle dot "
58
+ "character."
59
+ )
@@ -0,0 +1,84 @@
1
+ from typing import override
2
+
3
+ from pyexasol import ExaConnection
4
+
5
+ from exasol.tdbp.database_object import DatabaseObject
6
+ from exasol.tdbp.database_object_listener import DatabaseObjectListener
7
+ from exasol.tdbp.schema import Schema
8
+ from exasol.tdbp.table import Table
9
+
10
+
11
+ class ExasolImmediateDatabaseObjectWriter(DatabaseObjectListener):
12
+ """Listens to database object events and writes the object to Exasol immediately."""
13
+
14
+ def __init__(self, connection: ExaConnection):
15
+ """
16
+ Initializes the class with a provided database connection instance.
17
+
18
+ Args:
19
+ connection (ExaConnection): A connection to the Exasol database.
20
+ """
21
+ self.connection = connection
22
+
23
+ @override
24
+ def on_create(self, database_object: DatabaseObject) -> None:
25
+ """A database object was created.
26
+
27
+ Args:
28
+ database_object (DatabaseObject): The database object that was created.
29
+ """
30
+ sql = ""
31
+ if isinstance(database_object, Schema):
32
+ sql = f"""CREATE SCHEMA {database_object.fully_qualified_name()};"""
33
+ elif isinstance(database_object, Table):
34
+ print(f"Columns: {database_object.columns}")
35
+ column_definitions = [
36
+ f""""{key}" {value}""" for key, value in database_object.columns.items()
37
+ ]
38
+ sql = f"""CREATE TABLE {database_object.fully_qualified_name()}({", ".join(column_definitions)})"""
39
+ self.connection.execute(sql)
40
+ self.connection.commit()
41
+
42
+ @override
43
+ def on_insert(self, table: Table, values: list) -> None:
44
+ """
45
+ A row was inserted into a table.
46
+
47
+ Args:
48
+ table (Table): The table where the row was inserted.
49
+ values (list): The values of the inserted row.
50
+ """
51
+ self.on_insert_all(table, [values])
52
+
53
+ @override
54
+ def on_insert_all(self, table: Table, values: list[list]) -> None:
55
+ """
56
+ Rows were inserted into a table.
57
+
58
+ Args:
59
+ table (Table): The table where the rows were inserted.
60
+ values (list[list]): A list of lists, where each inner list represents a row.
61
+ """
62
+ self.connection.ext.insert_multi(
63
+ (table.schema.identifier, table.identifier), values
64
+ )
65
+ self.connection.commit()
66
+
67
+ @override
68
+ def purge_user_objects(self) -> None:
69
+ """Removes all user objects from the database.
70
+
71
+ A user object is any database object created by the user in contrast
72
+ to system objects, which are created by the database itself.
73
+
74
+ The purpose of this method is to ensure a clean database for testing.
75
+
76
+ System objects in Exasol are, for example, all tables and views in the SYS schema.
77
+ Those are not touched by this method.
78
+ """
79
+ with self.connection.execute(
80
+ "SELECT schema_name FROM sys.exa_dba_schemas"
81
+ ) as statement:
82
+ for row in statement:
83
+ self.connection.execute(f"DROP SCHEMA {row[0]} CASCADE")
84
+ self.connection.commit()
@@ -0,0 +1,14 @@
1
+ from pyexasol import ExaConnection
2
+
3
+ from exasol.tdbp.dialects.database_object_factory import DatabaseObjectFactory
4
+ from exasol.tdbp.dialects.exasol.exasol_immediate_database_object_writer import (
5
+ ExasolImmediateDatabaseObjectWriter,
6
+ )
7
+
8
+
9
+ class ExasolObjectFactory(DatabaseObjectFactory):
10
+ def __init__(self, connection: ExaConnection):
11
+ super().__init__("Exasol", ExasolImmediateDatabaseObjectWriter(connection))
12
+
13
+ def purge_user_objects(self):
14
+ self.listener.purge_user_objects()
exasol/tdbp/schema.py ADDED
@@ -0,0 +1,39 @@
1
+ from typing import override
2
+
3
+ from exasol.tdbp.database_object import DatabaseObject
4
+ from exasol.tdbp.database_object_listener import DatabaseObjectListener
5
+ from exasol.tdbp.table import Table
6
+
7
+
8
+ class Schema(DatabaseObject):
9
+ """
10
+ Represents a database schema.
11
+
12
+ Attributes:
13
+ listener (DatabaseObjectListener): Listener object that handles database
14
+ object events.
15
+ schema_name (str): The name of the schema as defined when creating the instance.
16
+ """
17
+
18
+ def __init__(self, listener: DatabaseObjectListener, schema_name: str):
19
+ super().__init__(listener, schema_name)
20
+
21
+ @override
22
+ def fully_qualified_name(self) -> str:
23
+ return f'"{self.identifier}"'
24
+
25
+ def create_table(self, table_name: str, **columns):
26
+ """
27
+ Creates a new table with the specified name and columns.
28
+
29
+ Args:
30
+ table_name (str): The name of the table to be created.
31
+ **columns: Arbitrary keyword arguments representing the columns and their
32
+ definitions for the table.
33
+
34
+ Returns:
35
+ Table: The newly created Table object.
36
+ """
37
+ table = Table(self.listener, table_name, self, **columns)
38
+ self.listener.on_create(table)
39
+ return table
exasol/tdbp/table.py ADDED
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import (
4
+ TYPE_CHECKING,
5
+ Any,
6
+ override,
7
+ )
8
+
9
+ from exasol.tdbp.database_object import DatabaseObject
10
+
11
+ if TYPE_CHECKING:
12
+ from exasol.tdbp.database_object_listener import DatabaseObjectListener
13
+ from exasol.tdbp.schema import Schema
14
+
15
+
16
+ class Table(DatabaseObject):
17
+ """
18
+ Represents a database table.
19
+
20
+ This class models a table within a database. It supports schema association,
21
+ defining columns, and provides methods for inserting records into the table.
22
+
23
+ Attributes:
24
+ listener (DatabaseObjectListener): Listener object that handles database
25
+ object events.
26
+ schema (Schema): The schema to which this table belongs.
27
+ table_name (str): The name of the table.
28
+ columns (dict): A dictionary defining the columns of the table.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ listener: DatabaseObjectListener,
34
+ table_name: str,
35
+ schema: Schema,
36
+ **columns,
37
+ ):
38
+ DatabaseObject.__init__(self, listener, table_name)
39
+ self.schema = schema
40
+ self.columns = columns
41
+
42
+ @override
43
+ def fully_qualified_name(self) -> str:
44
+ return f'"{self.schema.identifier}"."{self.identifier}"'
45
+
46
+ def insert(self, *values: Any) -> Table:
47
+ """
48
+ Inserts one or more values into the table and notifies the listener about the operation.
49
+
50
+ Args:
51
+ *values: Arbitrary number of values to be inserted into the table. The type
52
+ of each value is determined by the table's definition.
53
+
54
+ Returns:
55
+ Table: The current table instance for fluent method chaining.
56
+ """
57
+ self.listener.on_insert(self, list(values))
58
+ return self
59
+
60
+ def insert_all(self, *values: Any) -> Table:
61
+ """
62
+ Inserts all provided values into the table and notifies the listener.
63
+
64
+ Args:
65
+ *values: Any
66
+ The values to be inserted into the table.
67
+
68
+ Returns:
69
+ Table: The current table instance for fluent method chaining.
70
+ """
71
+ self.listener.on_insert_all(self, list(values))
72
+ return self
exasol/tdbp/version.py ADDED
@@ -0,0 +1,15 @@
1
+ """
2
+ ATTENTION:
3
+ This file is generated by exasol/toolbox/nox/_package_version.py when using:
4
+ * either "poetry run -- nox -s format:fix"
5
+ * or "poetry run -- nox -s version:check -- --fix"
6
+ Do not edit this file manually!
7
+ If you need to change the version, do so in the pyproject.toml, e.g. by using
8
+ `poetry version X.Y.Z`.
9
+ """
10
+
11
+ MAJOR = 1
12
+ MINOR = 0
13
+ PATCH = 0
14
+ VERSION = f"{MAJOR}.{MINOR}.{PATCH}"
15
+ __version__ = VERSION
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Exasol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.3
2
+ Name: test-db-builder-python
3
+ Version: 1.0.0
4
+ Summary: Write compact code to setup up database contents in integration tests
5
+ License: MIT
6
+ Author: Sebastian Bär
7
+ Author-email: sebastian.baer@exasol.com
8
+ Requires-Python: >=3.12,<3.14
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Database
16
+ Requires-Dist: pyexasol (>=2.0.0,<3)
17
+ Requires-Dist: regex (>=2025.11.3)
18
+ Description-Content-Type: text/x-rst
19
+
20
+ Test Database Builder for Python (TDBP)
21
+ =======================================
22
+
23
+ Test Database Builder for Python (TDBP) is a lightweight framework that simplifies database integration testing by providing a fluent API for creating test database objects and test data.
24
+
25
+ It helps developers write cleaner, more maintainable database integration tests by eliminating boilerplate code and providing a consistent way to set up test data.
26
+
27
+ TDBP promotes the concept of disposable test setups. The compact code encourages keeping each test independent by having it create its own test dataset.
28
+ This also makes reviews much easier, since setup execution and assertions are close to each other.
29
+
30
+ Please note that TDBP aims at functional tests, where the amount of data required for each test is usually small.
31
+ If you need to test with large amounts of data, TDBP is not the right approach. It is especially ill-suited for performance testing.
32
+
33
+ This project is inspired by Exasol's Test Database Builder for Java (https://github.com/exasol/test-db-builder-java).
34
+
35
+ Target Audience
36
+ ---------------
37
+
38
+ TDBP is designed for:
39
+
40
+ - Software developers writing database integration tests
41
+ - QA engineers automating database tests
42
+ - Database developers testing stored procedures and functions
43
+ - Anyone needing to create temporary test database objects and data
44
+
45
+
46
+ .. tip:: We recommend using TDBP when:
47
+
48
+ - You need to create temporary database objects for functional testing
49
+ - You want to isolate tests from each other
50
+ - You need to repeatedly set up and tear down test data
51
+ - You want to make your database tests more readable, maintainable and easy to review
52
+
53
+ .. warning:: **Do not** use TDBP in any of the situations below:
54
+
55
+ - Production data management
56
+ - Performance testing (use dedicated tools instead)
57
+ - Managing persistent database objects
58
+ - Complex data modeling (use proper database migration tools)
59
+
60
+
61
+ Quick Start
62
+ -------------
63
+
64
+ We recommend to make the object factory a fixture in your integration test and purge the database before each test. This ensures test isolation.
65
+
66
+ The object factory needs a database connection. In case of the Exasol dialect, the `pytest-exasol-backend` (https://github.com/exasol/pytest-backend) makes creating an Exasol backend and getting a connection very convenient.
67
+
68
+ .. code-block:: python3
69
+
70
+ @pytest.fixture
71
+ def factory(connection):
72
+ factory = ExasolObjectFactory(connection)
73
+ factory.purge_user_objects() # Clean slate for each test
74
+ return factory
75
+
76
+ With that done, the test preparation gets very compact.
77
+
78
+ .. code-block:: python3
79
+
80
+ def test_insert_customers(factory):
81
+ # Prepare the test database
82
+ schema = factory.create_schema("SALES")
83
+ table = schema.create_table("CUSTOMERS",
84
+ ID="DECIMAL(12,0)", NAME="VARCHAR(255)")
85
+ table.insert(1, "Alice").insert(2, "Bob")
86
+
87
+ # Execute your test
88
+ # ...
89
+
90
+ # Assert the results
91
+ # ...
92
+
93
+ Information for Users
94
+ ---------------------
95
+
96
+ * 📖 `User Guide <doc/user_guide/user_guide.rst>`_: Detailed instructions on using TDBP including examples and best practices
@@ -0,0 +1,16 @@
1
+ exasol/tdbp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ exasol/tdbp/database_object.py,sha256=KIODpVoJ8rEFvHU4x6junAAH4IYt3GMeOirouMzkNUQ,1080
3
+ exasol/tdbp/database_object_listener.py,sha256=SNvfLycqM0dgPMiWq9_yaupNVKc5M-RkGfUsWmOjyZs,1962
4
+ exasol/tdbp/dialects/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ exasol/tdbp/dialects/database_object_factory.py,sha256=Nk0QXVksQcgswwyiq5x0sy8qQ841iKp28c-ZE14RQ4A,1334
6
+ exasol/tdbp/dialects/exasol/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ exasol/tdbp/dialects/exasol/exasol_identifier.py,sha256=LFPs98ftkh29FrYBeOuE9M8VA95qhKeKbxHeRtLO8L0,2266
8
+ exasol/tdbp/dialects/exasol/exasol_immediate_database_object_writer.py,sha256=sZkAJCyif3Ro1bOIK1Zw2jkfYfSsKDhSQfhlI-ulqjo,3061
9
+ exasol/tdbp/dialects/exasol/exasol_object_factory.py,sha256=H8LV7X33DTyHLAo3Ni3U_JVXrGNYKHgGVHWyFhrEcas,505
10
+ exasol/tdbp/schema.py,sha256=KsV2oqq1eSUEy6AeJv5Oz_ukOTpgIT8g08Y2OjOz0MI,1261
11
+ exasol/tdbp/table.py,sha256=nEosAy4f8E2IJniYtQvHf30eeSqJPY4TighV9QG2P-k,2165
12
+ exasol/tdbp/version.py,sha256=jMC5JXALLVxFdDzGL8yVivJ-uR0-W-hNZUa7ZSZ5Mgc,434
13
+ test_db_builder_python-1.0.0.dist-info/LICENSE.txt,sha256=ln1sL-0IhH92l3X1V97Wfic599wN9Gs3zAdkaXVQotA,1062
14
+ test_db_builder_python-1.0.0.dist-info/METADATA,sha256=H6AKznGNA26uwiIop-MuKCbGi06c5Hp640lzi68X0Sc,3845
15
+ test_db_builder_python-1.0.0.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
16
+ test_db_builder_python-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.1.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any