Merge pull request '2021.11' (#50) from 2021.11 into master

Reviewed-on: #50
This commit is contained in:
Sven Heidemann 2021-11-30 12:03:03 +01:00
commit dffa3de1ec
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", "cwd": "${workspaceFolder}/src/tests/custom/database/src",
"program": "main.py", "program": "main.py",
"console": "integratedTerminal", "console": "integratedTerminal",
"env": {
"PYTHON_ENVIRONMENT": "development",
"PYTHONPATH": "${workspaceFolder}/src/:$PYTHONPATH"
}
}, },
{ {
"name": "CLI", "name": "CLI",
@ -197,7 +201,11 @@
"args": [ "args": [
"install", "install",
"discord.py", "discord.py",
] ],
"env": {
"GISMO_ENVIRONMENT": "development",
"PYTHONPATH": "${workspaceFolder}/src/:$PYTHONPATH"
}
}, },
{ {
"name": "CLI: install local", "name": "CLI: install local",

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_cli'
__author__ = 'Sven Heidemann' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -29,4 +29,4 @@ from .main import main
from .startup import Startup from .startup import Startup
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -28,4 +28,4 @@ from .publish_service import PublishService
from .version_service import VersionService from .version_service import VersionService
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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 os
import subprocess import subprocess
import textwrap 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.cli_settings import CLISettings
from cpl_cli.command_abc import CommandABC from cpl_cli.command_abc import CommandABC
from cpl_cli.configuration.build_settings import BuildSettings from cpl_cli.configuration.build_settings import BuildSettings
from cpl_cli.configuration.project_settings import ProjectSettings from cpl_cli.configuration.project_settings import ProjectSettings
from cpl_cli.configuration.settings_helper import SettingsHelper from cpl_cli.configuration.settings_helper import SettingsHelper
from cpl_cli.error import Error 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): class InstallService(CommandABC):
@ -38,6 +39,9 @@ class InstallService(CommandABC):
self._project_settings = project_settings self._project_settings = project_settings
self._cli_settings = cli_settings self._cli_settings = cli_settings
self._is_simulating = False
self._is_virtual = False
self._project_file = f'{self._config.get_configuration("ProjectName")}.json' self._project_file = f'{self._config.get_configuration("ProjectName")}.json'
@property @property
@ -50,6 +54,9 @@ class InstallService(CommandABC):
package The package to install 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): def _install_project(self):
""" """
Installs dependencies of CPl project Installs dependencies of CPl project
@ -64,11 +71,12 @@ class InstallService(CommandABC):
Error.error(f'Found invalid dependencies in {self._project_file}.') Error.error(f'Found invalid dependencies in {self._project_file}.')
return 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: for dependency in self._project_settings.dependencies:
Console.spinner( Console.spinner(
f'Installing: {dependency}', 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, source=self._cli_settings.pip_path if 'sh_cpl' in dependency else None,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
@ -76,7 +84,8 @@ class InstallService(CommandABC):
spinner_foreground_color=ForegroundColorEnum.cyan spinner_foreground_color=ForegroundColorEnum.cyan
) )
Pip.reset_executable() if not self._is_virtual:
Pip.reset_executable()
def _install_package(self, package: str): def _install_package(self, package: str):
""" """
@ -85,7 +94,8 @@ class InstallService(CommandABC):
:return: :return:
""" """
is_already_in_project = False 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: 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.') 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( Console.spinner(
f'Installing: {package}', 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, source=self._cli_settings.pip_path if 'sh_cpl' in package else None,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
text_foreground_color=ForegroundColorEnum.green, text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan 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 \ if new_package is None \
or '==' in package and \ or '==' in package and \
version.parse(package.split('==')[1]) != version.parse(new_package.split('==')[1]): 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) self._project_settings.dependencies.append(new_name)
config = { if not self._is_simulating:
ProjectSettings.__name__: SettingsHelper.get_project_settings_dict(self._project_settings), config = {
BuildSettings.__name__: SettingsHelper.get_build_settings_dict(self._build_settings) 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: 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.write(json.dumps(config, indent=2))
project_file.close() project_file.close()
Pip.reset_executable() Pip.reset_executable()
@ -176,6 +190,16 @@ class InstallService(CommandABC):
:param args: :param args:
:return: :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: if len(args) == 0:
self._install_project() self._install_project()
else: else:

View File

@ -2,6 +2,7 @@ import json
import os import os
import subprocess import subprocess
import textwrap import textwrap
import time
from cpl_core.configuration.configuration_abc import ConfigurationABC from cpl_core.configuration.configuration_abc import ConfigurationABC
from cpl_core.console.console import Console from cpl_core.console.console import Console
@ -32,6 +33,9 @@ class UninstallService(CommandABC):
self._build_settings = build_settings self._build_settings = build_settings
self._project_settings = project_settings self._project_settings = project_settings
self._is_simulating = False
self._is_virtual = False
@property @property
def help_message(self) -> str: def help_message(self) -> str:
return textwrap.dedent("""\ return textwrap.dedent("""\
@ -42,6 +46,9 @@ class UninstallService(CommandABC):
package The package to uninstall 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]): def run(self, args: list[str]):
""" """
Entry point of command Entry point of command
@ -53,12 +60,27 @@ class UninstallService(CommandABC):
Console.error(f'Usage: cpl uninstall <package>') Console.error(f'Usage: cpl uninstall <package>')
return return
Pip.set_executable(self._project_settings.python_executable)
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 not self._is_virtual:
Pip.set_executable(self._project_settings.python_executable)
package = args[0] package = args[0]
is_in_dependencies = False 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: for dependency in self._project_settings.dependencies:
if package in dependency: if package in dependency:
@ -74,7 +96,7 @@ class UninstallService(CommandABC):
Console.spinner( Console.spinner(
f'Uninstalling: {package}', 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, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
text_foreground_color=ForegroundColorEnum.green, text_foreground_color=ForegroundColorEnum.green,
@ -83,13 +105,15 @@ class UninstallService(CommandABC):
if package in self._project_settings.dependencies: if package in self._project_settings.dependencies:
self._project_settings.dependencies.remove(package) self._project_settings.dependencies.remove(package)
config = { if not self._is_simulating:
ProjectSettings.__name__: SettingsHelper.get_project_settings_dict(self._project_settings), config = {
BuildSettings.__name__: SettingsHelper.get_build_settings_dict(self._build_settings) 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)) with open(os.path.join(self._env.working_directory, f'{self._config.get_configuration("ProjectName")}.json'), 'w') as project_file:
project_file.close() project_file.write(json.dumps(config, indent=2))
project_file.close()
Console.write_line(f'Removed {package}') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -30,4 +30,4 @@ from .workspace_settings import WorkspaceSettings
from .workspace_settings_name_enum import WorkspaceSettingsNameEnum from .workspace_settings_name_enum import WorkspaceSettingsNameEnum
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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", "Name": "sh_cpl-cli",
"Version": { "Version": {
"Major": "2021", "Major": "2021",
"Minor": "10", "Minor": "11",
"Micro": "5.post2" "Micro": "0"
}, },
"Author": "Sven Heidemann", "Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de", "AuthorEmail": "sven.heidemann@sh-edraft.de",
@ -16,7 +16,7 @@
"LicenseName": "MIT", "LicenseName": "MIT",
"LicenseDescription": "MIT, see LICENSE for more details.", "LicenseDescription": "MIT, see LICENSE for more details.",
"Dependencies": [ "Dependencies": [
"sh_cpl-core>=2021.10.2" "sh_cpl-core>=2021.10.0"
], ],
"PythonVersion": ">=3.8", "PythonVersion": ">=3.8",
"PythonPath": {}, "PythonPath": {},

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_cli.live_server'
__author__ = 'Sven Heidemann' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -24,4 +24,4 @@ from .publisher_abc import PublisherABC
from .publisher_service import PublisherService from .publisher_service import PublisherService
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.5.post2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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) ConsoleArgument('', 'help', ['h', 'H'], ' ', is_value_token_optional=True)
) )
configuration.add_console_argument( 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=[ configuration.add_console_argument(ConsoleArgument('', 'new', ['n', 'N'], '', console_arguments=[
ConsoleArgument('', 'console', ['c', 'C'], ' '), ConsoleArgument('', 'console', ['c', 'C'], ' '),

View File

@ -15,11 +15,11 @@ __title__ = 'cpl_core'
__author__ = 'Sven Heidemann' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -26,4 +26,4 @@ from .application_builder_abc import ApplicationBuilderABC
from .startup_abc import StartupABC from .startup_abc import StartupABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -27,4 +27,4 @@ from .configuration_variable_name_enum import ConfigurationVariableNameEnum
from .console_argument import ConsoleArgument from .console_argument import ConsoleArgument
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -27,4 +27,4 @@ from .foreground_color_enum import ForegroundColorEnum
from .spinner_thread import SpinnerThread from .spinner_thread import SpinnerThread
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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", "Name": "sh_cpl-core",
"Version": { "Version": {
"Major": "2021", "Major": "2021",
"Minor": "10", "Minor": "11",
"Micro": "2" "Micro": "0"
}, },
"Author": "Sven Heidemann", "Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de", "AuthorEmail": "sven.heidemann@sh-edraft.de",
@ -19,15 +19,14 @@
"colorama==0.4.4", "colorama==0.4.4",
"mysql-connector==2.2.9", "mysql-connector==2.2.9",
"psutil==5.8.0", "psutil==5.8.0",
"packaging==20.9", "packaging==21.3",
"pyfiglet==0.8.post1", "pyfiglet==0.8.post1",
"pynput==1.7.3", "pynput==1.7.5",
"SQLAlchemy==1.4.7", "setuptools==59.4.0",
"setuptools==56.0.0",
"tabulate==0.8.9", "tabulate==0.8.9",
"termcolor==1.1.0", "termcolor==1.1.0",
"watchdog==2.0.2", "watchdog==2.1.6",
"wheel==0.36.2" "wheel==0.37.0"
], ],
"PythonVersion": ">=3.8", "PythonVersion": ">=3.8",
"PythonPath": {}, "PythonPath": {},

View File

@ -15,14 +15,14 @@ __title__ = 'cpl_core.database'
__author__ = 'Sven Heidemann' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
from .database_model import DatabaseModel
from .database_settings import DatabaseSettings
from .database_settings_name_enum import DatabaseSettingsNameEnum from .database_settings_name_enum import DatabaseSettingsNameEnum
from .database_settings import DatabaseSettings
from .table_abc import TableABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -24,4 +24,4 @@ from .database_connection import DatabaseConnection
from .database_connection_abc import DatabaseConnectionABC from .database_connection_abc import DatabaseConnectionABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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 typing import Optional
from sqlalchemy import engine, create_engine import mysql.connector as sql
from sqlalchemy.orm import Session, sessionmaker from cpl_core.database.connection.database_connection_abc import \
DatabaseConnectionABC
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
from cpl_core.database.database_settings import DatabaseSettings 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): class DatabaseConnection(DatabaseConnectionABC):
r"""Representation of the database connection 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) DatabaseConnectionABC.__init__(self)
self._db_settings = database_settings self._database: Optional[MySQLConnectionAbstract] = None
self._cursor: Optional[MySQLCursorBuffered] = None
self._engine: Optional[engine] = None
self._session: Optional[Session] = None
self._credentials: Optional[str] = None
@property @property
def engine(self) -> engine: def server(self) -> MySQLConnectionAbstract:
return self._engine return self._database
@property @property
def session(self) -> Session: def cursor(self) -> MySQLCursorBuffered:
return self._session return self._cursor
def connect(self, connection_string: str): def connect(self, database_settings: DatabaseSettings):
try: connection = sql.connect(
self._engine = create_engine(connection_string) host=database_settings.host,
user=database_settings.user,
if self._db_settings.auth_plugin is not None: passwd=CredentialManager.decrypt(database_settings.password),
self._engine = create_engine(connection_string, connect_args={'auth_plugin': self._db_settings.auth_plugin}) charset=database_settings.charset,
use_unicode=database_settings.use_unicode,
if self._db_settings.encoding is not None: buffered=database_settings.buffered,
self._engine.encoding = self._db_settings.encoding auth_plugin=database_settings.auth_plugin
)
if self._db_settings.case_sensitive is not None: connection.cursor().execute(
self._engine.case_sensitive = self._db_settings.case_sensitive f'CREATE DATABASE IF NOT EXISTS `{database_settings.database}`;')
self._database = sql.connect(
if self._db_settings.echo is not None: host=database_settings.host,
self._engine.echo = self._db_settings.echo user=database_settings.user,
passwd=CredentialManager.decrypt(database_settings.password),
self._engine.connect() db=database_settings.database,
charset=database_settings.charset,
db_session = sessionmaker(bind=self._engine) use_unicode=database_settings.use_unicode,
self._session = db_session() buffered=database_settings.buffered,
Console.set_foreground_color(ForegroundColorEnum.green) auth_plugin=database_settings.auth_plugin
Console.write_line(f'[{__name__}] Connected to database') )
Console.set_foreground_color(ForegroundColorEnum.default) self._cursor = self._database.cursor()
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()

View File

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

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.database.context'
__author__ = 'Sven Heidemann' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -24,4 +24,4 @@ from .database_context import DatabaseContext
from .database_context_abc import DatabaseContextABC from .database_context_abc import DatabaseContextABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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 typing import Optional
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.database.connection.database_connection import DatabaseConnection 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.context.database_context_abc import DatabaseContextABC
from cpl_core.database.database_settings import DatabaseSettings 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): class DatabaseContext(DatabaseContextABC):
@ -19,38 +19,23 @@ class DatabaseContext(DatabaseContextABC):
""" """
def __init__(self, database_settings: DatabaseSettings): def __init__(self, database_settings: DatabaseSettings):
DatabaseContextABC.__init__(self) DatabaseContextABC.__init__(self, database_settings)
self._db: DatabaseConnectionABC = DatabaseConnection(database_settings) self._db: DatabaseConnectionABC = DatabaseConnection()
self._tables: list[Table] = [] self._tables: list[TableABC] = TableABC.__subclasses__()
@property @property
def engine(self) -> engine: def cursor(self) -> MySQLCursorBuffered:
return self._db.engine return self._db.cursor
@property def connect(self, database_settings: DatabaseSettings):
def session(self) -> Session: self._db.connect(database_settings)
return self._db.session for table in self._tables:
self._db.cursor.execute(table.get_create_string())
def connect(self, connection_string: str):
self._db.connect(connection_string)
self._create_tables()
def save_changes(self): def save_changes(self):
self._db.session.commit() self._db.server.commit()
def _create_tables(self): def select(self, statement: str) -> list[tuple]:
try: self._db.cursor.execute(statement)
for subclass in DatabaseModel.__subclasses__(): return self._db.cursor.fetchall()
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()

View File

@ -1,7 +1,7 @@
from abc import abstractmethod, ABC from abc import ABC, abstractmethod
from sqlalchemy import engine from cpl_core.database.database_settings import DatabaseSettings
from sqlalchemy.orm import Session from mysql.connector.cursor import MySQLCursorBuffered
class DatabaseContextABC(ABC): class DatabaseContextABC(ABC):
@ -12,29 +12,34 @@ class DatabaseContextABC(ABC):
pass pass
@property @property
@abstractmethod def cursor(self) -> MySQLCursorBuffered:
def engine(self) -> engine: pass return self._cursor
@property
@abstractmethod
def session(self) -> Session: pass
@abstractmethod @abstractmethod
def connect(self, connection_string: str): def connect(self, database_settings: DatabaseSettings):
r"""Connects to a database by connection string r"""Connects to a database by connection settings
Parameter Parameter
--------- ---------
connection_string: :class:`str` database_settings :class:`cpl_core.database.database_settings.DatabaseSettings`
Database connection string, see: https://docs.sqlalchemy.org/en/14/core/engines.html
""" """
pass pass
@abstractmethod
def save_changes(self): def save_changes(self):
r"""Saves changes of the database""" r"""Saves changes of the database"""
pass pass
@abstractmethod @abstractmethod
def _create_tables(self): def select(self, statement: str) -> list[tuple]:
r"""Create all tables for application from database model""" r"""Runs SQL Statements
Parameter
---------
statement: :class:`str`
Returns
-------
list: Fetched list of selected elements
"""
pass 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): def __init__(self):
ConfigurationModelABC.__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._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 @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 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): def from_dict(self, settings: dict):
r"""Sets attributes from given dict r"""Sets attributes from given dict
@ -76,20 +62,22 @@ class DatabaseSettings(ConfigurationModelABC):
settings: :class:`dict` settings: :class:`dict`
""" """
try: try:
self._connection_string = settings[DatabaseSettingsNameEnum.connection_string.value] self._host = settings[DatabaseSettingsNameEnum.host.value]
self._credentials = settings[DatabaseSettingsNameEnum.credentials.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: if DatabaseSettingsNameEnum.auth_plugin.value in settings:
self._auth_plugin = settings[DatabaseSettingsNameEnum.auth_plugin.value] 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: except Exception as e:
Console.set_foreground_color(ForegroundColorEnum.red) Console.set_foreground_color(ForegroundColorEnum.red)
Console.write_line(f'[ ERROR ] [ {__name__} ]: Reading error in {self.__name__} settings') 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): class DatabaseSettingsNameEnum(Enum):
connection_string = 'ConnectionString' host = 'Host'
credentials = 'Credentials' user = 'User'
encoding = 'Encoding' password = 'Password'
case_sensitive = 'CaseSensitive' database = 'Database'
echo = 'Echo' charset = 'Charset'
use_unicode = 'UseUnicode'
buffered = 'Buffered'
auth_plugin = 'AuthPlugin' 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -28,4 +28,4 @@ from .service_provider import ServiceProvider
from .service_provider_abc import ServiceProviderABC from .service_provider_abc import ServiceProviderABC
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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): def add_db_context(self, db_context_type: Type[DatabaseContextABC], db_settings: DatabaseSettings):
self._database_context = db_context_type(db_settings) 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): def add_logging(self):
self.add_singleton(LoggerABC, Logger) self.add_singleton(LoggerABC, Logger)

View File

@ -15,15 +15,13 @@ class ServiceCollectionABC(ABC):
pass pass
@abstractmethod @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 r"""Adds database context
Parameter Parameter
--------- ---------
db_context: Type[:class:`cpl_core.database.context.database_context_abc.DatabaseContextABC`] db_context: Type[:class:`cpl_core.database.context.database_context_abc.DatabaseContextABC`]
Database context Database context
db_settings: :class:`cpl_core.database.database_settings.DatabaseSettings`
Database settings
""" """
pass pass

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_core.environment'
__author__ = 'Sven Heidemann' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -25,4 +25,4 @@ from .environment_name_enum import EnvironmentNameEnum
from .application_environment import ApplicationEnvironment from .application_environment import ApplicationEnvironment
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -27,4 +27,4 @@ from .logging_settings import LoggingSettings
from .logging_settings_name_enum import LoggingSettingsNameEnum from .logging_settings_name_enum import LoggingSettingsNameEnum
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -27,4 +27,4 @@ from .email_client_settings import EMailClientSettings
from .email_client_settings_name_enum import EMailClientSettingsNameEnum from .email_client_settings_name_enum import EMailClientSettingsNameEnum
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -24,4 +24,4 @@ from .time_format_settings import TimeFormatSettings
from .time_format_settings_names_enum import TimeFormatSettingsNamesEnum from .time_format_settings_names_enum import TimeFormatSettingsNamesEnum
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.2' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -25,4 +25,4 @@ from .string import String
from .pip import Pip from .pip import Pip
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.3' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.3' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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", "Name": "sh_cpl-query",
"Version": { "Version": {
"Major": "2021", "Major": "2021",
"Minor": "10", "Minor": "11",
"Micro": "3" "Micro": "0"
}, },
"Author": "Sven Heidemann", "Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de", "AuthorEmail": "sven.heidemann@sh-edraft.de",
@ -16,9 +16,9 @@
"LicenseName": "MIT", "LicenseName": "MIT",
"LicenseDescription": "MIT, see LICENSE for more details.", "LicenseDescription": "MIT, see LICENSE for more details.",
"Dependencies": [ "Dependencies": [
"sh_cpl-core>=2021.10.0" "sh_cpl-core>=2021.11.0"
], ],
"PythonVersion": ">=3.9.2", "PythonVersion": ">=3.8",
"PythonPath": {}, "PythonPath": {},
"Classifiers": [] "Classifiers": []
}, },

View File

@ -15,7 +15,7 @@ __title__ = 'cpl_query.extension'
__author__ = 'Sven Heidemann' __author__ = 'Sven Heidemann'
__license__ = 'MIT' __license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de' __copyright__ = 'Copyright (c) 2020 - 2021 sh-edraft.de'
__version__ = '2021.10.3' __version__ = '2021.11.0'
from collections import namedtuple from collections import namedtuple
@ -27,4 +27,4 @@ from .ordered_iterable_abc import OrderedIterableABC
from .ordered_iterable import OrderedIterable from .ordered_iterable import OrderedIterable
VersionInfo = namedtuple('VersionInfo', 'major minor micro') 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}') self._logger.debug(__name__, f'Customer: {self._configuration.environment.customer}')
user_repo: UserRepo = self._services.get_service(UserRepoABC) 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:') Console.write_line('Users:')
for user in user_repo.get_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:') Console.write_line('Cities:')
for city in user_repo.get_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": { "DatabaseSettings": {
"AuthPlugin": "mysql_native_password", "Host": "localhost",
"ConnectionString": "mysql+mysqlconnector://sh_cpl:$credentials@localhost/sh_cpl", "User": "sh_cpl",
"Credentials": "MHZhc0Y2bjhKc1VUMWV0Qw==", "Password": "MHZhc0Y2bjhKc1VUMWV0Qw==",
"Encoding": "utf8mb4" "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 TableABC
from cpl_core.database import DatabaseModel
class CityModel(DatabaseModel): class CityModel(TableABC):
__tablename__ = 'Cities'
Id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
Name = Column(String(64), nullable=False)
ZIP = Column(String(5), nullable=False)
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.Name = name
self.ZIP = zip_code 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 cpl_core.database import TableABC
from sqlalchemy.orm import relationship
from cpl_core.database import DatabaseModel
from .city_model import CityModel from .city_model import CityModel
class UserModel(DatabaseModel): class UserModel(TableABC):
__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")
def __init__(self, name: str, city: CityModel): def __init__(self, name: str, city: CityModel, id = 0):
self.UserId = id
self.Name = name self.Name = name
self.City_Id = city.Id self.CityId = city.CityId if city is not None else 0
self.City = city 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 cpl_core.database.context import DatabaseContextABC
from .city_model import CityModel from .city_model import CityModel
from .user_model import UserModel from .user_model import UserModel
from .user_repo_abc import UserRepoABC from .user_repo_abc import UserRepoABC
@ -9,21 +11,32 @@ class UserRepo(UserRepoABC):
def __init__(self, db_context: DatabaseContextABC): def __init__(self, db_context: DatabaseContextABC):
UserRepoABC.__init__(self) UserRepoABC.__init__(self)
self._session = db_context.session self._db_context: DatabaseContextABC = db_context
self._user_query = db_context.session.query(UserModel)
def create(self): pass
def add_test_user(self): def add_test_user(self):
city = CityModel('Haren', '49733') city = CityModel('Haren', '49733')
city2 = CityModel('Meppen', '49716') city2 = CityModel('Meppen', '49716')
self._session.add(city2) self._db_context.cursor.execute(city2.insert_string)
user = UserModel('TestUser', city) user = UserModel('TestUser', city)
self._session.add(user) self._db_context.cursor.execute(user.insert_string)
self._session.commit() self._db_context.save_changes()
def get_users(self) -> list[UserModel]: 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]: 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 abc import ABC, abstractmethod
from .city_model import CityModel
from .user_model import UserModel from .user_model import UserModel
@ -10,3 +11,9 @@ class UserRepoABC(ABC):
@abstractmethod @abstractmethod
def get_users(self) -> list[UserModel]: pass 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.application import StartupABC
from cpl_core.configuration import ConfigurationABC from cpl_core.configuration import ConfigurationABC
from cpl_core.database import DatabaseSettings from cpl_core.database import DatabaseSettings
from cpl_core.dependency_injection import ServiceProviderABC, ServiceCollectionABC from cpl_core.dependency_injection import (ServiceCollectionABC,
from cpl_core.logging import LoggerABC, Logger ServiceProviderABC)
from cpl_core.environment import ApplicationEnvironmentABC
from cpl_core.logging import Logger, LoggerABC
from model.db_context import DBContext from model.db_context import DBContext
from model.user_repo import UserRepo from model.user_repo import UserRepo
from model.user_repo_abc import UserRepoABC from model.user_repo_abc import UserRepoABC
@ -10,30 +13,29 @@ from model.user_repo_abc import UserRepoABC
class Startup(StartupABC): class Startup(StartupABC):
def __init__(self, config: ConfigurationABC, services: ServiceCollectionABC): def __init__(self):
StartupABC.__init__(self) StartupABC.__init__(self)
self._configuration = config self._configuration = None
self._environment = self._configuration.environment
self._services = services
def configure_configuration(self) -> ConfigurationABC: def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC) -> ConfigurationABC:
self._configuration.add_environment_variables('PYTHON_') configuration.add_environment_variables('PYTHON_')
self._configuration.add_environment_variables('CPL_') configuration.add_environment_variables('CPL_')
self._configuration.add_console_arguments() configuration.add_console_arguments()
self._configuration.add_json_file(f'appsettings.json') configuration.add_json_file(f'appsettings.json')
self._configuration.add_json_file(f'appsettings.{self._configuration.environment.environment_name}.json') configuration.add_json_file(f'appsettings.{configuration.environment.environment_name}.json')
self._configuration.add_json_file(f'appsettings.{self._configuration.environment.host_name}.json', optional=True) configuration.add_json_file(f'appsettings.{configuration.environment.host_name}.json', optional=True)
return self._configuration self._configuration = configuration
def configure_services(self) -> ServiceProviderABC: return configuration
def configure_services(self, services: ServiceCollectionABC, environment: ApplicationEnvironmentABC) -> ServiceProviderABC:
# Create and connect to database # Create and connect to database
db_settings: DatabaseSettings = self._configuration.get_configuration(DatabaseSettings) 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) services.add_singleton(UserRepoABC, UserRepo)
self._services.add_singleton(LoggerABC, Logger)
return self._services.build_service_provider()
services.add_singleton(LoggerABC, Logger)
return services.build_service_provider()