# This file was generated by mettle.genes.db.GenPy3 [ver 2.2] on Thu Aug 11 12:14:36 2022
#  Target Database = postgresql
#
import datetime
import uuid
import time
import mettle.lib
import mettle.io
import mettle.db

from bs_audit.db.tables.tran import tTran

class dTranInsert:
    __slots__ = ("_dbcon", "_dbstmnt", "irec")

    def __init__(self, dbcon: mettle.db.IAConnect):
        """
        Constructor.

        :param dbcon: Mettle database connection object.
        """
        self._dbcon   = dbcon
        self._dbstmnt = None
        self.irec     = tTran()

    def __enter__(self):
        """
        With statement enter.
        """
        return self

    def __exit__(self, type, value, traceback):
        """
        With statement exit.
        """
        self._destroy()

    def _destroy(self):
        self._dbstmnt = None

    async def exec_deft(self,
                        id: int,
                        site_id: int,
                        who: str,
                        src: str,
                        tm_stamp: datetime.datetime) -> "dTranInsert":
        """
        Execute the query by setting all the inputs.

        :param id: int
        :param site_id: int
        :param who: str
        :param src: str
        :param tm_stamp: datetime.datetime
        :return: Self for convenience.
        """
        self.irec.id = id
        self.irec.site_id = site_id
        self.irec.who = who
        self.irec.src = src
        self.irec.tm_stamp = tm_stamp

        return await self.exec()

    async def exec(self, irec: tTran = None) -> "dTranInsert":
        """
        Execute the query, optionally passing in the input rec.

        :param irec:
        :return: Self for convenience.
        """
        if irec:
            self.irec._copy_from(irec)

        self._destroy()

        self._dbstmnt = await self._dbcon.statement("TranInsert", self._dbcon.STMNT_TYPE_CUD)

        self._dbstmnt.sql("""insert into audit.Tran (
  site_id,
  who,
  src,
  tm_stamp
) values (
  :site_id,
  :who,
  :src,
  :tm_stamp
)""")

        self.irec.tm_stamp = await self._dbcon.get_timestamp()

        self._dbstmnt.bind_in("site_id", self.irec.site_id, int, 4)
        self._dbstmnt.bind_in("who", self.irec.who, str, 128)
        self._dbstmnt.bind_in("src", self.irec.src, str, 128)
        self._dbstmnt.bind_in("tm_stamp", self.irec.tm_stamp, datetime.datetime)

        await self._dbcon.execute(self._dbstmnt)

        self.irec.id = await self._dbcon.post_get_sequence(self._dbstmnt, "audit.Tran", "id", 8)

        if irec:
            irec._copy_from(self.irec)

        return self

