示例#1
0
    def __schemaCreate(self, schemaDefObj):
        """Create table schema using schema definition"""
        try:
            tableIdList = schemaDefObj.getSchemaIdList()
            sqlGen = SqlGenAdmin(self.__verbose)
            sqlL = sqlGen.createDatabaseSQL(schemaDefObj.getDatabaseName())
            for tableId in tableIdList:
                tableDefObj = schemaDefObj.getSchemaObject(tableId)
                sqlL.extend(
                    sqlGen.createTableSQL(
                        databaseName=schemaDefObj.getDatabaseName(),
                        tableDefObj=tableDefObj))

            logger.debug("Schema creation SQL string\n %s\n\n",
                         "\n".join(sqlL))
            with Connection(cfgOb=self.__cfgOb,
                            resourceName=self.__resourceName) as client:
                myQ = MyDbQuery(dbcon=client, verbose=self.__verbose)
                #
                # Permit warnings to support "drop table if exists" for missing tables.
                #
                myQ.setWarning("ignore")
                ret = myQ.sqlCommand(sqlCommandList=sqlL)
                logger.debug("\n\n+INFO mysql server returns %r\n", ret)
                self.assertTrue(ret)
        except Exception as e:
            logger.exception("Failing with %s", str(e))
            self.fail()
示例#2
0
    def __batchFileImport(self,
                          tableId,
                          tableLoadPath,
                          sqlFilePath=None,
                          containerNameList=None,
                          deleteOpt="all"):
        """Batch load the input table using data in the input loadable data file.

        if sqlFilePath is provided then any generated SQL commands are preserved in this file.

        deleteOpt None|'selected'| 'all' or 'truncate'
        """
        startTime = time.time()
        databaseName = self.__sD.getDatabaseName()
        sqlGen = SqlGenAdmin(self.__verbose)

        databaseName = self.__sD.getDatabaseName()
        tableDefObj = self.__sD.getSchemaObject(tableId)
        # tableName = tableDefObj.getName()

        #
        if deleteOpt:
            sqlCommandList = self.__getSqlDeleteList(
                tableId,
                containerNameList=containerNameList,
                deleteOpt=deleteOpt)
        else:
            sqlCommandList = []

        if os.access(tableLoadPath, os.R_OK):
            tableDefObj = self.__sD.getSchemaObject(tableId)

            sqlCommandList.append(
                sqlGen.importTable(databaseName,
                                   tableDefObj,
                                   importPath=tableLoadPath))

            if self.__verbose:
                logger.debug("SQL import command\n%s\n", sqlCommandList)
            #

        if sqlFilePath is not None:
            try:
                with open(sqlFilePath, "w", encoding="utf-8") as ofh:
                    ofh.write("%s" % "\n".join(sqlCommandList))
            except Exception:
                pass
        #
        myQ = MyDbQuery(dbcon=self.__dbCon, verbose=self.__verbose)
        myQ.setWarning(self.__warningAction)
        ret = myQ.sqlCommand(sqlCommandList=sqlCommandList)
        #
        #
        endTime = time.time()
        logger.debug("Table %s server returns %r\n", tableId, ret)
        logger.debug("Completed at %s (%.3f seconds)\n",
                     time.strftime("%Y %m %d %H:%M:%S", time.localtime()),
                     endTime - startTime)
        return ret
示例#3
0
    def __batchInsertImport(self, tableId, rowList=None, containerNameList=None, deleteOpt="selected"):
        """ Load the input table using batch inserts of the input list of dictionaries (i.e. d[attributeId]=value).

            The containerNameList corresponding to the data within loadable data in rowList can be provided
            if 'selected' deletions are to performed prior to the the batch data inserts.

            deleteOpt = ['selected','all'] where 'selected' deletes rows corresponding to the input container
                        list before insert.   The 'all' options truncates the table prior to insert.

                        Deletions are performed in the absence of loadable data.

        """
        startTime = time.time()

        myQ = MyDbQuery(dbcon=self.__dbCon, verbose=self.__verbose)
        myQ.setWarning(self.__warningAction)
        sqlGen = SqlGenAdmin(self.__verbose)
        #
        databaseName = self.__sD.getDatabaseName()
        tableDefObj = self.__sD.getSchemaObject(tableId)
        tableName = tableDefObj.getName()
        tableAttributeIdList = tableDefObj.getAttributeIdList()
        tableAttributeNameList = tableDefObj.getAttributeNameList()
        #
        sqlDeleteList = None
        if deleteOpt in ["selected", "delete"] and containerNameList is not None:
            deleteAttributeName = tableDefObj.getDeleteAttributeName()
            sqlDeleteList = sqlGen.deleteFromListSQL(databaseName, tableName, deleteAttributeName, containerNameList, chunkSize=10)
            if self.__verbose:
                logger.debug("Delete SQL for %s : %r\n", tableId, sqlDeleteList)
        elif deleteOpt in ["all", "truncate"]:
            sqlDeleteList = [sqlGen.truncateTableSQL(databaseName, tableName)]

        sqlInsertList = []
        for row in rowList:
            vList = []
            aList = []
            for tid, nm in zip(tableAttributeIdList, tableAttributeNameList):
                # if len(row[id]) > 0 and row[id] != r'\N':
                if row[tid] is not None and row[tid] != r"\N":
                    vList.append(row[tid])
                    aList.append(nm)
            sqlInsertList.append((sqlGen.insertTemplateSQL(databaseName, tableName, aList), vList))

        ret = myQ.sqlBatchTemplateCommand(sqlInsertList, prependSqlList=sqlDeleteList)
        if ret:
            logger.debug("Batch insert completed for table %s rows %d\n", tableName, len(sqlInsertList))
        else:
            logger.error("Batch insert fails for table %s length %d\n", tableName, len(sqlInsertList))

        endTime = time.time()
        if self.__verbose:
            logger.debug("Completed at %s (%.3f seconds)\n", time.strftime("%Y %m %d %H:%M:%S", time.localtime()), endTime - startTime)

        return ret
示例#4
0
    def _deleteRequest(self, tableId, **kwargs):
        """ Delete from input table records identified by the keyword value pairs provided as input arguments -
        """
        startTime = time.time()
        if self.__debug:
            logger.info("Starting at %s",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()))
        ret = False
        try:
            iOpened = False
            if self.__dbCon is None:
                self._open()
                iOpened = True

            tableDefObj = self.__sD.getSchemaObject(tableId)
            #
            #
            myQ = MyDbQuery(dbcon=self.__dbCon, verbose=self.__verbose)
            myAd = SqlGenAdmin(self.__verbose)
            #
            # Create the attribute and value list for template --
            #
            vList = []
            aList = []
            for atId, kwId in self._getAttributeParameterMap(tableId):
                if kwId in kwargs and kwargs[kwId] is not None:
                    vList.append(kwargs[kwId])
                    aList.append(atId)

            sqlT = myAd.idDeleteTemplateSQL(self.__databaseName,
                                            tableDefObj,
                                            conditionAttributeIdList=aList)
            if self.__debug:
                logger.info("delete sql: %s", sqlT)
                logger.info("delete values: %r", vList)
            ret = myQ.sqlTemplateCommand(sqlTemplate=sqlT, valueList=vList)

            if iOpened:
                self._close()

        except Exception as e:
            status = " delete operation error " + str(e)
            logger.info("status %s", status)
            if self.__verbose:
                logger.exception("Failing with %s", str(e))

        if self.__debug:
            endTime = time.time()
            logger.info("Completedat %s (%.3f seconds)",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()),
                        endTime - startTime)
        return ret
示例#5
0
 def testCreateMultipleConnWithQueryContext(self):
     """Test case -  multiple connection creation"""
     try:
         for ii in range(100):
             with Connection(cfgOb=self.__cfgOb,
                             resourceName="MYSQL_DB") as client:
                 self.assertNotEqual(client, None)
                 for jj in range(100):
                     my = MyDbQuery(dbcon=client)
                     ok = my.testSelectQuery(count=ii + jj)
                     self.assertTrue(ok)
     except Exception as e:
         logger.exception("Failing with %s", str(e))
         self.fail()
示例#6
0
    def delete(self, tableId, containerNameList=None, deleteOpt="all"):
        #
        startTime = time.time()
        sqlCommandList = self.__getSqlDeleteList(tableId, containerNameList=containerNameList, deleteOpt=deleteOpt)

        myQ = MyDbQuery(dbcon=self.__dbCon, verbose=self.__verbose)
        myQ.setWarning(self.__warningAction)
        ret = myQ.sqlCommand(sqlCommandList=sqlCommandList)
        #
        #
        endTime = time.time()

        logger.debug("Delete table %s server returns %r\n", tableId, ret)
        logger.debug("Completed at %s (%.3f seconds)\n", time.strftime("%Y %m %d %H:%M:%S", time.localtime()), endTime - startTime)
        return ret
示例#7
0
 def testCreateMultipleConnectionsWithQuery(self):
     """Test case -  multiple connection creation"""
     try:
         for ii in range(100):
             cObj = self.__open(self.__connectD)
             client = self.__getClientConnection(cObj)
             self.assertNotEqual(client, None)
             for jj in range(100):
                 my = MyDbQuery(dbcon=client)
                 ok = my.testSelectQuery(count=ii + jj)
                 self.assertTrue(ok)
             ok = self.__close(cObj)
             self.assertTrue(ok)
     except Exception as e:
         logger.exception("Failing with %s", str(e))
         self.fail()
示例#8
0
    def _createSchema(self):
        """ Create table schema using the current class schema definition
        """
        if self.__debug:
            startTime = time.time()
            logger.info("Starting at %s",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()))
        ret = False
        try:
            iOpened = False
            if self.__dbCon is None:
                self._open()
                iOpened = True
            #
            tableIdList = self.__sD.getSchemaIdList()
            myQ = MyDbQuery(dbcon=self.__dbCon, verbose=self.__verbose)
            myAd = SqlGenAdmin(self.__verbose)

            for tableId in tableIdList:
                sqlL = []
                tableDefObj = self.__sD.getSchemaObject(tableId)
                sqlL.extend(
                    myAd.createTableSQL(databaseName=self.__databaseName,
                                        tableDefObj=tableDefObj))

                ret = myQ.sqlCommand(sqlCommandList=sqlL)
                if self.__verbose:
                    logger.info("For tableId %s server returns: %s\n", tableId,
                                ret)
                if self.__debug:
                    logger.info("SQL: %s\n", "\n".join(sqlL))
            if iOpened:
                self._close()
        except Exception as e:
            status = " table create error " + str(e)
            logger.info("status %s\n", status)
            if self.__verbose:
                logger.exception("Failing with %s", str(e))

        if self.__debug:
            endTime = time.time()
            logger.info("Completed at %s (%.3f seconds)\n",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()),
                        endTime - startTime)
        return ret
示例#9
0
    def _select(self, tableId, **kwargs):
        """Construct a selection query for input table and optional constraints provided as keyword value pairs in the
        input arguments.  Return a list of dictionaries of these query details including all table attributes.
        """
        startTime = time.time()
        if self.__debug:
            logger.info("Starting at %s",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()))
        rdList = []
        try:
            iOpened = False
            if self.__dbCon is None:
                self._open()
                iOpened = True
            #
            tableDefObj = self.__sD.getSchemaObject(tableId)
            myQ = MyDbQuery(dbcon=self.__dbCon, verbose=self.__verbose)
            sqlGen = SqlGenQuery(schemaDefObj=self.__sD,
                                 verbose=self.__verbose)
            sqlGen.setDatabase(databaseName=self.__databaseName)
            sqlConstraint = SqlGenCondition(schemaDefObj=self.__sD,
                                            verbose=self.__verbose)
            #
            atMapL = self._getAttributeParameterMap(tableId=tableId)
            for kwArg, _ in kwargs.items():
                for atId, kwId in atMapL:
                    if kwId == kwArg:
                        if tableDefObj.isAttributeStringType(atId):
                            cTup = ((tableId, atId), "EQ", (kwargs[kwId],
                                                            "CHAR"))
                        else:
                            cTup = ((tableId, atId), "EQ", (kwargs[kwId],
                                                            "OTHER"))
                        sqlConstraint.addValueCondition(
                            cTup[0], cTup[1], cTup[2])
                        break
            #
            # Add optional constraints OR ordering by primary key attributes
            if sqlConstraint.get():
                sqlGen.setCondition(sqlConstraint)
            else:
                for atId in tableDefObj.getPrimaryKeyAttributeIdList():
                    sqlGen.addOrderByAttributeId(attributeTuple=(tableId,
                                                                 atId))

            atIdList = self.__sD.getAttributeIdList(tableId)
            for atId in atIdList:
                sqlGen.addSelectAttributeId(attributeTuple=(tableId, atId))
            #
            sqlS = sqlGen.getSql()
            if self.__debug:
                logger.info("selection sql: %s", sqlS)

            rowList = myQ.selectRows(queryString=sqlS)
            sqlGen.clear()
            #
            # return the result set as a list of dictionaries
            #
            for iRow, row in enumerate(rowList):
                rD = {}
                for colVal, atId in zip(row, atIdList):
                    rD[atId] = colVal
                if self.__debug:
                    logger.info("result set row %d dictionary %r", iRow,
                                rD.items())
                rdList.append(rD)
            if iOpened:
                self._close()
        except Exception as e:
            status = " operation error " + str(e)
            logger.info("status %s", status)
            if self.__verbose:
                logger.exception("Failing with %s", str(e))

        if self.__debug:
            endTime = time.time()
            logger.info("Completed at %s (%.3f seconds)",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()),
                        endTime - startTime)
        return rdList
示例#10
0
    def _updateRequest(self, tableId, contextId, **kwargs):
        """Update the input table using the keyword value pairs provided as input arguments -

        The contextId controls the handling default values for unspecified parameters.

        """
        startTime = time.time()
        if self.__debug:
            logger.info("Starting at %s",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()))
        ret = False
        try:
            iOpened = False
            if self.__dbCon is None:
                self._open()
                iOpened = True
            #
            tableDefObj = self.__sD.getSchemaObject(tableId)
            #
            myQ = MyDbQuery(dbcon=self.__dbCon, verbose=self.__verbose)
            myAd = SqlGenAdmin(self.__verbose)
            defaultValD = self._getParameterDefaultValues(contextId=contextId)
            cIdList = self._getConstraintParameterMap(tableId)

            #
            # create the value list for template --
            #
            vList = []
            aList = []
            cList = []
            for atId, kwId in self._getAttributeParameterMap(tableId):
                if (atId, kwId) in cIdList:
                    continue
                if kwId in kwargs and kwargs[kwId] is not None:
                    vList.append(kwargs[kwId])
                    aList.append(atId)
                else:
                    if kwId in defaultValD and defaultValD[kwId] is not None:
                        vList.append(defaultValD[kwId])
                        aList.append(atId)

            for atId, kwId in cIdList:
                if kwId in kwargs and kwargs[kwId] is not None:
                    vList.append(kwargs[kwId])
                    cList.append(atId)

            sqlT = myAd.idUpdateTemplateSQL(self.__databaseName,
                                            tableDefObj,
                                            updateAttributeIdList=aList,
                                            conditionAttributeIdList=cList)
            if self.__debug:
                logger.info("update sql: %s", sqlT)
                logger.info("update values: %r", vList)
            ret = myQ.sqlTemplateCommand(sqlTemplate=sqlT, valueList=vList)
            if iOpened:
                self._close()

        except Exception as e:
            status = " update operation error " + str(e)
            logger.info("status %s", status)
            if self.__verbose:
                logger.exception("Failing with %s", str(e))
        if self.__debug:
            endTime = time.time()
            logger.info("Completed at %s (%.3f seconds)",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()),
                        endTime - startTime)
        return ret
示例#11
0
    def _insertRequest(self, tableId, contextId, **kwargs):
        """Insert into the input table using the keyword value pairs provided as input arguments -

        The contextId controls the handling default values for unspecified parameters.
        """
        startTime = time.time()
        if self.__debug:
            logger.info("Starting at %s\n",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()))
        ret = False
        try:
            iOpened = False
            if self.__dbCon is None:
                self._open()
                iOpened = True
            #
            tableDefObj = self.__sD.getSchemaObject(tableId)
            #
            myQ = MyDbQuery(dbcon=self.__dbCon, verbose=self.__verbose)
            myAd = SqlGenAdmin(self.__verbose)
            defaultValD = self._getParameterDefaultValues(contextId=contextId)
            #
            # Create the attribute and value list for template --
            #
            vList = []
            aList = []
            for atId, kwId in self._getAttributeParameterMap(tableId=tableId):
                if kwId in kwargs and kwargs[kwId] is not None:
                    vList.append(kwargs[kwId])
                    aList.append(atId)
                else:
                    # use the default values if these exist
                    if kwId in defaultValD and defaultValD[kwId] is not None:
                        vList.append(defaultValD[kwId])
                        aList.append(atId)
                    else:
                        # appropriate null handling -- all fields must be assigned on insert --
                        vList.append(tableDefObj.getAppNullValue(atId))
                        aList.append(atId)

            sqlT = myAd.idInsertTemplateSQL(self.__databaseName,
                                            tableDefObj,
                                            insertAttributeIdList=aList)
            if self.__debug:
                logger.info("aList %d vList %d\n", len(aList), len(vList))
                logger.info("insert template sql=\n%s\n", sqlT)
                logger.info("insert values vList=\n%r\n", vList)
                # sqlC = sqlT % vList
                # logger.info("insert sql command =\n%s\n",  sqlC)
            ret = myQ.sqlTemplateCommand(sqlTemplate=sqlT, valueList=vList)
            if iOpened:
                self._close()

        except Exception as e:
            status = " insert operation error " + str(e)
            logger.info("status %s\n", status)
            if self.__verbose:
                logger.exception("Failing with %s", str(e))
        if self.__debug:
            endTime = time.time()
            logger.info("Completed %s (%.3f seconds)\n",
                        time.strftime("%Y %m %d %H:%M:%S", time.localtime()),
                        endTime - startTime)

        return ret