litepolis-database-default 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. litepolis_database_default-0.0.1/LICENSE +21 -0
  2. litepolis_database_default-0.0.1/PKG-INFO +75 -0
  3. litepolis_database_default-0.0.1/README.md +62 -0
  4. litepolis_database_default-0.0.1/litepolis_database_default/Actor.py +30 -0
  5. litepolis_database_default-0.0.1/litepolis_database_default/Comments.py +75 -0
  6. litepolis_database_default-0.0.1/litepolis_database_default/Conversations.py +72 -0
  7. litepolis_database_default-0.0.1/litepolis_database_default/MigrationRecord.py +51 -0
  8. litepolis_database_default-0.0.1/litepolis_database_default/Report.py +85 -0
  9. litepolis_database_default-0.0.1/litepolis_database_default/Users.py +80 -0
  10. litepolis_database_default-0.0.1/litepolis_database_default/Vote.py +73 -0
  11. litepolis_database_default-0.0.1/litepolis_database_default/__init__.py +2 -0
  12. litepolis_database_default-0.0.1/litepolis_database_default/utils.py +36 -0
  13. litepolis_database_default-0.0.1/litepolis_database_default.egg-info/PKG-INFO +75 -0
  14. litepolis_database_default-0.0.1/litepolis_database_default.egg-info/SOURCES.txt +27 -0
  15. litepolis_database_default-0.0.1/litepolis_database_default.egg-info/dependency_links.txt +1 -0
  16. litepolis_database_default-0.0.1/litepolis_database_default.egg-info/requires.txt +2 -0
  17. litepolis_database_default-0.0.1/litepolis_database_default.egg-info/top_level.txt +1 -0
  18. litepolis_database_default-0.0.1/pyproject.toml +36 -0
  19. litepolis_database_default-0.0.1/setup.cfg +4 -0
  20. litepolis_database_default-0.0.1/tests/test_Actor.py +22 -0
  21. litepolis_database_default-0.0.1/tests/test_CommentManager.py +114 -0
  22. litepolis_database_default-0.0.1/tests/test_ConversationManager.py +95 -0
  23. litepolis_database_default-0.0.1/tests/test_Conversations.py +97 -0
  24. litepolis_database_default-0.0.1/tests/test_MigrationRecord.py +42 -0
  25. litepolis_database_default-0.0.1/tests/test_ReportManager.py +115 -0
  26. litepolis_database_default-0.0.1/tests/test_UserManager.py +62 -0
  27. litepolis_database_default-0.0.1/tests/test_Users.py +87 -0
  28. litepolis_database_default-0.0.1/tests/test_VoteManager.py +113 -0
  29. litepolis_database_default-0.0.1/tests/test_export.py +10 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 David H.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: litepolis-database-default
3
+ Version: 0.0.1
4
+ Summary: The default database module for LitePolis that compatible with Polis
5
+ Author: Your name
6
+ License: file: LICENSE
7
+ Project-URL: Homepage, https://github.com/NewJerseyStyle/LitePolis-database-default
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: fastapi
11
+ Requires-Dist: sqlmodel
12
+ Dynamic: license-file
13
+
14
+ # LitePolis Database Default
15
+
16
+ This is the default database module that compatible with [Polis](https://github.com/CivicTechTO/polis/).
17
+
18
+ ## Quick Start
19
+
20
+ 1. Install the module:
21
+ ```bash
22
+ litepolis-cli add-deps litepolis-database-default
23
+ ```
24
+
25
+ 2. Configure database connection:
26
+ ```yaml
27
+ # ~/.litepolis/litepolis.config
28
+ [litepolis_database_default]
29
+ database_url: "postgresql://user:pass@localhost:5432/litepolis"
30
+ # database_url: "starrocks://<User>:<Password>@<Host>:<Port>/<Catalog>.<Database>"
31
+ ```
32
+
33
+ 3. Basic usage:
34
+ ```python
35
+ from litepolis_database_default import DatabaseActor
36
+
37
+ user = DatabaseActor.create_user({
38
+ "email": "test@example.com",
39
+ "auth_token": "auth_token",
40
+ })
41
+
42
+ conv = DatabaseActor.create_conversation({
43
+ "title": "Test Conversation",
44
+ "description": "This is a test conversation."
45
+ })
46
+ ```
47
+
48
+ ## Data Schema
49
+
50
+ ### Users (`users`)
51
+ ```sql
52
+ CREATE TABLE users (
53
+ id SERIAL PRIMARY KEY,
54
+ email VARCHAR(255) UNIQUE NOT NULL,
55
+ auth_token TEXT NOT NULL,
56
+ is_admin BOOLEAN DEFAULT false,
57
+ created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
58
+ modified TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
59
+ );
60
+ ```
61
+
62
+ ### Conversations (`conversations`)
63
+ ```sql
64
+ CREATE TABLE conversations (
65
+ id SERIAL PRIMARY KEY,
66
+ title TEXT NOT NULL,
67
+ description TEXT,
68
+ is_archived BOOLEAN DEFAULT false,
69
+ created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
70
+ modified TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
71
+ );
72
+ ```
73
+
74
+ ## License
75
+ MIT Licensed. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,62 @@
1
+ # LitePolis Database Default
2
+
3
+ This is the default database module that compatible with [Polis](https://github.com/CivicTechTO/polis/).
4
+
5
+ ## Quick Start
6
+
7
+ 1. Install the module:
8
+ ```bash
9
+ litepolis-cli add-deps litepolis-database-default
10
+ ```
11
+
12
+ 2. Configure database connection:
13
+ ```yaml
14
+ # ~/.litepolis/litepolis.config
15
+ [litepolis_database_default]
16
+ database_url: "postgresql://user:pass@localhost:5432/litepolis"
17
+ # database_url: "starrocks://<User>:<Password>@<Host>:<Port>/<Catalog>.<Database>"
18
+ ```
19
+
20
+ 3. Basic usage:
21
+ ```python
22
+ from litepolis_database_default import DatabaseActor
23
+
24
+ user = DatabaseActor.create_user({
25
+ "email": "test@example.com",
26
+ "auth_token": "auth_token",
27
+ })
28
+
29
+ conv = DatabaseActor.create_conversation({
30
+ "title": "Test Conversation",
31
+ "description": "This is a test conversation."
32
+ })
33
+ ```
34
+
35
+ ## Data Schema
36
+
37
+ ### Users (`users`)
38
+ ```sql
39
+ CREATE TABLE users (
40
+ id SERIAL PRIMARY KEY,
41
+ email VARCHAR(255) UNIQUE NOT NULL,
42
+ auth_token TEXT NOT NULL,
43
+ is_admin BOOLEAN DEFAULT false,
44
+ created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
45
+ modified TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
46
+ );
47
+ ```
48
+
49
+ ### Conversations (`conversations`)
50
+ ```sql
51
+ CREATE TABLE conversations (
52
+ id SERIAL PRIMARY KEY,
53
+ title TEXT NOT NULL,
54
+ description TEXT,
55
+ is_archived BOOLEAN DEFAULT false,
56
+ created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
57
+ modified TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
58
+ );
59
+ ```
60
+
61
+ ## License
62
+ MIT Licensed. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,30 @@
1
+ from typing import Dict, Any, List
2
+
3
+ from .Users import UserManager
4
+ from .Conversations import ConversationManager
5
+ from .Comments import CommentManager
6
+ from .Vote import VoteManager
7
+ from .Report import ReportManager
8
+ from .MigrationRecord import MigrationRecordManager
9
+
10
+
11
+ class DatabaseActor(
12
+ UserManager,
13
+ ConversationManager,
14
+ CommentManager,
15
+ VoteManager,
16
+ ReportManager,
17
+ MigrationRecordManager
18
+ ):
19
+ """
20
+ DatabaseActor class for LitePolis.
21
+
22
+ This class serves as the central point of interaction between the LitePolis system
23
+ and the database module. It aggregates operations from various manager classes,
24
+ such as UserManager and ConversationManager, providing a unified interface
25
+ for database interactions.
26
+
27
+ LitePolis system is designed to interact with a class named "DatabaseActor",
28
+ so ensure this class name is maintained.
29
+ """
30
+ pass
@@ -0,0 +1,75 @@
1
+ from sqlmodel import SQLModel, Field, Relationship
2
+ from typing import Optional, List, Type, Any, Dict
3
+ from datetime import datetime, UTC
4
+
5
+ # Removed BaseManager import
6
+ from .utils import create_db_and_tables, get_session # Import get_session
7
+ from sqlmodel import Session, select # Import Session and select
8
+
9
+ class BaseModel(SQLModel):
10
+ id: int = Field(primary_key=True)
11
+ created: datetime = Field(default_factory=lambda: datetime.now(UTC))
12
+ modified: datetime = Field(default_factory=lambda: datetime.now(UTC))
13
+
14
+ class Comment(BaseModel, table=True):
15
+ __tablename__ = "comments"
16
+ text: str
17
+ user_id: int = Field(foreign_key="users.id")
18
+ conversation_id: int = Field(foreign_key="conversations.id")
19
+ parent_comment_id: Optional[int] = Field(foreign_key="comments.id")
20
+ # Relationships
21
+ user: "User" = Relationship(back_populates="comments")
22
+ conversation: "Conversation" = Relationship(back_populates="comments")
23
+ votes: List["Vote"] = Relationship(back_populates="comment")
24
+
25
+ class CommentManager:
26
+ @staticmethod
27
+ def create_comment(data: Dict[str, Any]) -> Comment:
28
+ """Creates a new Comment record."""
29
+ with get_session() as session:
30
+ comment_instance = Comment(**data)
31
+ session.add(comment_instance)
32
+ session.commit()
33
+ session.refresh(comment_instance)
34
+ return comment_instance
35
+
36
+ @staticmethod
37
+ def read_comment(comment_id: int) -> Optional[Comment]:
38
+ """Reads a Comment record by ID."""
39
+ with get_session() as session:
40
+ comment_instance = session.get(Comment, comment_id)
41
+ return comment_instance
42
+
43
+ @staticmethod
44
+ def update_comment(comment_id: int, data: Dict[str, Any]) -> Optional[Comment]:
45
+ """Updates a Comment record by ID."""
46
+ with get_session() as session:
47
+ comment_instance = session.get(Comment, comment_id)
48
+ if not comment_instance:
49
+ return None
50
+ for key, value in data.items():
51
+ setattr(comment_instance, key, value)
52
+ session.add(comment_instance)
53
+ session.commit()
54
+ session.refresh(comment_instance)
55
+ return comment_instance
56
+
57
+ @staticmethod
58
+ def delete_comment(comment_id: int) -> bool:
59
+ """Deletes a Comment record by ID."""
60
+ with get_session() as session:
61
+ comment_instance = session.get(Comment, comment_id)
62
+ if not comment_instance:
63
+ return False
64
+ session.delete(comment_instance)
65
+ session.commit()
66
+ return True
67
+
68
+ @staticmethod
69
+ def list_comments() -> List[Comment]:
70
+ """Lists all Comment records."""
71
+ with get_session() as session:
72
+ comment_instances = session.exec(select(Comment)).all()
73
+ return comment_instances
74
+
75
+ create_db_and_tables()
@@ -0,0 +1,72 @@
1
+ from sqlmodel import SQLModel, Field, Relationship
2
+ from typing import Optional, List, Type, Any, Dict
3
+ from datetime import datetime, UTC
4
+
5
+ # Removed BaseManager import
6
+ from .utils import create_db_and_tables, get_session # Import get_session
7
+ from sqlmodel import Session, select # Import Session and select
8
+
9
+ class BaseModel(SQLModel):
10
+ id: int = Field(primary_key=True)
11
+ created: datetime = Field(default_factory=lambda: datetime.now(UTC))
12
+ modified: datetime = Field(default_factory=lambda: datetime.now(UTC))
13
+
14
+ class Conversation(BaseModel, table=True):
15
+ __tablename__ = "conversations"
16
+ title: str
17
+ description: str
18
+ is_archived: bool = Field(default=False)
19
+ # Relationships
20
+ comments: List["Comment"] = Relationship(back_populates="conversation")
21
+
22
+ class ConversationManager:
23
+ @staticmethod
24
+ def create_conversation(data: Dict[str, Any]) -> Conversation:
25
+ """Creates a new Conversation record."""
26
+ with get_session() as session:
27
+ conversation_instance = Conversation(**data)
28
+ session.add(conversation_instance)
29
+ session.commit()
30
+ session.refresh(conversation_instance)
31
+ return conversation_instance
32
+
33
+ @staticmethod
34
+ def read_conversation(conversation_id: int) -> Optional[Conversation]:
35
+ """Reads a Conversation record by ID."""
36
+ with get_session() as session:
37
+ conversation_instance = session.get(Conversation, conversation_id)
38
+ return conversation_instance
39
+
40
+ @staticmethod
41
+ def update_conversation(conversation_id: int, data: Dict[str, Any]) -> Optional[Conversation]:
42
+ """Updates a Conversation record by ID."""
43
+ with get_session() as session:
44
+ conversation_instance = session.get(Conversation, conversation_id)
45
+ if not conversation_instance:
46
+ return None
47
+ for key, value in data.items():
48
+ setattr(conversation_instance, key, value)
49
+ session.add(conversation_instance)
50
+ session.commit()
51
+ session.refresh(conversation_instance)
52
+ return conversation_instance
53
+
54
+ @staticmethod
55
+ def delete_conversation(conversation_id: int) -> bool:
56
+ """Deletes a Conversation record by ID."""
57
+ with get_session() as session:
58
+ conversation_instance = session.get(Conversation, conversation_id)
59
+ if not conversation_instance:
60
+ return False
61
+ session.delete(conversation_instance)
62
+ session.commit()
63
+ return True
64
+
65
+ @staticmethod
66
+ def list_conversations() -> List[Conversation]:
67
+ """Lists all Conversation records."""
68
+ with get_session() as session:
69
+ conversations = session.exec(select(Conversation)).all()
70
+ return conversations
71
+
72
+ create_db_and_tables()
@@ -0,0 +1,51 @@
1
+ from typing import Dict, Any, Optional, List
2
+ from sqlmodel import SQLModel, Field
3
+ from datetime import datetime, UTC
4
+
5
+ # Removed BaseManager import
6
+ from .utils import create_db_and_tables, get_session # Import get_session
7
+ from sqlmodel import Session, select # Import Session and select
8
+
9
+ class MigrationRecord(SQLModel, table=True):
10
+ __tablename__ = "migrations"
11
+ id: str = Field(primary_key=True) # Migration filename
12
+ hash: str # Content hash
13
+ executed_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
14
+
15
+ class MigrationRecordManager:
16
+ @staticmethod
17
+ def create_migration(data: Dict[str, Any]) -> MigrationRecord:
18
+ """Creates a new MigrationRecord record."""
19
+ with get_session() as session:
20
+ migration_record_instance = MigrationRecord(**data)
21
+ session.add(migration_record_instance)
22
+ session.commit()
23
+ session.refresh(migration_record_instance)
24
+ return migration_record_instance
25
+
26
+ @staticmethod
27
+ def read_migration(migration_record_id: str) -> Optional[MigrationRecord]:
28
+ """Reads a MigrationRecord record by ID (migration ID is a string)."""
29
+ with get_session() as session:
30
+ migration_record_instance = session.get(MigrationRecord, migration_record_id)
31
+ return migration_record_instance
32
+
33
+ @staticmethod
34
+ def delete_migration(migration_record_id: str) -> bool:
35
+ """Deletes a MigrationRecord record by ID."""
36
+ with get_session() as session:
37
+ migration_record_instance = session.get(MigrationRecord, migration_record_id)
38
+ if not migration_record_instance:
39
+ return False
40
+ session.delete(migration_record_instance)
41
+ session.commit()
42
+ return True
43
+
44
+ @staticmethod
45
+ def list_migrations() -> List[MigrationRecord]:
46
+ """Lists all MigrationRecord records."""
47
+ with get_session() as session:
48
+ migration_record_instances = session.exec(select(MigrationRecord)).all()
49
+ return migration_record_instances
50
+
51
+ create_db_and_tables()
@@ -0,0 +1,85 @@
1
+ from sqlmodel import SQLModel, Field, Relationship
2
+ from typing import Optional, List, Type, Any, Dict
3
+ from datetime import datetime, UTC
4
+
5
+ # Removed BaseManager import
6
+ from .utils import create_db_and_tables, get_session # Import get_session
7
+ from sqlmodel import Session, select # Import Session and select
8
+
9
+ class BaseModel(SQLModel):
10
+ id: int = Field(primary_key=True)
11
+ created: datetime = Field(default_factory=lambda: datetime.now(UTC))
12
+ modified: datetime = Field(default_factory=lambda: datetime.now(UTC))
13
+
14
+ class Report(BaseModel, table=True):
15
+ __tablename__ = "reports"
16
+ reporter_id: int = Field(foreign_key="users.id")
17
+ target_comment_id: int = Field(foreign_key="comments.id")
18
+ reason: str
19
+ status: str = Field(default="pending") # pending/resolved
20
+
21
+ class ReportManager:
22
+ @staticmethod
23
+ def create_report(data: Dict[str, Any]) -> Report:
24
+ """Creates a new Report record."""
25
+ with get_session() as session:
26
+ report_instance = Report(**data)
27
+ session.add(report_instance)
28
+ session.commit()
29
+ session.refresh(report_instance)
30
+ return report_instance
31
+
32
+ @staticmethod
33
+ def read_report(report_id: int) -> Optional[Report]:
34
+ """Reads a Report record by ID."""
35
+ with get_session() as session:
36
+ report_instance = session.get(Report, report_id)
37
+ return report_instance
38
+
39
+ @staticmethod
40
+ def update_report(report_id: int, data: Dict[str, Any]) -> Optional[Report]:
41
+ """Updates a Report record by ID."""
42
+ with get_session() as session:
43
+ report_instance = session.get(Report, report_id)
44
+ if not report_instance:
45
+ return None
46
+ for key, value in data.items():
47
+ setattr(report_instance, key, value)
48
+ session.add(report_instance)
49
+ session.commit()
50
+ session.refresh(report_instance)
51
+ return report_instance
52
+
53
+ @staticmethod
54
+ def delete_report(report_id: int) -> bool:
55
+ """Deletes a Report record by ID."""
56
+ with get_session() as session:
57
+ report_instance = session.get(Report, report_id)
58
+ if not report_instance:
59
+ return False
60
+ session.delete(report_instance)
61
+ session.commit()
62
+ return True
63
+
64
+ @staticmethod
65
+ def list_reports() -> List[Report]:
66
+ """Lists all Report records."""
67
+ with get_session() as session:
68
+ report_instances = session.exec(select(Report)).all()
69
+ return report_instances
70
+
71
+ @staticmethod
72
+ def update_report_status(report_id: int, status: str) -> Optional[Report]:
73
+ """Specific method to update only the report status."""
74
+ with get_session() as session:
75
+ report_instance = session.get(Report, report_id)
76
+ if not report_instance:
77
+ return None
78
+ report_instance.status = status # type: ignore
79
+ session.add(report_instance)
80
+ session.commit()
81
+ session.refresh(report_instance)
82
+ return report_instance
83
+
84
+
85
+ create_db_and_tables()
@@ -0,0 +1,80 @@
1
+ from sqlmodel import SQLModel, Field, Relationship
2
+ from typing import Optional, List, Type, Any, Dict
3
+ from datetime import datetime, UTC
4
+
5
+ # Removed BaseManager import
6
+ from .utils import create_db_and_tables, get_session # Import get_session
7
+ from sqlmodel import Session, select # Import Session and select
8
+
9
+ class BaseModel(SQLModel):
10
+ id: int = Field(primary_key=True)
11
+ created: datetime = Field(default_factory=lambda: datetime.now(UTC))
12
+ modified: datetime = Field(default_factory=lambda: datetime.now(UTC))
13
+
14
+ class User(BaseModel, table=True):
15
+ __tablename__ = "users"
16
+ email: str = Field(index=True)
17
+ auth_token: str
18
+ is_admin: bool = Field(default=False)
19
+ # Relationships
20
+ comments: List["Comment"] = Relationship(back_populates="user")
21
+ votes: List["Vote"] = Relationship(back_populates="user")
22
+
23
+ class UserManager:
24
+ @staticmethod
25
+ def create_user(data: Dict[str, Any]) -> User:
26
+ """Creates a new User record."""
27
+ with get_session() as session:
28
+ user_instance = User(**data)
29
+ session.add(user_instance)
30
+ session.commit()
31
+ session.refresh(user_instance)
32
+ return user_instance
33
+
34
+ @staticmethod
35
+ def read_user(user_id: int) -> Optional[User]:
36
+ """Reads a User record by ID."""
37
+ with get_session() as session:
38
+ user_instance = session.get(User, user_id)
39
+ return user_instance
40
+
41
+ @staticmethod
42
+ def list_users() -> List[User]:
43
+ """Reads all User records."""
44
+ with get_session() as session:
45
+ users = session.exec(select(User)).all()
46
+ return users
47
+
48
+ @staticmethod
49
+ def update_user(user_id: int, data: Dict[str, Any]) -> Optional[User]:
50
+ """Updates a User record by ID."""
51
+ with get_session() as session:
52
+ user_instance = session.get(User, user_id)
53
+ if not user_instance:
54
+ return None
55
+ for key, value in data.items():
56
+ setattr(user_instance, key, value)
57
+ session.add(user_instance)
58
+ session.commit()
59
+ session.refresh(user_instance)
60
+ return user_instance
61
+
62
+ @staticmethod
63
+ def delete_user(user_id: int) -> bool:
64
+ """Deletes a User record by ID. Returns True if successful."""
65
+ with get_session() as session:
66
+ user_instance = session.get(User, user_id)
67
+ if not user_instance:
68
+ return False
69
+ session.delete(user_instance)
70
+ session.commit()
71
+ return True
72
+
73
+ @staticmethod
74
+ def list_users() -> List[User]:
75
+ """Lists all User records."""
76
+ with get_session() as session:
77
+ users = session.exec(select(User)).all()
78
+ return users
79
+
80
+ create_db_and_tables()
@@ -0,0 +1,73 @@
1
+ from sqlmodel import SQLModel, Field, Relationship
2
+ from typing import Optional, List, Type, Any, Dict
3
+ from datetime import datetime, UTC
4
+
5
+ # Removed BaseManager import
6
+ from .utils import create_db_and_tables, get_session # Import get_session
7
+ from sqlmodel import Session, select # Import Session and select
8
+
9
+ class BaseModel(SQLModel):
10
+ id: int = Field(primary_key=True)
11
+ created: datetime = Field(default_factory=lambda: datetime.now(UTC))
12
+ modified: datetime = Field(default_factory=lambda: datetime.now(UTC))
13
+
14
+ class Vote(BaseModel, table=True):
15
+ __tablename__ = "votes"
16
+ user_id: int = Field(foreign_key="users.id")
17
+ comment_id: int = Field(foreign_key="comments.id")
18
+ value: int # -1, 0, 1
19
+ # Relationships
20
+ user: "User" = Relationship(back_populates="votes")
21
+ comment: "Comment" = Relationship(back_populates="votes")
22
+
23
+ class VoteManager:
24
+ @staticmethod
25
+ def create_vote(data: Dict[str, Any]) -> Vote:
26
+ """Creates a new Vote record."""
27
+ with get_session() as session:
28
+ vote_instance = Vote(**data)
29
+ session.add(vote_instance)
30
+ session.commit()
31
+ session.refresh(vote_instance)
32
+ return vote_instance
33
+
34
+ @staticmethod
35
+ def read_vote(vote_id: int) -> Optional[Vote]:
36
+ """Reads a Vote record by ID."""
37
+ with get_session() as session:
38
+ vote_instance = session.get(Vote, vote_id)
39
+ return vote_instance
40
+
41
+ @staticmethod
42
+ def update_vote(vote_id: int, data: Dict[str, Any]) -> Optional[Vote]:
43
+ """Updates a Vote record by ID."""
44
+ with get_session() as session:
45
+ vote_instance = session.get(Vote, vote_id)
46
+ if not vote_instance:
47
+ return None
48
+ for key, value in data.items():
49
+ setattr(vote_instance, key, value)
50
+ session.add(vote_instance)
51
+ session.commit()
52
+ session.refresh(vote_instance)
53
+ return vote_instance
54
+
55
+ @staticmethod
56
+ def delete_vote(vote_id: int) -> bool:
57
+ """Deletes a Vote record by ID."""
58
+ with get_session() as session:
59
+ vote_instance = session.get(Vote, vote_id)
60
+ if not vote_instance:
61
+ return False
62
+ session.delete(vote_instance)
63
+ session.commit()
64
+ return True
65
+
66
+ @staticmethod
67
+ def list_votes() -> List[Vote]:
68
+ """Lists all Vote records."""
69
+ with get_session() as session:
70
+ vote_instances = session.exec(select(Vote)).all()
71
+ return vote_instances
72
+
73
+ create_db_and_tables()
@@ -0,0 +1,2 @@
1
+ from .utils import DEFAULT_CONFIG
2
+ from .Actor import DatabaseActor
@@ -0,0 +1,36 @@
1
+ import os
2
+ from contextlib import contextmanager
3
+ from sqlmodel import Session, SQLModel, create_engine
4
+
5
+ from litepolis import get_config
6
+
7
+ DEFAULT_CONFIG = {
8
+ "database_url": "sqlite:///database.db"
9
+ }
10
+
11
+ if ("PYTEST_CURRENT_TEST" not in os.environ and
12
+ "PYTEST_VERSION" not in os.environ):
13
+ database_url = get_config("litepolis_database_default", "database_url")
14
+ else:
15
+ database_url = DEFAULT_CONFIG.get("database_url")
16
+ engine = create_engine(database_url,
17
+ pool_size=5,
18
+ max_overflow=10,
19
+ pool_timeout=30,
20
+ pool_pre_ping=True)
21
+
22
+ def connect_db():
23
+ engine = create_engine(database_url,
24
+ pool_size=5,
25
+ max_overflow=10,
26
+ pool_timeout=30,
27
+ pool_pre_ping=True)
28
+
29
+ def create_db_and_tables():
30
+ # SQLModel.metadata.create_all() has checkfirst=True by default
31
+ # so tables will only be created if they don't exist
32
+ SQLModel.metadata.create_all(engine)
33
+
34
+ @contextmanager
35
+ def get_session():
36
+ yield Session(engine)