def rollback(): database = QSqlDatabase.database() database.transaction() try: yield database finally: database.rollback()
def db_connection(): db = QSqlDatabase.database(Setup.DB_CONNECTION) if not db.isValid(): raise RuntimeError(f"DB connection '{Setup.DB_CONNECTION}' is invalid") if not db.isOpen(): logging.fatal(f"DB connection '{Setup.DB_CONNECTION}' is not open") return db
def createTable(): if table_name in QSqlDatabase.database().tables(): return query = QSqlQuery() if not query.exec_(""" CREATE TABLE IF NOT EXISTS 'Conversations' ( 'author' TEXT NOT NULL, 'recipient' TEXT NOT NULL, 'timestamp' TEXT NOT NULL, 'message' TEXT NOT NULL, FOREIGN KEY('author') REFERENCES Contacts ( name ), FOREIGN KEY('recipient') REFERENCES Contacts ( name ) ) """): logging.error("Failed to query database") # This adds the first message from the Bot # and further development is required to make it interactive. query.exec_(""" INSERT INTO Conversations VALUES( 'machine', 'Me', '2019-01-07T14:36:06', 'Hello!' ) """) logging.info(query)
def get_db(): name = "db-{0}".format(str(QThread.currentThread())) if QSqlDatabase.contains(name): return QSqlDatabase.database(name) else: db = QSqlDatabase.addDatabase("QSQLITE", name) db.setDatabaseName("video.db") return db
def get_password() -> str: """Return the password from the database.""" query = QSqlQuery(QSqlDatabase.database()) query.exec_("select password from credentials") if query.next(): password = query.value(0) query.finish() return password
def __init__(self): self.db = QSqlDatabase.database(Setup.DB_CONNECTION) if not self.db.isValid(): self.db = None logging.fatal("DB connection is invalid") return if not self.db.isOpen(): self.db = None logging.fatal("DB connection is not open") return
def init(self) -> bool: """Create the Connection to the Database. For the Moment just SQLite Returns: Return true is the database successfull initialized. """ self.database = QSqlDatabase.database() if self.dbType == "sqlite": if not self.database.isValid(): self.database = QSqlDatabase.addDatabase("QSQLITE") if not self.database.isValid(): self.log.error("Cannot add database") return False self.database_name = self.__get_sqlite_name() file = QFile(self.database_name) if file.exists(): # When using the SQLite driver, open() will create the SQLite # database if it doesn't exist. self.log.info("Try open the existing db : {}".format( self.database_name)) self.database.setDatabaseName(self.database_name) else: self.database.setDatabaseName(self.database_name) self.log.info("Try create db : {}".format(self.database_name)) self.prepare_db() if not self.database.open(): self.log.error("Cannot open database") QFile.remove(self.database_name) return False elif self.dbType == "psql": self.database = QSqlDatabase.addDatabase("QPSQL") elif self.dbType == "odbc": self.database = QSqlDatabase.addDatabase("QODBC") self.database.setHostName(self.database_hostname) self.database.setPort(self.database_port) self.database.setUserName(self.database_user_name) self.database.setPassword(self.database_password) if not self.database.isValid(): self.log.error("Cannot add database") return False if not self.database.open(): self.log.error("Cannot open database") return False return True
def connectToDatabase(): database = QSqlDatabase.database() if not database.isValid(): database = QSqlDatabase.addDatabase("QSQLITE") if not database.isValid(): logger.error("Cannot add database") writeDir = QDir() # writeDir = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) if not writeDir.mkpath("."): logger.error("Failed to create writable directory") # Ensure that we have a writable location on all devices fileName = writeDir.absolutePath() + "/chat-database.sqlite3" database.setDatabaseName(fileName) # open() will create the SQLite database if it doesn't exist if not database.open(): logger.error("Cannot open database") QFile.remove(fileName)
def connectToDatabase(logger): database = QSqlDatabase.database() if not database.isValid(): database = QSqlDatabase.addDatabase('QSQLITE') if not database.isValid(): logger.error('Cannot add database') write_dir = QDir() if not write_dir.mkpath('.'): logger.error('Failed to create writable directory') # Ensure that we have a writable location on all devices. filename = '{}/chat-database.sqlite3'.format(write_dir.absolutePath()) # When using the SQLite driver, open() will create the SQLite database if it doesn't exist. database.setDatabaseName(filename) if not database.open(): logger.error('Cannot open database') QFile.remove(filename)
def create_password() -> str: """Prompt for a password to be created and return it.""" dialogue = CreatePassword() dialogue.exec_() if dialogue.result() != QDialog.Accepted: sys.exit() password = dialogue.new_password # upsert query = QSqlQuery(QSqlDatabase.database()) query.prepare(""" insert into credentials (id, password) values (0, :password) on conflict (id) do update set password=:password """) query.bindValue(":password", password) query.exec_() query.finish() return password
def __init__(self): super(VentanaPrincipal, self).__init__() self.ui = Ui_TabWidget() self.ui.setupUi(self) # DB self.db = QSqlDatabase.addDatabase("QSQLITE") self.db.setDatabaseName("cuentas.db") self.conector = QSqlDatabase.database() self.general_query = QSqlQuery() self.organizar_db() # Querys para psw_tool self.master_query = QSqlQuery() self.save_query = QSqlQuery() self.passwords_query_retrieve = QSqlQuery() self.passwords_query_write = QSqlQuery() self.popular = QSqlQuery() self.comboBoxes_query_categoria = QSqlQuery() self.comboBoxes_query_mail = QSqlQuery() self.comboBoxes_query_usuario = QSqlQuery() self.verificar_columna_contrasenas = QSqlQuery() self.filtro = QSqlQuery() # Querys para pswItemDelegate self.all_data = QSqlQuery() # BASE DE DATOS en UI self.model = QSqlTableModel() # pswItemDelegate.CustomSqlModel() self.organizar_tabla_ui() self.model.setEditStrategy(QSqlTableModel.OnManualSubmit) # Va aca abajo por self.model.setTable('passwords') # Para cuando se cambian datos self.model.dataChanged.connect(self.celdas_cambiadas) self.ui.tabla_db.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.tabla_db.customContextMenuRequested.connect(self.context_menu) # Filtro DB # .connect(lambda: self. self.tabBarClicked.connect(self.actualizar_tabs) # Iconos DB en UI self.icon_seguridad = QIcon() self.icon_seguridad.addPixmap(QPixmap(":/media/iconografia/locked.png"), QIcon.Normal, QIcon.Off) self.icon_desbloqueado = QIcon() self.icon_desbloqueado.addPixmap(QPixmap(":/media/iconografia/unlocked.png"), QIcon.Normal, QIcon.Off) self.icon_editar = QIcon() self.icon_editar.addPixmap(QPixmap(":/media/iconografia/pencil.png"), QIcon.Normal, QIcon.Off) self.icon_guardar = QIcon() self.icon_guardar.addPixmap(QPixmap(":/media/iconografia/broken-pencil.png"), QIcon.Normal, QIcon.Off) # Procesos iniciales self.cargar_config() self.master_key = None self.seguridad_alterada = False self.candado = "cerrado" self.modo_boton_editar_guardar = "editar" self.contrasenas_nuevas = {} self.edits = {} self.revisar_columna_contrasenas() self.cargar_opciones_combo_boxes() # Alertas # Iconos para las alertas sin UI self.icon_ventana = QIcon() self.icon_ventana.addPixmap(QPixmap(":/media/imagenes/main_frame.png"), QIcon.Normal, QIcon.Off) self.alerta_config = QMessageBox(QMessageBox.Warning, "Problema con la configuración actual", "Existen dos posibilidades para este error:\n\n1. El archivo de configuración está dañando\n2. Usted tiene todas las opciones desmarcadas (el amor no cuenta)\n\nPara solucionarlo, borre el archivo de configuración ('opciones.ini'),\no marque alguna opción en la pestaña de configuración y guarde su selección\n" ) self.alerta_master_psw_mala = QMessageBox(QMessageBox.Warning, "Problema con la contraseña ingresada", "Por favor tome precauciones con la elección de la contraseña maestra.\nPara poder proseguir debe ingresar una contraseña con más de 5 y menos de 17 caracteres, o sino presione cancelar." ) self.alerta_master_psw_incorrecta = QMessageBox(QMessageBox.Warning, "Problema con la contraseña ingresada", "La contraseña que ingresaste es incorrecta" ) self.alerta_guardado_exitoso = QMessageBox(QMessageBox.Information, "Información guardada", "Toda la información que ingresaste se guardó con éxito." ) self.alerta_config.setWindowIcon(self.icon_ventana) self.alerta_master_psw_mala.setWindowIcon(self.icon_ventana) self.alerta_master_psw_incorrecta.setWindowIcon(self.icon_ventana) self.alerta_guardado_exitoso.setWindowIcon(self.icon_ventana) # Alertas con su propia UI # Dialog info self.dialogo_info = QDialog() self.info_app = Ui_dialogo_info() self.info_app.setupUi(self.dialogo_info) # Alerta master psw self.dialogo_master_psw = QDialog() self.alerta_master_psw = Ui_dialogo_master_psw() self.alerta_master_psw.setupUi(self.dialogo_master_psw) # Botones self.ui.boton_guardar_config.clicked.connect(self.guardar_config) self.ui.boton_info.clicked.connect(self.cargar_info) self.ui.boton_generar.clicked.connect(self.llamar_generar_contrasena) # Boton generar contrasñea self.ui.boton_guardar.clicked.connect(self.guardar_contrasena) # boton guardar data # Si presionan el boton revelar contraseña self.ui.reveal_psw.clicked.connect(self.mostrar_contrasena) self.alerta_master_psw.reveal_master_psw.clicked.connect(self.mostrar_contrasena_maestra) # Icono del boton revelar contraseña self.icon_not_view = QIcon() self.icon_not_view.addPixmap(QPixmap(":/media/iconografia/not_view.png"), QIcon.Normal, QIcon.Off) self.icon_view = QIcon() self.icon_view.addPixmap(QPixmap(":/media/iconografia/view.png"), QIcon.Normal, QIcon.Off) # Click en botones copiar # Otra manera de hacerlo: partial(self.llamar_copiar(n)) using functools.partial self.ui.cp1.clicked.connect(lambda: self.llamar_copiar(1)) self.ui.cp2.clicked.connect(lambda: self.llamar_copiar(2)) self.ui.cp3.clicked.connect(lambda: self.llamar_copiar(3)) # Botones DB self.ui.boton_filtro.clicked.connect(lambda: self.filtrar()) self.ui.boton_editar.clicked.connect(lambda: self.gestor_boton_editar_guardar()) self.ui.boton_seguridad.clicked.connect(lambda: self.mostrar_contrasenas()) # Botones Info self.info_app.boton_steam.clicked.connect(lambda: backend.abrir_link("https://steamcommunity.com/id/JosephKm")) self.info_app.boton_discord.clicked.connect(lambda: backend.abrir_link("https://discord.gg/wYuXPQS")) self.info_app.boton_github.clicked.connect( lambda: backend.abrir_link("https://github.com/kuttz-dev/Password-manager")) # Si se presiona la pestaña de configuracion # self.ui.tab_3.connect(self.cargar_config) # SETEAR COMBOBOXES self.ui.comboBox_usuario.setInsertPolicy(QComboBox.InsertAlphabetically) self.ui.comboBox_mail.setInsertPolicy(QComboBox.InsertAlphabetically) self.ui.comboBox_categoria.setInsertPolicy(QComboBox.InsertAlphabetically) self.ui.comboBox_usuario.setDuplicatesEnabled(False) self.ui.comboBox_mail.setDuplicatesEnabled(False) self.ui.comboBox_categoria.setDuplicatesEnabled(False) self.ui.comboBox_usuario.clearEditText() self.ui.comboBox_mail.clearEditText() self.ui.comboBox_categoria.clearEditText()
def db(self): db = QSqlDatabase.database(self.db_path) return db
def prepare_db(self) -> bool: """Create the Database from the DDL. The DDL is a script that provided as QResource Returns: True if creation succesful. """ if not self.database.isValid(): self.log.warning("The Database is not valid, reopen") self.database = QSqlDatabase.database(self.database_name) self.database.open() query = QSqlQuery(self.database) file = QFile(":/data/script.sql") if not file.exists(): self.log.error("Kritischer Fehler beim erzeugen der Datenbank" " {} nicht gefunden".format(file.fileName())) return False if not file.open(QIODevice.ReadOnly): self.log.error( "Kritischer Fehler bei der Initialisierung der Datenbank." "Die Datei {} konnte nicht geöffnet werden".format( file.fileName())) ts = QTextStream(file) line: str = "" cleaned_line: str = "" string_list: list = [] read_line: list = [] self.log.info("File at end: {}".format(ts.atEnd())) while not ts.atEnd(): has_text: bool = False line = "" string_list.clear() while not has_text: read_line = ts.read_line() self.log.info("read Line: {}".format(read_line)) cleaned_line = read_line.strip() string_list = cleaned_line.split("--") cleaned_line = string_list[0] if not cleaned_line.startswith( "--") and not cleaned_line.startswith("DROP"): line += cleaned_line if cleaned_line.endswith(";"): break if cleaned_line.startswith("COMMIT"): has_text = True if not line == "": self.log.info("Line: {}".format(line)) if not query.exec_(line): self.log.error( "Fehler beim Erzeugen der Tabelle {}".format(line)) self.log.error("Datenbank meldet Fehler {}".format( query.lastError())) return False else: self.log.error( "Fehler beim Lesen der Datei zur Datenbank Erzeugung: ") return False file.close() self.log.info("Datenbank erfolgreich erzeugt") return True