コード例 #1
0
    def _insert_into_db(self, data):
        em = EntityManager()
        db = em.get_db()
        # create placeholders for the data
        columns, values = self._get_sql_data(data)

        assert len(columns) == len(values)

        column_string = ""
        value_string = ""

        for c, v in zip(columns, values):
            value_string += v + ", "
            column_string += c + ", "

        value_string = value_string[:-2]  #remove trailing comma
        column_string = column_string[:-2]  #remove trailing comma

        sql = "INSERT INTO `{}`({}) VALUES({});".format(
            self.table_name, column_string, value_string)
        logging.debug("Using db: %s", db.database)
        cursor = db.cursor()
        logging.debug("EXECUTING SQL: %s", sql)
        logging.debug("DATA FROM MODEL: %s", data)
        cursor.execute(sql, data)
        db.commit()
        if cursor.rowcount > 0:
            # set the id, now the class exists!
            self._key = cursor.lastrowid
            return True
        else:
            raise Exception("Unable to insert in db")
コード例 #2
0
 def db(self):
     """
   Turns out singletons can't get accessed on init of a class
   So simple hack, creating a property that accesses the singleton
   and getting the wanted property
   """
     em = EntityManager()
     db = em.get_db()
     return db
コード例 #3
0
ファイル: create_db.py プロジェクト: EricB2A/BDR_RBNB
    def run(self, *args):
        em = EntityManager()
        db_name = em.db_name
        if em.is_connected:
            em.create_database()
            print("New database {} created succesfully".format(db_name))

        else:
            print(
                "Couldn't connect to database, are you sure of your credentials?"
            )
コード例 #4
0
ファイル: delete_db.py プロジェクト: EricB2A/BDR_RBNB
    def run(self, *args):
        em = EntityManager()
        db_name = em.db_name
        if em.is_connected:
            try:
                em.destroy_db()  #might fail because db doesn't exist
            except Exception:
                pass
            print("Database {} dropped succesfully".format(db_name))

        else:
            print(
                "Couldn't connect to database, are you sure of your credentials?"
            )
コード例 #5
0
    def help(self):

        entities_available = ""
        em = EntityManager()
        for name in em.get_all_entities():
            entities_available += "\t - " + name + "\n"

        command_executable = "{} {}".format(sys.executable, sys.argv[0])
        usage = "{} update [entity name] [id][".format(command_executable)
        print("""
Update an existing entity (location, user, etc...)
You will be prompted to complete the necessary fields, once you selected an entity
Usage: {}
Available entities: 
{}

Exmaple usage: 
      """.format(usage, entities_available))
コード例 #6
0
ファイル: one_to_many.py プロジェクト: EricB2A/BDR_RBNB
 def find(self, entity):
     sql = "SELECT * FROM {} WHERE {} in ({})".format(
         self.foreign_table, self.foreign_key, entity.key)
     logging.debug("QUERY: %s", sql)
     em = EntityManager()
     db = em.db
     cursor = db.cursor(dictionary=True)
     cursor.execute(sql)
     return [
         self.foreign_entity.build(**data) for data in cursor.fetchall()
     ]
コード例 #7
0
    def _get_sql_data(self, data):
        """
      returns tuple with (columns, values)
      """
        em = EntityManager()
        db = em.get_db()
        config = Config()
        charset = config.db.charset if "charset" in config.db.keys(
        ) else "utf8"
        converter = MySQLConverter(charset)

        def none_to_null(val):
            if val is None:
                return "NULL"
            return val

        def quote(val):
            if isinstance(val, NUMERIC_TYPES):
                return str(val)
            return "'" + val + "'"

        def quote_col(val):
            return "`" + val + "`"

        _escape_value = compose(none_to_null, quote, converter.escape)
        _escape_column = compose(
            none_to_null, quote_col,
            converter.escape)  #column quting is different than normal quotes

        if self.key_name not in data.keys(
        ) and self.key is not None:  #add the key to the data
            data[self.key_name] = self.key

        columns = list()
        values = list()

        for k, v in data.items():
            values.append(_escape_value(v))
            columns.append(_escape_column(k))

        return (columns, values)
コード例 #8
0
ファイル: relationship.py プロジェクト: EricB2A/BDR_RBNB
 def __init__(self,
              local_entity_name,
              foreign_entity_name,
              foreign_key=None,
              local_key=None):
     self.local_entity_name = local_entity_name
     self.foreign_entity_name = foreign_entity_name
     self.foreign_key = foreign_key if foreign_key else foreign_entity_name + "_id"
     self.local_key = local_key if local_key is not None else foreign_entity_name + "_id"
     self.manager = EntityManager()
     self.db = self.manager.db
     self._data = None
コード例 #9
0
ファイル: find.py プロジェクト: EricB2A/BDR_RBNB
   def run(self, *args):
      em = EntityManager()

      if len(args) < 1:
         return self.help()
      entity_name = args[0]
      entity = em.get_entity(entity_name)
      if not entity:
         print("Couldn't find the class you are looking for")
         return self.help()
      
      ids = args[1:]
      res = None
      if len(ids) > 0:
         res = entity.find(ids)
      else:
         res = entity.find()

      data = []
      self.headers = list(entity.fields.keys())
      self.headers.insert(0, "id")
      logging.debug("GOT MODELS: %s",res)
      if isinstance(res, Entity):
         data = [e.key] + [ self._get_data_from_entity(res) ]
      else:
         for e in res:
            data.append([e.key] + self._get_data_from_entity(e))
         
      
      if len(data) <= 0:
         data = [ [ "" for i in range(len(self.headers)) ]] 

      logging.debug(data)
      logging.debug(self.headers)
      string = tt.to_string(
         data,
         header=self.headers,
         style=tt.styles.ascii_thin_double,
      )
      print(string)
コード例 #10
0
    def destroy(self):
        if not self.local_entity.exists:
            self._data = []
            return True

        sql = "DELETE FROM {} WHERE {} in ({})".format(self.foreign_table,
                                                       self.foreign_key,
                                                       self.local_entity.key)
        em = EntityManager()
        db = em.db
        cursor = db.cursor()
        res = cursor.execute(sql)
        db.commit()
コード例 #11
0
 def find(self, entity):
     if getattr(entity, self.local_key) is None:
         return None
     sql = "SELECT * FROM {} WHERE {} = {} LIMIT 0,1".format(
         self.foreign_table, self.foreign_key,
         getattr(entity, self.local_key))
     logging.debug("QUERY: %s", sql)
     em = EntityManager()
     db = em.db
     cursor = db.cursor(dictionary=True)
     cursor.execute(sql)
     res = cursor.fetchone()
     if res is None:
         return None
     return self.foreign_entity.build(**res)
コード例 #12
0
ファイル: reset_db.py プロジェクト: EricB2A/BDR_RBNB
    def run(self, *args):
        em = EntityManager()
        db_name = em.db_name
        if em.is_connected:
            cmd = DeleteDb()
            cmd.run(*args)

            cmd = CreateDb()
            cmd.run(*args)

            self.import_schema()
            print("Database {} reseted succesfully".format(db_name))

        else:
            print(
                "Couldn't connect to database, are you sure of your credentials?"
            )
コード例 #13
0
ファイル: reset_db.py プロジェクト: EricB2A/BDR_RBNB
    def import_schema(self):
        em = EntityManager()
        with open(self.schema_file, "r") as f:
            db = em.db
            sql = f.read()
            cursor = db.cursor()
            try:
                mcurs = cursor.execute(sql, multi=True)
                for result in mcurs:
                    if result.with_rows:
                        logging.debug("Rows added by {}".format(
                            result.statement))
                        logging.debug(reuslt.fetchall())
                    else:
                        logging.debug("Rows affected {} by {}".format(
                            result.rowcount, result.statement))

                db.commit()
                mcrus.close()
            except StopIteration as e:  #multi cursor execute generates an error in python>=3.7...
                pass
コード例 #14
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.entity_manager = EntityManager()
コード例 #15
0
class Update(Command):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.entity_manager = EntityManager()

    def help(self):

        entities_available = ""
        em = EntityManager()
        for name in em.get_all_entities():
            entities_available += "\t - " + name + "\n"

        command_executable = "{} {}".format(sys.executable, sys.argv[0])
        usage = "{} update [entity name] [id][".format(command_executable)
        print("""
Update an existing entity (location, user, etc...)
You will be prompted to complete the necessary fields, once you selected an entity
Usage: {}
Available entities: 
{}

Exmaple usage: 
      """.format(usage, entities_available))

    def run(self, *args):
        if len(args) < 1:
            return self.help()
        entity_name = args[0]
        entity = self.entity_manager.get_entity(entity_name)
        logging.debug("EM: %s", self.entity_manager)
        logging.debug("Available entities: %s",
                      self.entity_manager.get_all_entities())

        if not entity:
            print("Couldn't find the class you are looking for")
            return self.help()

        if len(args) != 2:
            print("You must only provide a single id to update")
            return

        entity = entity.find(args[1])
        if entity is None:
            print("Couldn't find {} {}".format(args[0], args[2]))

        logging.debug("UPDATING ENTITY: %s", entity)
        print("Updating {}:\n\n".format(entity_name))

        self.ask_for_fields(entity)

        for name, relationship in entity.relationships.items():
            if isinstance(relationship, ManyToMany):
                pass
                # Do something for many to many
            elif isinstance(relationship, OneToMany):
                #get all remote entities
                available_data = list(relationship.find_all())
                available_data = list(
                    map(lambda x: (x.render_excerpt(), x), available_data))
                logging.debug(available_data)
                questions = [
                    inquirer.Checkbox(
                        "relation",
                        message="Which {}?".format(name),
                        choices=available_data,
                    )
                ]
                res = inquirer.prompt(questions)
                logging.debug(res)
                setattr(entity, name, res["relation"])
            elif isinstance(relationship, OneToOne):
                #get all remote entities
                available_data = list(relationship.find_all())
                available_data = list(
                    map(lambda x: (x.render_excerpt(), x), available_data))
                logging.debug(available_data)
                questions = [
                    inquirer.List(
                        "relation",
                        message="Which {}?".format(name),
                        choices=available_data,
                    )
                ]
                res = inquirer.prompt(questions)
                logging.debug(res)
                setattr(entity, name, res["relation"])

        #TODO add resume plus confirm
        entity.save()
        print("{} {} updated succesfully".format(entity_name, entity.id))

    def ask_for_fields(self, entity):
        fields = entity.fields
        #filter out all relationship fields to not ask for them
        fields = {k: v for (k, v) in fields.items() if v is not "relationship"}
        questions = map(lambda f: inquirer.Text(f, message="{}".format(f)),
                        fields)
        answers = inquirer.prompt(questions)
        logging.debug("Creating entity (%s) with values %s", entity, answers)
        for field, value in answers.items():
            setattr(entity, field, value)
コード例 #16
0
class Destroy(Command):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.entity_manager = EntityManager()

    def help(self):

        entities_available = ""
        em = EntityManager()
        for name in em.get_all_entities():
            entities_available += "\t - " + name + "\n"

        command_executable = "{} {}".format(sys.executable, sys.argv[0])
        usage = "{} update [entity name] [id][".format(command_executable)
        print("""
Update an existing entity (location, user, etc...)
You will be prompted to complete the necessary fields, once you selected an entity
Usage: {}
Available entities: 
{}

Exmaple usage: 
      """.format(usage, entities_available))

    def run(self, *args):
        if len(args) < 1:
            return self.help()
        entity_name = args[0]
        entity = self.entity_manager.get_entity(entity_name)
        logging.debug("EM: %s", self.entity_manager)
        logging.debug("Available entities: %s",
                      self.entity_manager.get_all_entities())

        if not entity:
            print("Couldn't find the class you are looking for")
            return self.help()

        if len(args) != 2:
            print("You must only provide a single id to destroy")
            return

        entity = entity.find(args[1])
        if entity is None:
            print("Couldn't find {} {}".format(args[0], args[2]))
            return
        id = entity.key
        questions = [
            inquirer.Confirm(
                "confirmed",
                message="Are you sure you want to delete {} {}".format(
                    entity_name, id),
                default=False)
        ]
        res = inquirer.prompt(questions)
        if not res["confirmed"]:
            logging.debug("ABORTED")
            return

        logging.debug("DELETING ENTITY: %s", entity)
        print("Deleting {}:\n\n".format(entity_name))

        entity.delete()
        print("{} {} deleted succesfully".format(entity_name, id))
コード例 #17
0
 def parent_entity(self):
     em = EntityManager()
     parent = em.get_entity(self.parent_entity)
     return parent