Skip to content

Commit

Permalink
Examples added
Browse files Browse the repository at this point in the history
  • Loading branch information
iagolirapasssos committed Apr 25, 2023
1 parent 456d198 commit fbe2ffe
Show file tree
Hide file tree
Showing 11 changed files with 217 additions and 0 deletions.
24 changes: 24 additions & 0 deletions examples/backup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from simple_database.simple_database import SimpleDatabase

# Cria uma nova instância do banco de dados
db = SimpleDatabase("example.db")

# Adiciona alguns dados
db.set("key1", "value1")
db.set("key2", "value2")
db.set("key3", "value3")

# Cria um backup do banco de dados
db.create_backup("example_backup.db")

# Modifica alguns dados
db.set("key1", "new_value1")
db.set("key2", "new_value2")

# Restaura o backup
db.restore_backup("example_backup.db")

# Verifica se os dados foram restaurados corretamente
print(db.get("key1")) # Saída: "value1"
print(db.get("key2")) # Saída: "value2"
print(db.get("key3")) # Saída: "value3"
27 changes: 27 additions & 0 deletions examples/master_slave.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from simple_database import SimpleDatabase, Master, Slave

# Cria um banco de dados
db = SimpleDatabase()

# Adiciona um dado no banco de dados
db.set("nome", "João")

# Cria um servidor Master na porta 8000
master = Master(db, "localhost", 8000)

# Cria dois servidores Slave que se conectam ao Master na porta 8000
slave1 = Slave(db, "localhost", 8000)
slave2 = Slave(db, "localhost", 8000)

# Imprime o dado do banco de dados em cada servidor
print("Master:", master.get_data("nome"))
print("Slave 1:", slave1.get_data("nome"))
print("Slave 2:", slave2.get_data("nome"))

# Modifica o dado no banco de dados
db.set("nome", "Maria")

# Imprime o dado do banco de dados em cada servidor novamente
print("Master:", master.get_data("nome"))
print("Slave 1:", slave1.get_data("nome"))
print("Slave 2:", slave2.get_data("nome"))
24 changes: 24 additions & 0 deletions examples/mix_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from simple_database.async_simple_database import AsyncSimpleDatabase
from simple_database.simple_database import SimpleDatabase


async def run_async():
# criando instância assíncrona do banco de dados
async_db = AsyncSimpleDatabase()

# escrevendo valores assincronamente
await async_db.set("key1", "value1")
await async_db.set("key2", "value2")

# lendo valores síncronamente
db = SimpleDatabase()
print(db.get("key1"))
print(db.get("key2"))

# lendo valores assincronamente
print(await async_db.get("key1"))
print(await async_db.get("key2"))


# executando a função assíncrona
asyncio.run(run_async())
9 changes: 9 additions & 0 deletions examples/performance_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from performance import measure_time

@measure_time
def slow_function():
# Simula um processo lento
for i in range(1000000):
pass

slow_function() # Saída: Elapsed time: 0.0675s
23 changes: 23 additions & 0 deletions examples/replication_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from simple_database.simple_database import SimpleDatabase
from simple_database.replication import Master, Slave

# Cria uma nova instância do banco de dados
db = SimpleDatabase("example.db")

# Cria uma instância do mestre e adiciona alguns dados
master = Master(db, "localhost", 5000)
master.set_data("key1", "value1")
master.set_data("key2", "value2")

# Cria uma instância do escravo e sincroniza os dados
slave = Slave(db, "localhost", 5000)
print(slave.get_data("key1")) # Saída: "value1"
print(slave.get_data("key2")) # Saída: "value2"

# Modifica alguns dados no mestre
master.set_data("key1", "new_value1")
master.set_data("key2", "new_value2")

# Verifica se os dados foram sincronizados corretamente no escravo
print(slave.get_data("key1")) # Saída: "new_value1"
print(slave.get_data("key2")) # Saída: "new_value2"
15 changes: 15 additions & 0 deletions examples/security2_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from simple_database import SimpleDatabase, Security

db = SimpleDatabase("my_db", "/path/to/db")

# Criando um usuário com senha
Security.add_user("admin", "password123")

# Verificando se a senha é válida
if Security.authenticate_user("admin", "password123"):
# Acesso permitido
data = {"name": "John", "age": 30}
db.set("user_data", data)
else:
# Acesso negado
print("Senha incorreta.")
5 changes: 5 additions & 0 deletions examples/security_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from security import hash_string

password = "my_password"
hashed_password = hash_string(password)
print(hashed_password) # Saída: 41d067c4a14adac4fa4ff38bc6f53d6d0a6e41b6daa7456c04b57d7bbd9f8aaf
19 changes: 19 additions & 0 deletions examples/simple_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from simple_database import SimpleDatabase

db = SimpleDatabase("my_db")

# Adiciona um registro
db.put("my_key", {"foo": "bar"})

# Recupera um registro
record = db.get("my_key")
print(record) # Saída: {"foo": "bar"}

# Remove um registro
db.delete("my_key")

# Backup do banco de dados
db.backup("my_backup.db")

# Restaura o banco de dados a partir de um backup
db.restore("my_backup.db")
23 changes: 23 additions & 0 deletions examples/transaction2_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from simple_database.simple_database import SimpleDatabase
from simple_database.transaction import Transaction

# Cria uma nova instância do banco de dados
db = SimpleDatabase("example.db")

# Adiciona alguns dados
db.set("key1", 10)
db.set("key2", 5)

# Cria uma transação
with Transaction(db) as tx:
# Realiza algumas operações na transação
tx.set("key1", tx.get("key1") + 1)
tx.set("key2", tx.get("key2") - 1)

# Verifica os valores dentro da transação
print(tx.get("key1")) # Saída: 11
print(tx.get("key2")) # Saída: 4

# Verifica os valores fora da transação (devem ser os mesmos)
print(db.get("key1")) # Saída: 11
print(db.get("key2")) # Saída: 4
47 changes: 47 additions & 0 deletions examples/transaction_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from simple_database import SimpleDatabase
from transaction import transactional, transaction_manager


class Bank:
def __init__(self):
self.db = SimpleDatabase("bank")

@transactional
def transfer(self, source: str, destination: str, amount: float) -> None:
self.db.decrement(source, amount)
self.db.increment(destination, amount)

def balance(self, account: str) -> float:
return self.db.get(account, default=0)

def begin_transaction(self):
transaction_manager.begin_transaction()

def commit_transaction(self):
transaction_manager.commit_transaction()

def rollback_transaction(self):
transaction_manager.rollback_transaction()


bank = Bank()
bank.db.put("John", 1000.0)
bank.db.put("Mary", 500.0)
print(bank.balance("John")) # Saída: 1000.0
print(bank.balance("Mary")) # Saída: 500.0

bank.begin_transaction()
bank.transfer("John", "Mary", 300.0)
print(bank.balance("John")) # Saída: 700.0
print(bank.balance("Mary")) # Saída: 800.0
bank.rollback_transaction()
print(bank.balance("John")) # Saída: 1000.0
print(bank.balance("Mary")) # Saída: 500.0

bank.begin_transaction()
bank.transfer("John", "Mary", 300.0)
print(bank.balance("John")) # Saída: 700.0
print(bank.balance("Mary")) # Saída: 800.0
bank.commit_transaction()
print(bank.balance("John")) # Saída: 700.0
print(bank.balance("Mary")) # Saída: 800.0
1 change: 1 addition & 0 deletions simple_database/performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ def wrapper(*args, **kwargs):
return result

return wrapper

0 comments on commit fbe2ffe

Please sign in to comment.