Commit aa805e2e authored by Andreas Knüpfer's avatar Andreas Knüpfer
Browse files

Separate repository for the NocoDB metadata scripts

parent a22a35bd
Loading
Loading
Loading
Loading

.gitignore

0 → 100644
+2 −0
Original line number Diff line number Diff line
env.sh
__pycache__/
+1 −91
Original line number Diff line number Diff line
# nocodb_automation



## Getting started

To make it easy for you to get started with GitLab, here's a list of recommended next steps.

Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!

## Add your files

- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:

```
cd existing_repo
git remote add origin https://codebase.helmholtz.cloud/casus-datalad/nocodb_automation.git
git branch -M main
git push -uf origin main
```

## Integrate with your tools

- [ ] [Set up project integrations](https://codebase.helmholtz.cloud/casus-datalad/nocodb_automation/-/settings/integrations)

## Collaborate with your team

- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)

## Test and Deploy

Use the built-in continuous integration in GitLab.

- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)

***

# Editing this README

When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.

## Suggestions for a good README

Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.

## Name
Choose a self-explaining name for your project.

## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.

## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.

## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.

## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.

## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.

## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.

## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.

## Contributing
State if you are open to contributions and what your requirements are for accepting them.

For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.

You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.

## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.

## License
For open source projects, say how it is licensed.

## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
Separate repository for the DataLad + Gitlab integration for NocoDB. In this way it can be installed as a submodule in DataLad repositories that want to use it.

enter_dataset.py

0 → 100755
+49 −0
Original line number Diff line number Diff line
#!/usr/bin/env python3

import argparse
import json
import os
import sys

import prepare_json
import nocodb

"""
Read one ore more 'DATASET.json' files and add it's contents to an existing NocoDB table
"""

if __name__ == '__main__':

    nocodb_host = os.getenv('NOCODB_HOST', 'http://localhost')
    nocodb_token = os.getenv('NOCODB_TOKEN', 'none')
    nocodb_ssl_cert = os.getenv('NOCODB_SSL_CERT', True)

    parser = argparse.ArgumentParser()
    parser.add_argument("inputs", nargs='+', help="Input JSON files")
    parser.add_argument("-t", "--table", required=True, help="Existing Nocodb table id, then insert into this table")
    parser.add_argument("-p", "--prefix", default="",
                        help="Prefix to the URL field which is usually the host part of the URL but can be any prefix string")
    args = parser.parse_args()

    tableid = args.table
    table = nocodb.Table( tableid, host=nocodb_host, auth_token=nocodb_token, verify=nocodb_ssl_cert )

    for f in args.inputs:

        print("    Read ", f)
        with open(f) as ff:

            input = json.load(ff)

            # set special extra fields:
            extra= {}
            extra['URL']= args.prefix + ": " + f 
            extra['status']= "current"
            extra['branch']= "blahblah"

            data = prepare_json.prepare_input( input, extra=extra )

            #print(f"Enter input from {f} into table {args.table}")
            #print(f"        insert: ", json.dumps(data, indent=4) )
            res = table.insert(data)
            #print("    RESULT: ", json.dumps(res, indent=4))

env.sh.template

0 → 100644
+3 −0
Original line number Diff line number Diff line
export NOCODB_TOKEN="insert API access token here"
export NOCODB_HOST="https://my.nocodb.server.url"
export NOCODB_SSL_CERT="file/with/SSL_CA_cert" #optional, don't set if the host CA certs work, set to "" to disable SSL cert checking

nocodb.py

0 → 100644
+447 −0
Original line number Diff line number Diff line
# nocodb class

from enum import Enum

import requests
import json

"""
Class for access to a NOCODB instance
"""


class Nocodb:

    def __init__(self, host, auth_token, verify=True):
        self.host = host
        self.auth_token = auth_token
        self.verify = verify

        self.session = requests.Session()
        self.session.headers.update({"accept": "application/json", "xc-token": self.auth_token})
        self.session.verify = self.verify

    """ 
    [META] List Bases
    List all base meta data
    https://meta-apis-v2.nocodb.com/#tag/Base/operation/base-list
    GET http://localhost:8080/api/v2/meta/bases/
    """

    def list_bases(self) -> dict:

        url = f"{self.host}/api/v2/meta/bases/"

        res = self.session.get(url, params={}).json()

        # print(json.dumps(res, indent=4))

        ret = {}
        for i in res['list']:
            # print( i['title'], i['id'] )
            ret[i['id']] = i['title']

        return ret

    """
    [META] Create Base
    Create a new base
    https://meta-apis-v2.nocodb.com/#tag/Base/operation/base-create
    POST http://localhost:8080/api/v2/meta/bases/
    """

    def create_base(self, title, color=None, description=None, base_type=None) -> dict:

        url = f"{self.host}/api/v2/meta/bases/"

        data = {"title": title}
        if color:
            data["color"] = color
        if description:
            data["description"] = description
        # TODO this won't be returned
        if base_type:
            data["type"] = base_type.name

        res = self.session.post(url, data=data).json()

        if 'msg' in res and res['msg'] == 'Invalid token':
            raise Exception("Invalid token")

        # print( json.dumps(res, indent=4 ) )

        return res

    def get_base_object(self, title):

        # check if such a table exists
        all_bases = self.list_bases()

        for base_id, base_title in all_bases.items():
            if title == base_title:
                return Base(base_id, nocodb=self)
        return None

    """
    [META] Delete Base
    Delete the given base
    https://meta-apis-v2.nocodb.com/#tag/Base/operation/base-delete
    DELETE http://localhost:8080/api/v2/meta/bases/{baseId}
    """

    def delete_base(self, base_id) -> dict:
        url = f'{self.host}/api/v2/meta/bases/{base_id}'
        headers = {"accept": "application/json", "xc-token": self.auth_token}
        return requests.delete(url, headers=headers).json()


"""
Class for access to a NOCODB base == one database in the Nocodb instance
"""


class Base:

    def __init__(self, base_id, nocodb=None, host=None, auth_token=None, verify=True):

        # Don't keep the parent Nocodb object because we can work without it
        # Accessing a Base only needs the baseid and the auth_token
        # Thus like this one can create a Base object without a Nocodb object.
        # #self.nocodb= nocodb
        self.base_id = base_id
        self.verify = verify
        self.session = None

        if nocodb:

            self.host = nocodb.host
            self.auth_token = nocodb.auth_token
            self.verify = nocodb.verify
            self.session = nocodb.session  # re-use the same session

        else:

            assert None != host
            assert None != auth_token

            self.host = host
            self.auth_token = auth_token

            self.session = requests.Session()
            self.session.headers.update({"accept": "application/json", "xc-token": self.auth_token})
            self.session.verify = self.verify

        self.info = self.get_base_info()
        self.metadata = self.get_base()

    class Type(Enum):
        database = 'database'
        documentation = 'documentation'
        dashboard = 'dashboard'

    def debug(self):
        print("class Base: ", self.base_id)
        print(json.dumps(self.info, indent=4))
        print(json.dumps(self.metadata, indent=4))

    """
    [META] Get Base info
    Get info such as node version, arch, platform, is docker, rootdb and package version of a given base
    https://meta-apis-v2.nocodb.com/#tag/Base/operation/base-meta-get
    GET http://localhost:8080/api/v2/meta/bases/{baseId}/info
    """

    def get_base_info(self) -> dict:

        url = f"{self.host}/api/v2/meta/bases/{self.base_id}/info"

        res = self.session.get(url, params={}).json()

        # print( json.dumps(res, indent=4 ) )

        return res

    """
    [META] Get Base
    Get the info of a given base
    https://meta-apis-v2.nocodb.com/#tag/Base/operation/base-read
    GET http://localhost:8080/api/v2/meta/bases/{baseId}
    """

    def get_base(self) -> dict:

        url = f"{self.host}/api/v2/meta/bases/{self.base_id}"

        res = self.session.get(url, params={}).json()

        # print( json.dumps(res, indent=4 ) )

        return res

    """
    [META] List Tables
    List all tables in a given base
    https://meta-apis-v2.nocodb.com/#tag/DB-Table/operation/db-table-list
    GET http://localhost:8080/api/v2/meta/bases/{baseId}/tables
    """

    def list_tables(self) -> dict:

        url = f"{self.host}/api/v2/meta/bases/{self.base_id}/tables"

        res = self.session.get(url, params={}).json()

        # print( json.dumps(res, indent=4 ) )

        ret = {}
        for i in res['list']:
            # print( i['title'], i['id'] )
            ret[i['title']] = i['id']

        return ret

    """
    [META] Create Table
    Create a new table in a given base
    https://meta-apis-v2.nocodb.com/#tag/DB-Table/operation/db-table-create
    POST http://localhost:8080/api/v2/meta/bases/{baseId}/tables
    TBD
    """

    def create_table(self, name, columns, color=None):

        url = f"{self.host}/api/v2/meta/bases/{self.base_id}/tables"

        data = {
            "columns": columns,
            "table_name": name,
            "title": name
        }
        # print( json.dumps(data, indent=4 ) )

        if color:
            data["color"] = color

        res = self.session.post(url, json=data).json()

        if "errors" in res or "msg" in res:
            print("ERROR: ")
            print(json.dumps(res, indent=4))
            return None

        # print( json.dumps(res, indent=4 ) )
        # print(" --> newly created table id ", res['id'] )

        return res['id']

    def get_table_object(self, title):

        # check if such a table exists
        alltables = self.list_tables()

        if title in alltables:

            return Table(alltables[title], base=self)

        else:

            return None


"""
Class for access to a NOCODB table
"""


class Table:

    def __init__(self, tableid, base=None, host=None, auth_token=None, verify=True):

        # Don't keep the parent Base object because we can work without it
        # Accessing a Table only needs the tableid and the auth_token
        # Thus like this one can create a Table object without a Base object.
        # self.base= base
        self.tableid = tableid
        self.verify = verify
        self.session = None

        if base:

            self.host = base.host
            self.auth_token = base.auth_token
            self.verify = base.verify
            self.session = base.session

        else:

            assert None != host
            assert None != auth_token

            self.host = host
            self.auth_token = auth_token

            self.session = requests.Session()
            self.session.headers.update({"accept": "application/json", "xc-token": self.auth_token})
            self.session.verify = self.verify

        # connection test
        res = self.count()
        assert 'count' in res
        assert 'msg' not in res

    def debug(self):
        # print("class Table: ", self.tableid )
        metadata = self.read_table()
        metadata['columnsById'] = "<skipped>"
        print(json.dumps(metadata, indent=4))

    """
    [META] Read Table
    Read the table meta data by the given table ID
    https://meta-apis-v2.nocodb.com/#tag/DB-Table/operation/db-table-read
    GET http://localhost:8080/api/v2/meta/tables/{tableId}
    """

    def read_table(self):

        url = f"{self.host}/api/v2/meta/tables/{self.tableid}"

        res = self.session.get(url, params={}).json()

        # print( json.dumps(res, indent=4 ) )

        return res

    """
    [DATA] Create Table Records
    https://data-apis-v2.nocodb.com/#tag/Table-Records/operation/db-data-table-row-list
    POST http://localhost:8080/api/v2/tables/{tableId}/records
    """

    def insert(self, data) -> dict:

        url = f"{self.host}/api/v2/tables/{self.tableid}/records"

        # print( json.dumps(data, indent=4 ) )

        res = self.session.post(url, json=data).json()

        # print( json.dumps(res, indent=4 ) )

        return res

    """
    [DATA] Update Table Records
    https://data-apis-v2.nocodb.com/#tag/Table-Records/operation/db-data-table-row-update
    PATCH http://localhost:8080/api/v2/tables/{tableId}/records
    """

    def update(self, data):

        # print("AA")
        # print("TABLE DELETE ", json.dumps(list,indent=4) )
        # print("    JSON ", json.dumps(list))

        url = f"{self.host}/api/v2/tables/{self.tableid}/records"

        # print( json.dumps(data, indent=4 ) )
        res= self.session.patch(url, data=data).json()

        return res

    """
    [DATA] Read Table Record
    This API endpoint allows you to retrieve a single record identified by Record-ID, serving as unique identifier for the record from a specified table.
    https://data-apis-v2.nocodb.com/#tag/Table-Records/operation/db-data-table-row-read
    GET http://localhost:8080/api/v2/tables/{tableId}/records/{recordId}
    """

    def read_table_record(self, primary_key: any) -> dict:
        url = f"{self.host}/api/v2/tables/{self.tableid}/records/{primary_key}"
        return self.session.get(url).json()

    def update_record(self, pk: int, key: str, value: object) -> dict:
        # record = self.read_table_record(pk)
        # if 'CreatedAt' in record:
        #     del record['CreatedAt']
        # if 'UpdatedAt' in record:
        #     del record['UpdatedAt']
        # if key == 'Primary Key':
        #     raise ValueError("Primary Key is not overridable")
        # record[key] = value
        record = [{'Primary Key': pk, f'{key}': value}]
        return self.update(record)

    """ 
    [DATA] Count Table Records
    This API endpoint allows you to retrieve the total number of records from a specified table or a view. You can narrow down search results by applying where query parameter
    https://data-apis-v2.nocodb.com/#tag/Table-Records/operation/db-data-table-row-count
    Get http://localhost:8080/api/v2/tables/{tableId}/records/count
    """

    def count(self, where=None):

        url = f"{self.host}/api/v2/tables/{self.tableid}/records/count"

        params = {}

        if where:
            params['where'] = where

        res = self.session.get(url, params=params).json()

        return res

    """ 
    [DATA] List Table Records
    This API endpoint allows you to retrieve records from a specified table. 
    https://data-apis-v2.nocodb.com/#tag/Table-Records/operation/db-data-table-row-list
    Get http://localhost:8080/api/v2/tables/{tableId}/records
    """

    def list(self, fields=None, sort=None, where=None, offset=0, limit=None):

        url = f"{self.host}/api/v2/tables/{self.tableid}/records"

        params = {}

        if fields:
            params['fields'] = fields
        if sort:
            params['sort'] = sort
        if where:
            params['where'] = where
            print("                WHERE ", where)
        if limit:
            params['limit'] = limit

        res = self.session.get(url, params=params).json()

        # print(" #### page info #### ")
        # print( json.dumps(res['pageInfo'], indent=4 ) )
        # print(" ######## ")

        return res


"""
[DATA] Delete Table Records
This API endpoint allows deleting existing records within a specified table identified by 
an array of Record-IDs, serving as unique identifier for the record. Records to be deleted are input as an array of record-identifiers.
https://data-apis-v2.nocodb.com/#tag/Table-Records/operation/db-data-table-row-delete
DELETE http://localhost:8080/api/v2/tables/{tableId}/records
"""


def delete(self, list=None):
    url = f"{self.host}/api/v2/tables/{self.tableid}/records"

    # print("TABLE DELETE ", json.dumps(list,indent=4) )
    # print("    JSON ", json.dumps(list))

    if list is None:
        res = self.session.delete(url)
    else:
        res = self.session.delete(url, data=list)

    return res
Loading