Skip to content

Commit

Permalink
Delete and Update actions + Refactor (#6)
Browse files Browse the repository at this point in the history
* Refactor code for improved readability and consistency in Record, Column, and Base classes

* Fix record API calls

* Fix column test

---------

Co-authored-by: infeeeee <gyetpet@mailbox.org>
  • Loading branch information
ihor-sokoliuk and infeeeee authored Dec 31, 2024
1 parent 11d42bf commit e7713df
Show file tree
Hide file tree
Showing 6 changed files with 158 additions and 93 deletions.
5 changes: 3 additions & 2 deletions .github/workflows/unittests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ name: Unit tests
on:
# push:
# branches: ["main"]
pull_request:
branches: ["main"]
pull_request_target:
types: [labeled]
workflow_dispatch:

permissions:
Expand All @@ -13,6 +13,7 @@ permissions:
jobs:
tests:
name: Unit tests on Cloud
if: contains(github.event.pull_request.labels.*.name, 'safe to test')
strategy:
max-parallel: 1
matrix:
Expand Down
64 changes: 35 additions & 29 deletions nocodb/Base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from nocodb import NocoDB

Expand All @@ -8,45 +9,48 @@
from nocodb.Table import Table

import logging

_logger = logging.getLogger(__name__)
_logger.addHandler(logging.NullHandler())


class Base:
def __init__(self, noco_db: "NocoDB",
**kwargs) -> None:
def __init__(self, noco_db: "NocoDB", **kwargs) -> None:

self.noco_db = noco_db
self.base_id = kwargs["id"]
self.title = kwargs["title"]
self.metadata = kwargs

def duplicate(self,
exclude_data: bool = True,
exclude_views: bool = True,
exclude_hooks: bool = True
) -> "Base":

r = self.noco_db.call_noco(path=f"meta/duplicate/{self.base_id}",
method="POST",
json={
"excludeData": exclude_data,
"excludeViews": exclude_views,
"excludeHooks": exclude_hooks})
def duplicate(
self,
exclude_data: bool = True,
exclude_views: bool = True,
exclude_hooks: bool = True,
) -> "Base":

r = self.noco_db.call_noco(
path=f"meta/duplicate/{self.base_id}",
method="POST",
json={
"excludeData": exclude_data,
"excludeViews": exclude_views,
"excludeHooks": exclude_hooks,
},
)
_logger.info(f"Base {self.title} duplicated")

return self.noco_db.get_base(base_id=r.json()["base_id"])

def delete(self) -> bool:
r = self.noco_db.call_noco(path=f"meta/bases/{self.base_id}",
method="DELETE")
r = self.noco_db.call_noco(path=f"meta/bases/{self.base_id}", method="DELETE")
_logger.info(f"Base {self.title} deleted")
return r.json()

def update(self, **kwargs) -> None:
self.noco_db.call_noco(path=f"meta/bases/{self.base_id}",
method="PATCH",
json=kwargs)
self.noco_db.call_noco(
path=f"meta/bases/{self.base_id}", method="PATCH", json=kwargs
)

def get_base_info(self) -> dict:
r = self.noco_db.call_noco(path=f"meta/bases/{self.base_id}/info")
Expand All @@ -55,13 +59,11 @@ def get_base_info(self) -> dict:
def get_tables(self) -> list[Table]:
r = self.noco_db.call_noco(path=f"meta/bases/{self.base_id}/tables")
tables = [Table(noco_db=self.noco_db, **t) for t in r.json()["list"]]
_logger.debug(f"Tables in base {self.title}: "
+ str([t.title for t in tables]))
_logger.debug(f"Tables in base {self.title}: " + str([t.title for t in tables]))
return tables

def get_table(self, table_id: str) -> Table:
r = self.noco_db.call_noco(
path=f"meta/tables/{table_id}")
r = self.noco_db.call_noco(path=f"meta/tables/{table_id}")
return Table(noco_db=self.noco_db, **r.json())

def get_table_by_title(self, title: str) -> Table:
Expand All @@ -70,9 +72,13 @@ def get_table_by_title(self, title: str) -> Table:
except StopIteration:
raise Exception(f"Table with name {title} not found!")

def create_table(self, table_name: str,
columns: list[dict] | None = None, add_default_columns: bool = True,
**kwargs) -> Table:
def create_table(
self,
table_name: str,
columns: list[dict] | None = None,
add_default_columns: bool = True,
**kwargs,
) -> Table:
kwargs["table_name"] = table_name

if not columns:
Expand All @@ -83,7 +89,7 @@ def create_table(self, table_name: str,
else:
kwargs["columns"] = columns

r = self.noco_db.call_noco(path=f"meta/bases/{self.base_id}/tables",
method="POST",
json=kwargs)
r = self.noco_db.call_noco(
path=f"meta/bases/{self.base_id}/tables", method="POST", json=kwargs
)
return self.get_table(table_id=r.json()["id"])
51 changes: 36 additions & 15 deletions nocodb/Column.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@


from typing import TYPE_CHECKING

if TYPE_CHECKING:
from nocodb.Table import Table
from nocodb import NocoDB
Expand All @@ -17,7 +18,7 @@ def __str__(self) -> str:


class Column:
def __init__(self, noco_db: "NocoDB",**kwargs) -> None:
def __init__(self, noco_db: "NocoDB", **kwargs) -> None:
self.noco_db = noco_db
self.title = kwargs["title"]
self.column_id = kwargs["id"]
Expand All @@ -31,7 +32,7 @@ def __init__(self, noco_db: "NocoDB",**kwargs) -> None:

if "colOptions" in kwargs and "fk_related_model_id" in kwargs["colOptions"]:
self.linked_table_id = kwargs["colOptions"]["fk_related_model_id"]

def get_linked_table(self) -> Table:
if hasattr(self, "linked_table_id"):
return self.noco_db.get_table(self.linked_table_id)
Expand All @@ -41,25 +42,46 @@ def get_linked_table(self) -> Table:
@staticmethod
def get_id_metadata() -> list[dict]:
return [
{'title': 'Id', 'column_name': 'id', 'uidt': str(Column.DataType.ID),
'dt': 'int4', 'np': '11', 'ns': '0', 'clen': None,
'pk': True, 'pv': None, 'rqd': True, 'ct': 'int(11)', 'ai': True,
'dtx': 'integer', 'dtxp': '11', },
{'title': 'Title', 'column_name': 'title', 'uidt': str(Column.DataType.SingleLineText),
'dt': 'character varying', 'np': None, 'ns': None, 'clen': '45',
'pk': False, 'pv': True, 'rqd': False, 'ct': 'varchar(45)', 'ai': False,
'dtx': 'specificType', 'dtxp': '45', }
{
"title": "Id",
"column_name": "id",
"uidt": str(Column.DataType.ID),
"dt": "int4",
"np": "11",
"ns": "0",
"clen": None,
"pk": True,
"pv": None,
"rqd": True,
"ct": "int(11)",
"ai": True,
"dtx": "integer",
"dtxp": "11",
},
{
"title": "Title",
"column_name": "title",
"uidt": str(Column.DataType.SingleLineText),
"dt": "character varying",
"np": None,
"ns": None,
"clen": "45",
"pk": False,
"pv": True,
"rqd": False,
"ct": "varchar(45)",
"ai": False,
"dtx": "specificType",
"dtxp": "45",
},
]

class DataType:
Formula = DataType("Formula")

LinkToAnotherRecord = DataType("LinkToAnotherRecord")
Links = DataType("Links")

Lookup = DataType("Lookup")
Rollup = DataType("Rollup")

Attachment = DataType("Attachment")
AutoNumber = DataType("AutoNumber")
Barcode = DataType("Barcode")
Expand All @@ -85,6 +107,7 @@ class DataType:
LongText = DataType("LongText")
MultiSelect = DataType("MultiSelect")
Number = DataType("Number")
Order = DataType("Order")
Percent = DataType("Percent")
PhoneNumber = DataType("PhoneNumber")
QrCode = DataType("QrCode")
Expand All @@ -103,5 +126,3 @@ def get_data_type(cls, uidt: str) -> DataType:
return getattr(cls, uidt)
else:
raise Exception(f"Invalid datatype {uidt}")


35 changes: 23 additions & 12 deletions nocodb/Record.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import TYPE_CHECKING, Any

from nocodb.Column import Column

if TYPE_CHECKING:
from nocodb.Table import Table

Expand All @@ -15,24 +16,32 @@ def __init__(self, table: "Table", **kwargs) -> None:
self.metadata = kwargs

def link_record(self, column: Column, link_record: "Record") -> bool:
path = (f"tables/{self.table.table_id}/links/" +
f"{column.column_id}/records/{self.record_id}")
r = self.noco_db.call_noco(path=path,
method="POST", json={"Id": link_record.record_id})
path = (
f"tables/{self.table.table_id}/links/"
+ f"{column.column_id}/records/{self.record_id}"
)
r = self.noco_db.call_noco(
path=path, method="POST", json={"Id": link_record.record_id}
)

return r.json()

def link_records(self, column: Column, link_records: list["Record"]) -> bool:
path = (f"tables/{self.table.table_id}/links/" +
f"{column.column_id}/records/{self.record_id}")
r = self.noco_db.call_noco(path=path,
method="POST", json=[{"Id": l.record_id} for l in link_records])
path = (
f"tables/{self.table.table_id}/links/"
+ f"{column.column_id}/records/{self.record_id}"
)
r = self.noco_db.call_noco(
path=path, method="POST", json=[{"Id": l.record_id} for l in link_records]
)

return r.json()

def get_linked_records(self, column: Column) -> list[Record]:
path = (f"tables/{self.table.table_id}/links/" +
f"{column.column_id}/records/{self.record_id}")
path = (
f"tables/{self.table.table_id}/links/"
+ f"{column.column_id}/records/{self.record_id}"
)
r = self.noco_db.call_noco(path=path)

if "list" in r.json():
Expand Down Expand Up @@ -64,5 +73,7 @@ def get_attachments(self, field: str, encoding: str = "utf-8") -> list[str]:
if not isinstance(value_list, list):
raise Exception("Invalid field value")

return [self.noco_db.get_file(p["signedPath"], encoding=encoding)
for p in value_list]
return [
self.noco_db.get_file(p["signedPath"], encoding=encoding)
for p in value_list
]
Loading

0 comments on commit e7713df

Please sign in to comment.