2021.11 #49

Manually merged
edraft merged 10 commits from 2021.11 into master 2021-11-30 12:03:04 +01:00
62 changed files with 513 additions and 363 deletions

10
.vscode/launch.json vendored
View File

@ -41,6 +41,10 @@
"cwd": "${workspaceFolder}/src/tests/custom/database/src",
"program": "main.py",
"console": "integratedTerminal",
"env": {
"PYTHON_ENVIRONMENT": "development",
"PYTHONPATH": "${workspaceFolder}/src/:$PYTHONPATH"
}
},
{
"name": "CLI",
@ -197,7 +201,11 @@
"args": [
"install",
"discord.py",
]
],
"env": {
"GISMO_ENVIRONMENT": "development",
"PYTHONPATH": "${workspaceFolder}/src/:$PYTHONPATH"
}
},
{
"name": "CLI: install local",

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_cli'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -29,4 +29,4 @@ from .main import main
from .startup import Startup
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.build'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.generate'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new.console'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new.console.source'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new.console.source.name'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new.console.source.tests'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new.library'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new.library.source'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new.library.source.name'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.new.library.source.tests'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli._templates.publish'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_cli.command'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -28,4 +28,4 @@ from .publish_service import PublishService
from .version_service import VersionService
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -2,20 +2,21 @@ import json
import os
import subprocess
import textwrap
import time
from packaging import version
from cpl_core.configuration.configuration_abc import ConfigurationABC
from cpl_core.console.console import Console
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.environment.application_environment_abc import ApplicationEnvironmentABC
from cpl_core.utils.pip import Pip
from cpl_cli.cli_settings import CLISettings
from cpl_cli.command_abc import CommandABC
from cpl_cli.configuration.build_settings import BuildSettings
from cpl_cli.configuration.project_settings import ProjectSettings
from cpl_cli.configuration.settings_helper import SettingsHelper
from cpl_cli.error import Error
from cpl_core.configuration.configuration_abc import ConfigurationABC
from cpl_core.console.console import Console
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.environment.application_environment_abc import \
ApplicationEnvironmentABC
from cpl_core.utils.pip import Pip
from packaging import version
class InstallService(CommandABC):
@ -37,6 +38,9 @@ class InstallService(CommandABC):
self._build_settings = build_settings
self._project_settings = project_settings
self._cli_settings = cli_settings
self._is_simulating = False
self._is_virtual = False
self._project_file = f'{self._config.get_configuration("ProjectName")}.json'
@ -49,6 +53,9 @@ class InstallService(CommandABC):
Arguments:
package The package to install
""")
def _wait(self, t: int, *args, source: str = None, stdout=None, stderr=None):
time.sleep(t)
def _install_project(self):
"""
@ -64,11 +71,12 @@ class InstallService(CommandABC):
Error.error(f'Found invalid dependencies in {self._project_file}.')
return
Pip.set_executable(self._project_settings.python_executable)
if not self._is_virtual:
Pip.set_executable(self._project_settings.python_executable)
for dependency in self._project_settings.dependencies:
Console.spinner(
f'Installing: {dependency}',
Pip.install, dependency,
Pip.install if not self._is_virtual else self._wait, dependency if not self._is_virtual else 2,
source=self._cli_settings.pip_path if 'sh_cpl' in dependency else None,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
@ -76,7 +84,8 @@ class InstallService(CommandABC):
spinner_foreground_color=ForegroundColorEnum.cyan
)
Pip.reset_executable()
if not self._is_virtual:
Pip.reset_executable()
def _install_package(self, package: str):
"""
@ -85,7 +94,8 @@ class InstallService(CommandABC):
:return:
"""
is_already_in_project = False
Pip.set_executable(self._project_settings.python_executable)
if not self._is_virtual:
Pip.set_executable(self._project_settings.python_executable)
if self._project_settings is None or self._build_settings is None:
Error.error('The command requires to be run in an CPL project, but a project could not be found.')
@ -129,15 +139,18 @@ class InstallService(CommandABC):
Console.spinner(
f'Installing: {package}',
Pip.install, package,
Pip.install if not self._is_virtual else self._wait, package if not self._is_virtual else 2,
source=self._cli_settings.pip_path if 'sh_cpl' in package else None,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
new_package = Pip.get_package(name)
Console.write_line(new_package)
if self._is_virtual:
new_package = name
else:
new_package = Pip.get_package(name)
if new_package is None \
or '==' in package and \
version.parse(package.split('==')[1]) != version.parse(new_package.split('==')[1]):
@ -159,14 +172,15 @@ class InstallService(CommandABC):
self._project_settings.dependencies.append(new_name)
config = {
ProjectSettings.__name__: SettingsHelper.get_project_settings_dict(self._project_settings),
BuildSettings.__name__: SettingsHelper.get_build_settings_dict(self._build_settings)
}
with open(os.path.join(self._env.working_directory, self._project_file), 'w') as project_file:
project_file.write(json.dumps(config, indent=2))
project_file.close()
if not self._is_simulating:
config = {
ProjectSettings.__name__: SettingsHelper.get_project_settings_dict(self._project_settings),
BuildSettings.__name__: SettingsHelper.get_build_settings_dict(self._build_settings)
}
with open(os.path.join(self._env.working_directory, self._project_file), 'w') as project_file:
project_file.write(json.dumps(config, indent=2))
project_file.close()
Pip.reset_executable()
@ -176,6 +190,16 @@ class InstallService(CommandABC):
:param args:
:return:
"""
if '--virtual' in args:
self._is_virtual = True
args.remove('--virtual')
Console.write_line('Running in virtual mode:')
if '--simulate' in args:
self._is_virtual = True
args.remove('--simulate')
Console.write_line('Running in simulation mode:')
if len(args) == 0:
self._install_project()
else:

View File

@ -2,6 +2,7 @@ import json
import os
import subprocess
import textwrap
import time
from cpl_core.configuration.configuration_abc import ConfigurationABC
from cpl_core.console.console import Console
@ -31,6 +32,9 @@ class UninstallService(CommandABC):
self._env = env
self._build_settings = build_settings
self._project_settings = project_settings
self._is_simulating = False
self._is_virtual = False
@property
def help_message(self) -> str:
@ -41,6 +45,9 @@ class UninstallService(CommandABC):
Arguments:
package The package to uninstall
""")
def _wait(self, t: int, *args, source: str = None, stdout=None, stderr=None):
time.sleep(t)
def run(self, args: list[str]):
"""
@ -52,13 +59,28 @@ class UninstallService(CommandABC):
Console.error(f'Expected package')
Console.error(f'Usage: cpl uninstall <package>')
return
if '--virtual' in args:
self._is_virtual = True
args.remove('--virtual')
Console.write_line('Running in virtual mode:')
if '--simulate' in args:
self._is_virtual = True
args.remove('--simulate')
Console.write_line('Running in simulation mode:')
Pip.set_executable(self._project_settings.python_executable)
if not self._is_virtual:
Pip.set_executable(self._project_settings.python_executable)
package = args[0]
is_in_dependencies = False
pip_package = Pip.get_package(package)
if not self._is_virtual:
pip_package = Pip.get_package(package)
else:
pip_package = package
for dependency in self._project_settings.dependencies:
if package in dependency:
@ -74,7 +96,7 @@ class UninstallService(CommandABC):
Console.spinner(
f'Uninstalling: {package}',
Pip.uninstall, package,
Pip.uninstall if not self._is_virtual else self._wait, package if not self._is_virtual else 2,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
text_foreground_color=ForegroundColorEnum.green,
@ -83,13 +105,15 @@ class UninstallService(CommandABC):
if package in self._project_settings.dependencies:
self._project_settings.dependencies.remove(package)
config = {
ProjectSettings.__name__: SettingsHelper.get_project_settings_dict(self._project_settings),
BuildSettings.__name__: SettingsHelper.get_build_settings_dict(self._build_settings)
}
with open(os.path.join(self._env.working_directory, f'{self._config.get_configuration("ProjectName")}.json'), 'w') as project_file:
project_file.write(json.dumps(config, indent=2))
project_file.close()
if not self._is_simulating:
config = {
ProjectSettings.__name__: SettingsHelper.get_project_settings_dict(self._project_settings),
BuildSettings.__name__: SettingsHelper.get_build_settings_dict(self._build_settings)
}
with open(os.path.join(self._env.working_directory, f'{self._config.get_configuration("ProjectName")}.json'), 'w') as project_file:
project_file.write(json.dumps(config, indent=2))
project_file.close()
Console.write_line(f'Removed {package}')
Pip.reset_executable()
if not self._is_virtual:
Pip.reset_executable()

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_cli.configuration'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -30,4 +30,4 @@ from .workspace_settings import WorkspaceSettings
from .workspace_settings_name_enum import WorkspaceSettingsNameEnum
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -3,8 +3,8 @@
"Name": "sh_cpl-cli",
"Version": {
"Major": "2021",
"Minor": "10",
"Micro": "5.post2"
"Minor": "11",
"Micro": "0"
},
"Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de",
@ -16,7 +16,7 @@
"LicenseName": "MIT",
"LicenseDescription": "MIT, see LICENSE for more details.",
"Dependencies": [
"sh_cpl-core>=2021.10.2"
"sh_cpl-core>=2021.10.0"
],
"PythonVersion": ">=3.8",
"PythonPath": {},

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli.live_server'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_cli.publish'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -24,4 +24,4 @@ from .publisher_abc import PublisherABC
from .publisher_service import PublisherService
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli.source_creator'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='5.post2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -55,7 +55,10 @@ class Startup(StartupABC):
ConsoleArgument('', 'help', ['h', 'H'], ' ', is_value_token_optional=True)
)
configuration.add_console_argument(
ConsoleArgument('', 'install', ['i', 'I'], ' ', is_value_token_optional=True)
ConsoleArgument('', 'install', ['i', 'I'], ' ', is_value_token_optional=True, console_arguments= [
ConsoleArgument('', '--virtual', ['--v', '--V'], ''),
ConsoleArgument('', '--simulate', ['--s', '--S'], ''),
])
)
configuration.add_console_argument(ConsoleArgument('', 'new', ['n', 'N'], '', console_arguments=[
ConsoleArgument('', 'console', ['c', 'C'], ' '),

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_core'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.application'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -26,4 +26,4 @@ from .application_builder_abc import ApplicationBuilderABC
from .startup_abc import StartupABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.configuration'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -27,4 +27,4 @@ from .configuration_variable_name_enum import ConfigurationVariableNameEnum
from .console_argument import ConsoleArgument
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.console'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -27,4 +27,4 @@ from .foreground_color_enum import ForegroundColorEnum
from .spinner_thread import SpinnerThread
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -3,8 +3,8 @@
"Name": "sh_cpl-core",
"Version": {
"Major": "2021",
"Minor": "10",
"Micro": "2"
"Minor": "11",
"Micro": "0"
},
"Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de",
@ -19,15 +19,14 @@
"colorama==0.4.4",
"mysql-connector==2.2.9",
"psutil==5.8.0",
"packaging==20.9",
"packaging==21.3",
"pyfiglet==0.8.post1",
"pynput==1.7.3",
"SQLAlchemy==1.4.7",
"setuptools==56.0.0",
"pynput==1.7.5",
"setuptools==59.4.0",
"tabulate==0.8.9",
"termcolor==1.1.0",
"watchdog==2.0.2",
"wheel==0.36.2"
"watchdog==2.1.6",
"wheel==0.37.0"
],
"PythonVersion": ">=3.8",
"PythonPath": {},

View File

@ -15,14 +15,14 @@ __title__ = 'cpl_core.database'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
from .database_model import DatabaseModel
from .database_settings import DatabaseSettings
from .database_settings_name_enum import DatabaseSettingsNameEnum
from .database_settings import DatabaseSettings
from .table_abc import TableABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.database.connection'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -24,4 +24,4 @@ from .database_connection import DatabaseConnection
from .database_connection_abc import DatabaseConnectionABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -1,64 +1,52 @@
from typing import Optional
from sqlalchemy import engine, create_engine
from sqlalchemy.orm import Session, sessionmaker
from cpl_core.console.console import Console
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.database.connection.database_connection_abc import DatabaseConnectionABC
import mysql.connector as sql
from cpl_core.database.connection.database_connection_abc import \
DatabaseConnectionABC
from cpl_core.database.database_settings import DatabaseSettings
from cpl_core.utils.credential_manager import CredentialManager
from mysql.connector.abstracts import MySQLConnectionAbstract
from mysql.connector.cursor import MySQLCursorBuffered
class DatabaseConnection(DatabaseConnectionABC):
r"""Representation of the database connection
Parameter
---------
database_settings: :class:`cpl_core.database.database_settings.DatabaseSettings`
"""
def __init__(self, database_settings: DatabaseSettings):
def __init__(self):
DatabaseConnectionABC.__init__(self)
self._db_settings = database_settings
self._engine: Optional[engine] = None
self._session: Optional[Session] = None
self._credentials: Optional[str] = None
self._database: Optional[MySQLConnectionAbstract] = None
self._cursor: Optional[MySQLCursorBuffered] = None
@property
def engine(self) -> engine:
return self._engine
def server(self) -> MySQLConnectionAbstract:
return self._database
@property
def session(self) -> Session:
return self._session
def cursor(self) -> MySQLCursorBuffered:
return self._cursor
def connect(self, connection_string: str):
try:
self._engine = create_engine(connection_string)
if self._db_settings.auth_plugin is not None:
self._engine = create_engine(connection_string, connect_args={'auth_plugin': self._db_settings.auth_plugin})
if self._db_settings.encoding is not None:
self._engine.encoding = self._db_settings.encoding
if self._db_settings.case_sensitive is not None:
self._engine.case_sensitive = self._db_settings.case_sensitive
if self._db_settings.echo is not None:
self._engine.echo = self._db_settings.echo
self._engine.connect()
db_session = sessionmaker(bind=self._engine)
self._session = db_session()
Console.set_foreground_color(ForegroundColorEnum.green)
Console.write_line(f'[{__name__}] Connected to database')
Console.set_foreground_color(ForegroundColorEnum.default)
except Exception as e:
Console.set_foreground_color(ForegroundColorEnum.red)
Console.write_line(f'[{__name__}] Database connection failed -> {e}')
Console.set_foreground_color(ForegroundColorEnum.default)
exit()
def connect(self, database_settings: DatabaseSettings):
connection = sql.connect(
host=database_settings.host,
user=database_settings.user,
passwd=CredentialManager.decrypt(database_settings.password),
charset=database_settings.charset,
use_unicode=database_settings.use_unicode,
buffered=database_settings.buffered,
auth_plugin=database_settings.auth_plugin
)
connection.cursor().execute(
f'CREATE DATABASE IF NOT EXISTS `{database_settings.database}`;')
self._database = sql.connect(
host=database_settings.host,
user=database_settings.user,
passwd=CredentialManager.decrypt(database_settings.password),
db=database_settings.database,
charset=database_settings.charset,
use_unicode=database_settings.use_unicode,
buffered=database_settings.buffered,
auth_plugin=database_settings.auth_plugin
)
self._cursor = self._database.cursor()

View File

@ -1,7 +1,8 @@
from abc import abstractmethod, ABC
from abc import ABC, abstractmethod
from sqlalchemy import engine
from sqlalchemy.orm import Session
from cpl_core.database.database_settings import DatabaseSettings
from mysql.connector.abstracts import MySQLConnectionAbstract
from mysql.connector.cursor import MySQLCursorBuffered
class DatabaseConnectionABC(ABC):
@ -12,14 +13,14 @@ class DatabaseConnectionABC(ABC):
@property
@abstractmethod
def engine(self) -> engine: pass
def server(self) -> MySQLConnectionAbstract: pass
@property
@abstractmethod
def session(self) -> Session: pass
def cursor(self) -> MySQLCursorBuffered: pass
@abstractmethod
def connect(self, connection_string: str):
def connect(self, database_settings: DatabaseSettings):
r"""Connects to a database by connection string
Parameter

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.database.context'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -24,4 +24,4 @@ from .database_context import DatabaseContext
from .database_context_abc import DatabaseContextABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -1,13 +1,13 @@
from sqlalchemy import engine, Table
from sqlalchemy.orm import Session
from cpl_core.console.console import Console
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from typing import Optional
from cpl_core.database.connection.database_connection import DatabaseConnection
from cpl_core.database.connection.database_connection_abc import DatabaseConnectionABC
from cpl_core.database.connection.database_connection_abc import \
DatabaseConnectionABC
from cpl_core.database.context.database_context_abc import DatabaseContextABC
from cpl_core.database.database_settings import DatabaseSettings
from cpl_core.database.database_model import DatabaseModel
from cpl_core.database.table_abc import TableABC
from mysql.connector.cursor import MySQLCursorBuffered
class DatabaseContext(DatabaseContextABC):
@ -19,38 +19,23 @@ class DatabaseContext(DatabaseContextABC):
"""
def __init__(self, database_settings: DatabaseSettings):
DatabaseContextABC.__init__(self)
DatabaseContextABC.__init__(self, database_settings)
self._db: DatabaseConnectionABC = DatabaseConnection(database_settings)
self._tables: list[Table] = []
self._db: DatabaseConnectionABC = DatabaseConnection()
self._tables: list[TableABC] = TableABC.__subclasses__()
@property
def engine(self) -> engine:
return self._db.engine
@property
def session(self) -> Session:
return self._db.session
def connect(self, connection_string: str):
self._db.connect(connection_string)
self._create_tables()
def cursor(self) -> MySQLCursorBuffered:
return self._db.cursor
def connect(self, database_settings: DatabaseSettings):
self._db.connect(database_settings)
for table in self._tables:
self._db.cursor.execute(table.get_create_string())
def save_changes(self):
self._db.session.commit()
def _create_tables(self):
try:
for subclass in DatabaseModel.__subclasses__():
self._tables.append(subclass.__table__)
DatabaseModel.metadata.drop_all(self._db.engine, self._tables)
DatabaseModel.metadata.create_all(self._db.engine, self._tables, checkfirst=True)
Console.set_foreground_color(ForegroundColorEnum.green)
Console.write_line(f'[{__name__}] Created tables')
Console.set_foreground_color(ForegroundColorEnum.default)
except Exception as e:
Console.set_foreground_color(ForegroundColorEnum.red)
Console.write_line(f'[{__name__}] Creating tables failed -> {e}')
Console.set_foreground_color(ForegroundColorEnum.default)
exit()
self._db.server.commit()
def select(self, statement: str) -> list[tuple]:
self._db.cursor.execute(statement)
return self._db.cursor.fetchall()

View File

@ -1,7 +1,7 @@
from abc import abstractmethod, ABC
from abc import ABC, abstractmethod
from sqlalchemy import engine
from sqlalchemy.orm import Session
from cpl_core.database.database_settings import DatabaseSettings
from mysql.connector.cursor import MySQLCursorBuffered
class DatabaseContextABC(ABC):
@ -12,29 +12,34 @@ class DatabaseContextABC(ABC):
pass
@property
def cursor(self) -> MySQLCursorBuffered:
return self._cursor
@abstractmethod
def engine(self) -> engine: pass
@property
@abstractmethod
def session(self) -> Session: pass
@abstractmethod
def connect(self, connection_string: str):
r"""Connects to a database by connection string
def connect(self, database_settings: DatabaseSettings):
r"""Connects to a database by connection settings
Parameter
---------
connection_string: :class:`str`
Database connection string, see: https://docs.sqlalchemy.org/en/14/core/engines.html
database_settings :class:`cpl_core.database.database_settings.DatabaseSettings`
"""
pass
@abstractmethod
def save_changes(self):
r"""Saves changes of the database"""
pass
@abstractmethod
def _create_tables(self):
r"""Create all tables for application from database model"""
def select(self, statement: str) -> list[tuple]:
r"""Runs SQL Statements
Parameter
---------
statement: :class:`str`
Returns
-------
list: Fetched list of selected elements
"""
pass

View File

@ -1,3 +0,0 @@
from sqlalchemy.ext.declarative import declarative_base
DatabaseModel: declarative_base = declarative_base()

View File

@ -13,61 +13,47 @@ class DatabaseSettings(ConfigurationModelABC):
def __init__(self):
ConfigurationModelABC.__init__(self)
self._host: Optional[str] = None
self._user: Optional[str] = None
self._password: Optional[str] = None
self._databse: Optional[str] = None
self._charset: Optional[str] = None
self._use_unicode: Optional[bool] = None
self._buffered: Optional[bool] = None
self._auth_plugin: Optional[str] = None
self._connection_string: Optional[str] = None
self._credentials: Optional[str] = None
self._encoding: Optional[str] = None
self._case_sensitive: Optional[bool] = None
self._echo: Optional[bool] = None
@property
def auth_plugin(self) -> str:
def host(self) -> Optional[str]:
return self._host
@property
def user(self) -> Optional[str]:
return self._user
@property
def password(self) -> Optional[str]:
return self._password
@property
def database(self) -> Optional[str]:
return self._databse
@property
def charset(self) -> Optional[str]:
return self._charset
@property
def use_unicode(self) -> Optional[bool]:
return self._use_unicode
@property
def buffered(self) -> Optional[bool]:
return self._buffered
@property
def auth_plugin(self) -> Optional[str]:
return self._auth_plugin
@auth_plugin.setter
def auth_plugin(self, auth_plugin: str):
self._auth_plugin = auth_plugin
@property
def connection_string(self) -> str:
return self._connection_string
@connection_string.setter
def connection_string(self, connection_string: str):
self._connection_string = connection_string
@property
def credentials(self) -> str:
return self._credentials
@credentials.setter
def credentials(self, credentials: str):
self._credentials = credentials
@property
def encoding(self) -> str:
return self._encoding
@encoding.setter
def encoding(self, encoding: str) -> None:
self._encoding = encoding
@property
def case_sensitive(self) -> bool:
return self._case_sensitive
@case_sensitive.setter
def case_sensitive(self, case_sensitive: bool) -> None:
self._case_sensitive = case_sensitive
@property
def echo(self) -> bool:
return self._echo
@echo.setter
def echo(self, echo: bool) -> None:
self._echo = echo
def from_dict(self, settings: dict):
r"""Sets attributes from given dict
@ -76,20 +62,22 @@ class DatabaseSettings(ConfigurationModelABC):
settings: :class:`dict`
"""
try:
self._connection_string = settings[DatabaseSettingsNameEnum.connection_string.value]
self._credentials = settings[DatabaseSettingsNameEnum.credentials.value]
self._host = settings[DatabaseSettingsNameEnum.host.value]
self._user = settings[DatabaseSettingsNameEnum.user.value]
self._password = settings[DatabaseSettingsNameEnum.password.value]
self._databse = settings[DatabaseSettingsNameEnum.database.value]
if DatabaseSettingsNameEnum.charset.value in settings:
self._charset = settings[DatabaseSettingsNameEnum.charset.value]
if DatabaseSettingsNameEnum.buffered.value in settings:
self._use_unicode = bool(settings[DatabaseSettingsNameEnum.use_unicode.value])
if DatabaseSettingsNameEnum.buffered.value in settings:
self._buffered = bool(settings[DatabaseSettingsNameEnum.buffered.value])
if DatabaseSettingsNameEnum.auth_plugin.value in settings:
self._auth_plugin = settings[DatabaseSettingsNameEnum.auth_plugin.value]
if DatabaseSettingsNameEnum.encoding.value in settings:
self._encoding = settings[DatabaseSettingsNameEnum.encoding.value]
if DatabaseSettingsNameEnum.case_sensitive.value in settings:
self._case_sensitive = bool(settings[DatabaseSettingsNameEnum.case_sensitive.value])
if DatabaseSettingsNameEnum.echo.value in settings:
self._echo = bool(settings[DatabaseSettingsNameEnum.echo.value])
except Exception as e:
Console.set_foreground_color(ForegroundColorEnum.red)
Console.write_line(f'[ ERROR ] [ {__name__} ]: Reading error in {self.__name__} settings')

View File

@ -3,9 +3,11 @@ from enum import Enum
class DatabaseSettingsNameEnum(Enum):
connection_string = 'ConnectionString'
credentials = 'Credentials'
encoding = 'Encoding'
case_sensitive = 'CaseSensitive'
echo = 'Echo'
host = 'Host'
user = 'User'
password = 'Password'
database = 'Database'
charset = 'Charset'
use_unicode = 'UseUnicode'
buffered = 'Buffered'
auth_plugin = 'AuthPlugin'

View File

@ -0,0 +1,35 @@
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Optional
class TableABC(ABC):
@abstractmethod
def __init__(self):
self._created_at: Optional[datetime] = None
self._modified_at: Optional[datetime] = None
@property
def CreatedAt(self) -> datetime:
return self._created_at
@property
def LastModifiedAt(self) -> datetime:
return self._modified_at
@staticmethod
@abstractmethod
def get_create_string() -> str: pass
@property
@abstractmethod
def insert_string(self) -> str: pass
@property
@abstractmethod
def udpate_string(self) -> str: pass
@property
@abstractmethod
def delete_string(self) -> str: pass

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.dependency_injection'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -28,4 +28,4 @@ from .service_provider import ServiceProvider
from .service_provider_abc import ServiceProviderABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -40,7 +40,7 @@ class ServiceCollection(ServiceCollectionABC):
def add_db_context(self, db_context_type: Type[DatabaseContextABC], db_settings: DatabaseSettings):
self._database_context = db_context_type(db_settings)
self._database_context.connect(CredentialManager.build_string(db_settings.connection_string, db_settings.credentials))
self._database_context.connect(db_settings)
def add_logging(self):
self.add_singleton(LoggerABC, Logger)

View File

@ -15,15 +15,13 @@ class ServiceCollectionABC(ABC):
pass
@abstractmethod
def add_db_context(self, db_context: Type[DatabaseContextABC], db_settings: DatabaseSettings):
def add_db_context(self, db_context: Type[DatabaseContextABC]):
r"""Adds database context
Parameter
---------
db_context: Type[:class:`cpl_core.database.context.database_context_abc.DatabaseContextABC`]
Database context
db_settings: :class:`cpl_core.database.database_settings.DatabaseSettings`
Database settings
"""
pass

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.environment'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -25,4 +25,4 @@ from .environment_name_enum import EnvironmentNameEnum
from .application_environment import ApplicationEnvironment
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.logging'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -27,4 +27,4 @@ from .logging_settings import LoggingSettings
from .logging_settings_name_enum import LoggingSettingsNameEnum
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.mailing'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -27,4 +27,4 @@ from .email_client_settings import EMailClientSettings
from .email_client_settings_name_enum import EMailClientSettingsNameEnum
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.time'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -24,4 +24,4 @@ from .time_format_settings import TimeFormatSettings
from .time_format_settings_names_enum import TimeFormatSettingsNamesEnum
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.utils'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2'
__version__ = '2021.11.0'
from collections import namedtuple
@ -25,4 +25,4 @@ from .string import String
from .pip import Pip
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='2')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_query'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.3'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='3')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_query._query'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.3'
__version__ = '2021.11.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='3')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -3,8 +3,8 @@
"Name": "sh_cpl-query",
"Version": {
"Major": "2021",
"Minor": "10",
"Micro": "3"
"Minor": "11",
"Micro": "0"
},
"Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de",
@ -16,9 +16,9 @@
"LicenseName": "MIT",
"LicenseDescription": "MIT, see LICENSE for more details.",
"Dependencies": [
"sh_cpl-core>=2021.10.0"
"sh_cpl-core>=2021.11.0"
],
"PythonVersion": ">=3.9.2",
"PythonVersion": ">=3.8",
"PythonPath": {},
"Classifiers": []
},

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_query.extension'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.3'
__version__ = '2021.11.0'
from collections import namedtuple
@ -27,4 +27,4 @@ from .ordered_iterable_abc import OrderedIterableABC
from .ordered_iterable import OrderedIterable
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2021', minor='10', micro='3')
version_info = VersionInfo(major='2021', minor='11', micro='0')

View File

@ -26,11 +26,13 @@ class Application(ApplicationABC):
self._logger.debug(__name__, f'Customer: {self._configuration.environment.customer}')
user_repo: UserRepo = self._services.get_service(UserRepoABC)
user_repo.add_test_user()
if len(user_repo.get_users()) == 0:
user_repo.add_test_user()
Console.write_line('Users:')
for user in user_repo.get_users():
Console.write_line(user.Id, user.Name, user.City_Id, user.City.Id, user.City.Name, user.City.ZIP)
Console.write_line(user.UserId, user.Name, user.City)
Console.write_line('Cities:')
for city in user_repo.get_cities():
Console.write_line(city.Id, city.Name, city.ZIP)
Console.write_line(city.CityId, city.Name, city.ZIP)

View File

@ -14,9 +14,13 @@
},
"DatabaseSettings": {
"AuthPlugin": "mysql_native_password",
"ConnectionString": "mysql+mysqlconnector://sh_cpl:$credentials@localhost/sh_cpl",
"Credentials": "MHZhc0Y2bjhKc1VUMWV0Qw==",
"Encoding": "utf8mb4"
"Host": "localhost",
"User": "sh_cpl",
"Password": "MHZhc0Y2bjhKc1VUMWV0Qw==",
"Database": "sh_cpl",
"Charset": "utf8mb4",
"UseUnicode": "true",
"Buffered": "true",
"AuthPlugin": "mysql_native_password"
}
}

View File

@ -1,14 +1,47 @@
from sqlalchemy import Column, Integer, String
from cpl_core.database import DatabaseModel
from cpl_core.database import TableABC
class CityModel(DatabaseModel):
__tablename__ = 'Cities'
Id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
Name = Column(String(64), nullable=False)
ZIP = Column(String(5), nullable=False)
class CityModel(TableABC):
def __init__(self, name: str, zip_code: str):
def __init__(self, name: str, zip_code: str, id = 0):
self.CityId = id
self.Name = name
self.ZIP = zip_code
@staticmethod
def get_create_string() -> str:
return str(f"""
CREATE TABLE IF NOT EXISTS `City` (
`CityId` INT(30) NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(64) NOT NULL,
`ZIP` VARCHAR(5) NOT NULL,
PRIMARY KEY(`CityId`)
);
""")
@property
def insert_string(self) -> str:
return str(f"""
INSERT INTO `City` (
`Name`, `ZIP`
) VALUES (
'{self.Name}',
'{self.ZIP}'
);
""")
@property
def udpate_string(self) -> str:
return str(f"""
UPDATE `City`
SET `Name` = '{self.Name}',
`ZIP` = '{self.ZIP}',
WHERE `CityId` = {self.Id};
""")
@property
def delete_string(self) -> str:
return str(f"""
DELETE FROM `City`
WHERE `CityId` = {self.Id};
""")

View File

@ -1,18 +1,50 @@
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from cpl_core.database import TableABC
from cpl_core.database import DatabaseModel
from .city_model import CityModel
class UserModel(DatabaseModel):
__tablename__ = 'Users'
Id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
Name = Column(String(64), nullable=False)
City_Id = Column(Integer, ForeignKey('Cities.Id'), nullable=False)
City = relationship("CityModel")
class UserModel(TableABC):
def __init__(self, name: str, city: CityModel):
def __init__(self, name: str, city: CityModel, id = 0):
self.UserId = id
self.Name = name
self.City_Id = city.Id
self.CityId = city.CityId if city is not None else 0
self.City = city
@staticmethod
def get_create_string() -> str:
return str(f"""
CREATE TABLE IF NOT EXISTS `User` (
`UserId` INT(30) NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(64) NOT NULL,
`CityId` INT(30),
FOREIGN KEY (`UserId`) REFERENCES City(`CityId`),
PRIMARY KEY(`UserId`)
);
""")
@property
def insert_string(self) -> str:
return str(f"""
INSERT INTO `User` (
`Name`
) VALUES (
'{self.Name}'
);
""")
@property
def udpate_string(self) -> str:
return str(f"""
UPDATE `User`
SET `Name` = '{self.Name}',
`CityId` = {self.CityId},
WHERE `UserId` = {self.UserId};
""")
@property
def delete_string(self) -> str:
return str(f"""
DELETE FROM `User`
WHERE `UserId` = {self.UserId};
""")

View File

@ -1,4 +1,6 @@
from cpl_core.console import Console
from cpl_core.database.context import DatabaseContextABC
from .city_model import CityModel
from .user_model import UserModel
from .user_repo_abc import UserRepoABC
@ -9,21 +11,32 @@ class UserRepo(UserRepoABC):
def __init__(self, db_context: DatabaseContextABC):
UserRepoABC.__init__(self)
self._session = db_context.session
self._user_query = db_context.session.query(UserModel)
def create(self): pass
self._db_context: DatabaseContextABC = db_context
def add_test_user(self):
city = CityModel('Haren', '49733')
city2 = CityModel('Meppen', '49716')
self._session.add(city2)
self._db_context.cursor.execute(city2.insert_string)
user = UserModel('TestUser', city)
self._session.add(user)
self._session.commit()
self._db_context.cursor.execute(user.insert_string)
self._db_context.save_changes()
def get_users(self) -> list[UserModel]:
return self._session.query(UserModel).all()
users = []
results = self._db_context.select('SELECT * FROM `User`')
for result in results:
users.append(UserModel(result[1], self.get_city_by_id(result[2]), id = result[0]))
return users
def get_cities(self) -> list[CityModel]:
return self._session.query(CityModel).all()
cities = []
results = self._db_context.select('SELECT * FROM `City`')
for result in results:
cities.append(CityModel(result[1], result[2], id = result[0]))
return cities
def get_city_by_id(self, id: int) -> CityModel:
if id is None:
return None
result = self._db_context.select(f'SELECT * FROM `City` WHERE `Id` = {id}')
return CityModel(result[1], result[2], id = result[0])

View File

@ -1,5 +1,6 @@
from abc import ABC, abstractmethod
from .city_model import CityModel
from .user_model import UserModel
@ -10,3 +11,9 @@ class UserRepoABC(ABC):
@abstractmethod
def get_users(self) -> list[UserModel]: pass
@abstractmethod
def get_cities(self) -> list[CityModel]: pass
@abstractmethod
def get_city_by_id(self, id: int) -> CityModel: pass

View File

@ -1,8 +1,11 @@
from cpl_core.application import StartupABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.database import DatabaseSettings
from cpl_core.dependency_injection import ServiceProviderABC, ServiceCollectionABC
from cpl_core.logging import LoggerABC, Logger
from cpl_core.dependency_injection import (ServiceCollectionABC,
ServiceProviderABC)
from cpl_core.environment import ApplicationEnvironmentABC
from cpl_core.logging import Logger, LoggerABC
from model.db_context import DBContext
from model.user_repo import UserRepo
from model.user_repo_abc import UserRepoABC
@ -10,30 +13,29 @@ from model.user_repo_abc import UserRepoABC
class Startup(StartupABC):
def __init__(self, config: ConfigurationABC, services: ServiceCollectionABC):
def __init__(self):
StartupABC.__init__(self)
self._configuration = None
self._configuration = config
self._environment = self._configuration.environment
self._services = services
def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC) -> ConfigurationABC:
configuration.add_environment_variables('PYTHON_')
configuration.add_environment_variables('CPL_')
configuration.add_console_arguments()
configuration.add_json_file(f'appsettings.json')
configuration.add_json_file(f'appsettings.{configuration.environment.environment_name}.json')
configuration.add_json_file(f'appsettings.{configuration.environment.host_name}.json', optional=True)
def configure_configuration(self) -> ConfigurationABC:
self._configuration.add_environment_variables('PYTHON_')
self._configuration.add_environment_variables('CPL_')
self._configuration.add_console_arguments()
self._configuration.add_json_file(f'appsettings.json')
self._configuration.add_json_file(f'appsettings.{self._configuration.environment.environment_name}.json')
self._configuration.add_json_file(f'appsettings.{self._configuration.environment.host_name}.json', optional=True)
self._configuration = configuration
return configuration
return self._configuration
def configure_services(self) -> ServiceProviderABC:
def configure_services(self, services: ServiceCollectionABC, environment: ApplicationEnvironmentABC) -> ServiceProviderABC:
# Create and connect to database
db_settings: DatabaseSettings = self._configuration.get_configuration(DatabaseSettings)
self._services.add_db_context(DBContext, db_settings)
services.add_db_context(DBContext, db_settings)
self._services.add_singleton(UserRepoABC, UserRepo)
self._services.add_singleton(LoggerABC, Logger)
return self._services.build_service_provider()
services.add_singleton(UserRepoABC, UserRepo)
services.add_singleton(LoggerABC, Logger)
return services.build_service_provider()