<filename>src/scilab_datastoremod/_OLD_datastore_JSON.py
import os
import json

from .datastore_base import _DatastoreBase


# =========================================================
#                      G L O B A L S
# =========================================================
_DB_TYPE_: str = 'json'

_FORMAT_MAP_ = {
    'str': str,         # strings (e.g. "some long string")
    'strIDX': str,      # strings as index (for SQL data stores)
    'int': int,         # integers (e.g. 1, 2, 3, ... gazillion ... maybe ;-)
    'intIDX': int,      # integers as index (for SQL data stores)
    'float': float,     # floats (e.g. 0.1. 0.22, 0.333, ... )
    'bool': bool,       # booleans (e.g. True|False, Yes|No, etc.)
}


# =========================================================
#        M A I N   C L A S S   D E F I N I T I O N
# =========================================================
class Datastore(_DatastoreBase):
    def __init__(self, dbFlds, dbName, force=True):
        """Initialize JSON data store.

        Args:
            dbFlds:  Dict with field names (as keys) and (pseudo) data types
                     Example: {'fld1': 'str', 'fld2': 'float', 'fld3': 'int'}
            dbName:  JSON file name
            force:   If TRUE, JSON file will be created if it doesn't exist

        Raises:
            OSError: If unable to access or save data to JSON file.
        """
        self._check_db(dbName, force, _DB_TYPE_)
        super().__init__(dbFlds, _FORMAT_MAP_, None, dbName, _DB_TYPE_)

    def _read_json(self):
        try:
            dbFile = open(self._name, "r")
            data = json.load(dbFile)

        except json.JSONDecodeError as e:
            raise OSError("Failed to read data from '{}'!\n{}".format(self._name, e))

        else:
            dbFile.close()

        return data

    def _write_json(self, data=None):
        try:
            dbFile = open(self._name, "w")
            json.dump(data, dbFile)

        except OSError as e:
            raise OSError("Failed to write data to '{}'!\n{}".format(self._name, e))

        else:
            dbFile.close()

    def _process_data(self, dataIn=None):
        dataOut = []

        # Filter each row to only hold approved keys using dictionary
        # comprehension and, of course, a common set of keys ;-)
        for row in dataIn:
            commonFlds = list(set(row.keys()) & set(self._flds))

            if len(commonFlds) > 0:
                dataOut.append({key: row[key] for key in commonFlds})

        return dataOut

    def total_records(self):
        """Count number of records in JSON file.

        Raises:
            OSError: If unable to access or read data from JSON file.
        """
        jsonData = self._read_json() if os.path.exists(self._name) else None

        return len(jsonData)

    def trim_records(self, numRecs=0, attribs=None):
        """Trim data records from JSON file.

        Args:
            numRecs:  Number of records to trim
            attribs:
                'first' - If TRUE, trim first 'numRecs' records.
                          Else trim last 'numRecs' records.

        Raises:
            OSError: If unable to access or read data from JSON file.
        """
        if numRecs > 0:
            first = self._parse_attribs(attribs, 'first', True)

            try:
                jsonData = self._read_json() if os.path.exists(self._name) else None

                if jsonData is not None:
                    maxRec = len(jsonData)
                    if numRecs >= maxRec:
                        data = []
                    else:
                        startRec = numRecs if first else 0
                        endRec = maxRec if first else max(1, maxRec - numRecs)
                        data = self._process_data(jsonData[startRec:endRec])

                    self._write_json(data)

            except OSError as e:
                raise OSError("Failed to read data from '{}'!\n{}".format(self._name, e))

    def store_data(self, data=None):
        """Save data to JSON file.

        Args:
            data:    List with one or more data rows

        Raises:
            OSError: If unable to access or save data to JSON file.
        """
        if data is None:
            data = []

        try:
            oldData = self._read_json() if os.path.exists(self._name) else None

        except OSError:                 # We'll just 'overwrite' the file
            oldData = None              # if it's empty or if we can't read it.

        try:
            newData = self._process_data(data)
            self._write_json(newData if oldData is None else oldData + newData)

        except OSError as e:
            raise OSError("Failed to access '{}'!\n{}".format(self._name, e))

    def get_data(self, numRecs=1, attribs=None):
        """Retrieve data records from JSON file.

        Args:
            numRecs:  Number of records to retrieve
            attribs:
                'first'     - If TRUE, retrieve first 'numRecs' records.
                              Else retrieve last 'numRecs' records.
        Returns:
            list:     List of all records retrieved

        Raises:
            OSError: If unable to access or read data from JSON file.
        """
        first = self._parse_attribs(attribs, 'first', True)

        try:
            jsonData = self._read_json() if os.path.exists(self._name) else None

            if jsonData is None:
                data = []
            else:
                lastRec = numRecs if first else len(jsonData)
                firstRec = 0 if first else max(0, lastRec - numRecs)
                data = self._process_data(jsonData[firstRec:lastRec])

        except OSError as e:
            raise OSError("Failed to read data from '{}'!\n{}".format(self._name, e))

        return data

<filename>src/scilab_datastoremod/_OLD_datastore_JSON.py
import os
import json

from .datastore_base import _DatastoreBase


# =========================================================
#                      G L O B A L S
# =========================================================
_DB_TYPE_: str = 'json'

_FORMAT_MAP_ = {
    'str': str,         # strings (e.g. "some long string")
    'strIDX': str,      # strings as index (for SQL data stores)
    'int': int,         # integers (e.g. 1, 2, 3, ... gazillion ... maybe ;-)
    'intIDX': int,      # integers as index (for SQL data stores)
    'float': float,     # floats (e.g. 0.1. 0.22, 0.333, ... )
    'bool': bool,       # booleans (e.g. True|False, Yes|No, etc.)
}


# =========================================================
#        M A I N   C L A S S   D E F I N I T I O N
# =========================================================
class Datastore(_DatastoreBase):
    def __init__(self, dbFlds, dbName, force=True):
        """Initialize JSON data store.

        Args:
            dbFlds:  Dict with field names (as keys) and (pseudo) data types
                     Example: {'fld1': 'str', 'fld2': 'float', 'fld3': 'int'}
            dbName:  JSON file name
            force:   If TRUE, JSON file will be created if it doesn't exist

        Raises:
            OSError: If unable to access or save data to JSON file.
        """
        self._check_db(dbName, force, _DB_TYPE_)
        super().__init__(dbFlds, _FORMAT_MAP_, None, dbName, _DB_TYPE_)

    def _read_json(self):
        try:
            dbFile = open(self._name, "r")
            data = json.load(dbFile)

        except json.JSONDecodeError as e:
            raise OSError("Failed to read data from '{}'!\n{}".format(self._name, e))

        else:
            dbFile.close()

        return data

    def _write_json(self, data=None):
        try:
            dbFile = open(self._name, "w")
            json.dump(data, dbFile)

        except OSError as e:
            raise OSError("Failed to write data to '{}'!\n{}".format(self._name, e))

        else:
            dbFile.close()

    def _process_data(self, dataIn=None):
        dataOut = []

        # Filter each row to only hold approved keys using dictionary
        # comprehension and, of course, a common set of keys ;-)
        for row in dataIn:
            commonFlds = list(set(row.keys()) & set(self._flds))

            if len(commonFlds) > 0:
                dataOut.append({key: row[key] for key in commonFlds})

        return dataOut

    def total_records(self):
        """Count number of records in JSON file.

        Raises:
            OSError: If unable to access or read data from JSON file.
        """
        jsonData = self._read_json() if os.path.exists(self._name) else None

        return len(jsonData)

    def trim_records(self, numRecs=0, attribs=None):
        """Trim data records from JSON file.

        Args:
            numRecs:  Number of records to trim
            attribs:
                'first' - If TRUE, trim first 'numRecs' records.
                          Else trim last 'numRecs' records.

        Raises:
            OSError: If unable to access or read data from JSON file.
        """
        if numRecs > 0:
            first = self._parse_attribs(attribs, 'first', True)

            try:
                jsonData = self._read_json() if os.path.exists(self._name) else None

                if jsonData is not None:
                    maxRec = len(jsonData)
                    if numRecs >= maxRec:
                        data = []
                    else:
                        startRec = numRecs if first else 0
                        endRec = maxRec if first else max(1, maxRec - numRecs)
                        data = self._process_data(jsonData[startRec:endRec])

                    self._write_json(data)

            except OSError as e:
                raise OSError("Failed to read data from '{}'!\n{}".format(self._name, e))

    def store_data(self, data=None):
        """Save data to JSON file.

        Args:
            data:    List with one or more data rows

        Raises:
            OSError: If unable to access or save data to JSON file.
        """
        if data is None:
            data = []

        try:
            oldData = self._read_json() if os.path.exists(self._name) else None

        except OSError:                 # We'll just 'overwrite' the file
            oldData = None              # if it's empty or if we can't read it.

        try:
            newData = self._process_data(data)
            self._write_json(newData if oldData is None else oldData + newData)

        except OSError as e:
            raise OSError("Failed to access '{}'!\n{}".format(self._name, e))

    def get_data(self, numRecs=1, attribs=None):
        """Retrieve data records from JSON file.

        Args:
            numRecs:  Number of records to retrieve
            attribs:
                'first'     - If TRUE, retrieve first 'numRecs' records.
                              Else retrieve last 'numRecs' records.
        Returns:
            list:     List of all records retrieved

        Raises:
            OSError: If unable to access or read data from JSON file.
        """
        first = self._parse_attribs(attribs, 'first', True)

        try:
            jsonData = self._read_json() if os.path.exists(self._name) else None

            if jsonData is None:
                data = []
            else:
                lastRec = numRecs if first else len(jsonData)
                firstRec = 0 if first else max(0, lastRec - numRecs)
                data = self._process_data(jsonData[firstRec:lastRec])

        except OSError as e:
            raise OSError("Failed to read data from '{}'!\n{}".format(self._name, e))

        return data

# ========================================================= #                      G L O B A L S # ========================================================= # strings (e.g. "some long string") # strings as index (for SQL data stores) # integers (e.g. 1, 2, 3, ... gazillion ... maybe ;-) # integers as index (for SQL data stores) # floats (e.g. 0.1. 0.22, 0.333, ... ) # booleans (e.g. True|False, Yes|No, etc.) # ========================================================= #        M A I N   C L A S S   D E F I N I T I O N # ========================================================= Initialize JSON data store.          Args:             dbFlds:  Dict with field names (as keys) and (pseudo) data types                      Example: {'fld1': 'str', 'fld2': 'float', 'fld3': 'int'}             dbName:  JSON file name             force:   If TRUE, JSON file will be created if it doesn't exist          Raises:             OSError: If unable to access or save data to JSON file. # Filter each row to only hold approved keys using dictionary # comprehension and, of course, a common set of keys ;-) Count number of records in JSON file.          Raises:             OSError: If unable to access or read data from JSON file. Trim data records from JSON file.          Args:             numRecs:  Number of records to trim             attribs:                 'first' - If TRUE, trim first 'numRecs' records.                           Else trim last 'numRecs' records.          Raises:             OSError: If unable to access or read data from JSON file. Save data to JSON file.          Args:             data:    List with one or more data rows          Raises:             OSError: If unable to access or save data to JSON file. # We'll just 'overwrite' the file # if it's empty or if we can't read it. Retrieve data records from JSON file.          Args:             numRecs:  Number of records to retrieve             attribs:                 'first'     - If TRUE, retrieve first 'numRecs' records.                               Else retrieve last 'numRecs' records.         Returns:             list:     List of all records retrieved          Raises:             OSError: If unable to access or read data from JSON file.