Skip to content

Commit

Permalink
move Database model to Connection
Browse files Browse the repository at this point in the history
  • Loading branch information
mathemancer committed Jun 13, 2024
1 parent 1f6bac6 commit 4c2758c
Show file tree
Hide file tree
Showing 25 changed files with 148 additions and 114 deletions.
4 changes: 2 additions & 2 deletions mathesar/api/db/viewsets/databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from rest_framework.response import Response

from mathesar.api.db.permissions.database import DatabaseAccessPolicy
from mathesar.models.base import Database
from mathesar.models.base import Connection
from mathesar.api.dj_filters import DatabaseFilter
from mathesar.api.pagination import DefaultLimitOffsetPagination

Expand All @@ -28,7 +28,7 @@ class ConnectionViewSet(AccessViewSetMixin, viewsets.ModelViewSet):
def get_queryset(self):
return self.access_policy.scope_queryset(
self.request,
Database.objects.all().order_by('-created_at')
Connection.objects.all().order_by('-created_at')
)

def destroy(self, request, pk=None):
Expand Down
4 changes: 2 additions & 2 deletions mathesar/api/dj_filters.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django_filters import BooleanFilter, DateTimeFromToRangeFilter, OrderingFilter
from django_property_filter import PropertyFilterSet, PropertyBaseInFilter, PropertyCharFilter, PropertyOrderingFilter

from mathesar.models.base import Schema, Table, Database, DataFile
from mathesar.models.base import Schema, Table, Connection, DataFile
from mathesar.models.query import UIQuery


Expand All @@ -19,7 +19,7 @@ class DatabaseFilter(PropertyFilterSet):
)

class Meta:
model = Database
model = Connection
fields = ['deleted']


Expand Down
6 changes: 3 additions & 3 deletions mathesar/api/serializers/databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from mathesar.api.display_options import DISPLAY_OPTIONS_BY_UI_TYPE
from mathesar.api.exceptions.mixins import MathesarErrorMessageMixin
from mathesar.models.base import Database
from mathesar.models.base import Connection


class ConnectionSerializer(MathesarErrorMessageMixin, serializers.ModelSerializer):
Expand All @@ -12,15 +12,15 @@ class ConnectionSerializer(MathesarErrorMessageMixin, serializers.ModelSerialize
database = serializers.CharField(source='db_name')

class Meta:
model = Database
model = Connection
fields = ['id', 'nickname', 'database', 'supported_types_url', 'username', 'password', 'host', 'port']
read_only_fields = ['id', 'supported_types_url']
extra_kwargs = {
'password': {'write_only': True}
}

def get_supported_types_url(self, obj):
if isinstance(obj, Database) and not self.partial:
if isinstance(obj, Connection) and not self.partial:
# Only get records if we are serializing an existing table
request = self.context['request']
return request.build_absolute_uri(reverse('connection-types', kwargs={'pk': obj.pk}))
Expand Down
4 changes: 2 additions & 2 deletions mathesar/api/serializers/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from mathesar.api.db.permissions.table import TableAccessPolicy
from mathesar.api.db.permissions.database import DatabaseAccessPolicy
from mathesar.api.exceptions.mixins import MathesarErrorMessageMixin
from mathesar.models.base import Database, Schema, Table
from mathesar.models.base import Connection, Schema, Table
from mathesar.api.exceptions.database_exceptions import (
exceptions as database_api_exceptions
)
Expand All @@ -19,7 +19,7 @@ class SchemaSerializer(MathesarErrorMessageMixin, serializers.HyperlinkedModelSe
connection_id = PermittedPkRelatedField(
source='database',
access_policy=DatabaseAccessPolicy,
queryset=Database.current_objects.all()
queryset=Connection.current_objects.all()
)
description = serializers.CharField(
required=False, allow_blank=True, default=None, allow_null=True
Expand Down
4 changes: 2 additions & 2 deletions mathesar/api/ui/permissions/database_role.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.db.models import Q
from rest_access_policy import AccessPolicy

from mathesar.models.base import Database
from mathesar.models.base import Connection
from mathesar.models.users import DatabaseRole, Role


Expand Down Expand Up @@ -32,7 +32,7 @@ def scope_queryset(cls, request, qs):
if not (request.user.is_superuser or request.user.is_anonymous):
# TODO Consider moving to more reusable place
allowed_roles = (Role.MANAGER.value, Role.EDITOR.value, Role.VIEWER.value)
databases_with_view_access = Database.objects.filter(
databases_with_view_access = Connection.objects.filter(
Q(database_role__role__in=allowed_roles) & Q(database_role__user=request.user)
)
qs = qs.filter(database__in=databases_with_view_access)
Expand Down
4 changes: 2 additions & 2 deletions mathesar/api/ui/permissions/schema_role.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.db.models import Q
from rest_access_policy import AccessPolicy

from mathesar.models.base import Database, Schema
from mathesar.models.base import Connection, Schema
from mathesar.models.users import DatabaseRole, Role, SchemaRole


Expand All @@ -27,7 +27,7 @@ class SchemaRoleAccessPolicy(AccessPolicy):
def scope_queryset(cls, request, qs):
if not (request.user.is_superuser or request.user.is_anonymous):
allowed_roles = (Role.MANAGER.value, Role.EDITOR.value, Role.VIEWER.value)
databases_with_view_access = Database.objects.filter(
databases_with_view_access = Connection.objects.filter(
Q(database_role__role__in=allowed_roles) & Q(database_role__user=request.user)
)
schema_with_view_access = Schema.objects.filter(
Expand Down
4 changes: 2 additions & 2 deletions mathesar/api/ui/serializers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from mathesar.api.exceptions.mixins import MathesarErrorMessageMixin
from mathesar.api.exceptions.validation_exceptions.exceptions import IncorrectOldPassword
from mathesar.api.ui.permissions.users import UserAccessPolicy
from mathesar.models.base import Database, Schema
from mathesar.models.base import Connection, Schema
from mathesar.models.users import User, DatabaseRole, SchemaRole


Expand Down Expand Up @@ -107,7 +107,7 @@ class Meta:
# Refer https://rsinger86.github.io/drf-access-policy/policy_reuse/ for the usage of `PermittedPkRelatedField`
database = PermittedPkRelatedField(
access_policy=DatabaseAccessPolicy,
queryset=Database.current_objects.all()
queryset=Connection.current_objects.all()
)


Expand Down
4 changes: 2 additions & 2 deletions mathesar/api/ui/viewsets/databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from rest_framework.response import Response

from mathesar.api.ui.permissions.ui_database import UIDatabaseAccessPolicy
from mathesar.models.base import Database
from mathesar.models.base import Connection
from mathesar.api.dj_filters import DatabaseFilter
from mathesar.api.exceptions.validation_exceptions.exceptions import (
DictHasBadKeys, UnsupportedInstallationDatabase
Expand Down Expand Up @@ -39,7 +39,7 @@ class ConnectionViewSet(
def get_queryset(self):
return self.access_policy.scope_queryset(
self.request,
Database.objects.all().order_by('-created_at')
Connection.objects.all().order_by('-created_at')
)

@action(methods=['get'], detail=True)
Expand Down
4 changes: 2 additions & 2 deletions mathesar/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ def main(skip_static_collection=False):


def install_on_db_with_key(database_key, skip_confirm):
from mathesar.models.base import Database
db_model = Database.create_from_settings_key(database_key)
from mathesar.models.base import Connection
db_model = Connection.create_from_settings_key(database_key)
db_model.save()
try:
install.install_mathesar(
Expand Down
34 changes: 34 additions & 0 deletions mathesar/migrations/0007_rename_database_connection_and_more.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Generated by Django 4.2.11 on 2024-06-13 09:05

from django.db import migrations, models
import django.db.models.deletion
import mathesar.models.base


class Migration(migrations.Migration):

dependencies = [
('mathesar', '0006_mathesar_databases_to_model'),
]

operations = [
migrations.RenameModel(
old_name='Database',
new_name='Connection',
),
migrations.AlterField(
model_name='databaserole',
name='database',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mathesar.connection'),
),
migrations.AlterField(
model_name='schemarole',
name='schema',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mathesar.schema'),
),
migrations.AlterField(
model_name='tablesettings',
name='column_order',
field=models.JSONField(blank=True, default=None, null=True, validators=[mathesar.models.base.validate_column_order]),
),
]
4 changes: 2 additions & 2 deletions mathesar/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def __repr__(self):
_engine_cache = {}


class Database(ReflectionManagerMixin, BaseModel):
class Connection(ReflectionManagerMixin, BaseModel):
name = models.CharField(max_length=128, unique=True)
db_name = models.CharField(max_length=128)
username = EncryptedCharField(max_length=255)
Expand Down Expand Up @@ -178,7 +178,7 @@ def save(self, **kwargs):


class Schema(DatabaseObject):
database = models.ForeignKey('Database', on_delete=models.CASCADE,
database = models.ForeignKey('Connection', on_delete=models.CASCADE,
related_name='schemas')

class Meta:
Expand Down
4 changes: 2 additions & 2 deletions mathesar/models/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.contrib.auth.models import AbstractUser
from django.db import models

from mathesar.models.base import BaseModel, Database, Schema
from mathesar.models.base import BaseModel, Connection, Schema


class User(AbstractUser):
Expand All @@ -29,7 +29,7 @@ class Role(models.TextChoices):

class DatabaseRole(BaseModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='database_roles')
database = models.ForeignKey(Database, on_delete=models.CASCADE)
database = models.ForeignKey(Connection, on_delete=models.CASCADE)
role = models.CharField(max_length=10, choices=Role.choices)

class Meta:
Expand Down
12 changes: 6 additions & 6 deletions mathesar/rpc/utils.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from mathesar.database.base import get_psycopg_connection
from mathesar.models.base import Database
from mathesar.models.base import Connection


def connect(db_id, user):
def connect(conn_id, user):
"""
Return a psycopg connection, given a Database model id.
Return a psycopg connection, given a Connection model id.
Args:
db_id: The Django id corresponding to the Database.
conn_id: The Django id corresponding to the Connection.
"""
print("User is: ", user)
db_model = Database.current_objects.get(id=db_id)
return get_psycopg_connection(db_model)
conn_model = Connection.current_objects.get(id=conn_id)
return get_psycopg_connection(conn_model)
6 changes: 3 additions & 3 deletions mathesar/state/django.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def clear_dj_cache():


def reflect_db_objects(metadata, db_name=None):
databases = models.Database.current_objects.all()
databases = models.Connection.current_objects.all()
if db_name is not None:
databases = databases.filter(name=db_name)
sync_databases_status(databases)
Expand All @@ -53,7 +53,7 @@ def reflect_db_objects(metadata, db_name=None):


def sync_databases_status(databases):
"""Update status and check health for current Database Model instances."""
"""Update status and check health for current Connection Model instances."""
for db in databases:
try:
db._sa_engine.connect()
Expand All @@ -65,7 +65,7 @@ def sync_databases_status(databases):

def _set_db_is_deleted(db, deleted):
"""
Assures that a Django Database model's `deleted` field is equal to the `deleted`
Assures that a Django Connection model's `deleted` field is equal to the `deleted`
parameter, updating if necessary. Takes care to `save()` only when an update has been performed,
to save on the noteworthy performance cost.
"""
Expand Down
8 changes: 4 additions & 4 deletions mathesar/tests/api/test_database_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from db.metadata import get_empty_metadata
from mathesar.models.users import DatabaseRole
from mathesar.state.django import reflect_db_objects
from mathesar.models.base import Table, Schema, Database
from mathesar.models.base import Table, Schema, Connection
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from db.install import install_mathesar
Expand Down Expand Up @@ -50,7 +50,7 @@ def test_db_name(worker_id):
@pytest.fixture
def db_dj_model(test_db_name):
_recreate_db(test_db_name)
db = Database.objects.get_or_create(
db = Connection.objects.get_or_create(
name=test_db_name,
defaults={
'db_name': test_db_name,
Expand All @@ -70,7 +70,7 @@ def test_database_reflection_delete(db_dj_model):
assert db_dj_model.deleted is False # check DB is not marked deleted inappropriately
_remove_db(db_dj_model.name)
reflect_db_objects(get_empty_metadata())
fresh_db_model = Database.objects.get(name=db_dj_model.name)
fresh_db_model = Connection.objects.get(name=db_dj_model.name)
assert fresh_db_model.deleted is True # check DB is marked deleted appropriately


Expand Down Expand Up @@ -166,7 +166,7 @@ def test_delete_dbconn_with_msar_schemas(client, db_dj_model):
after_deletion = conn.execute(check_schema_exists)

with pytest.raises(ObjectDoesNotExist):
Database.objects.get(id=db_dj_model.id)
Connection.objects.get(id=db_dj_model.id)
assert response.status_code == 204
assert before_deletion.rowcount == 3
assert after_deletion.rowcount == 0
Expand Down
4 changes: 2 additions & 2 deletions mathesar/tests/api/test_ui_filters_api.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from mathesar.models.base import Database
from mathesar.models.base import Connection
from mathesar.filters.base import get_available_filters
from mathesar.models.users import DatabaseRole


def test_filter_list(client, test_db_name):
database = Database.objects.get(name=test_db_name)
database = Connection.objects.get(name=test_db_name)

response = client.get(f'/api/ui/v0/connections/{database.id}/filters/')
response_data = response.json()
Expand Down
6 changes: 3 additions & 3 deletions mathesar/tests/api/test_ui_types_api.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from mathesar.api.display_options import DISPLAY_OPTIONS_BY_UI_TYPE
from mathesar.models.base import Database
from mathesar.models.base import Connection
from mathesar.database.types import get_ui_type_from_id, UIType
from db.types.base import PostgresType, MathesarCustomType
from mathesar.models.users import DatabaseRole


def test_type_list(client, test_db_name):
database = Database.objects.get(name=test_db_name)
database = Connection.objects.get(name=test_db_name)

response = client.get(f'/api/ui/v0/connections/{database.id}/types/')
response_data = response.json()
Expand Down Expand Up @@ -62,7 +62,7 @@ def test_database_types_installed(client, test_db_name):
'display_options': None
},
]
default_database = Database.objects.get(name=test_db_name)
default_database = Connection.objects.get(name=test_db_name)

response = client.get(f'/api/ui/v0/connections/{default_database.id}/types/')
assert response.status_code == 200
Expand Down
Loading

0 comments on commit 4c2758c

Please sign in to comment.