#databases

1 messages ยท Page 46 of 1

terse stump
#

you are mixing Grafana with Graphite (this is a data source)

stoic pendant
#

ah, i see

terse stump
#

so use the expertice here to figure out what data source to use for your problem, then check if grafana supports it. ๐Ÿ˜„

stoic pendant
#

k, gotcha ๐Ÿ˜„

stoic pendant
#

@viral crag What would you suggest using, if you had to choose one or two, for my project?

viral crag
#

We use rethinkdb

#

but postgresql is a great SQL-based database

stoic pendant
#

thanks, i'll give these a look and get back to you ๐Ÿ˜ƒ

orchid charm
#
            self.bot.c.execute('SELECT SCN from Profile where UID = ?', (ctx.message.author.id,))
            result = self.bot.c.fetchone()
#
    if result >= bet:
TypeError: '>=' not supported between instances of 'tuple' and 'int'
#
(406,)

Why is the result a tuple?

#

No matter what i do it comes as a tuple

#

In other cogs this does not happen though

deep glacier
#

because you may fetch more than one item (per row)

#

and having the library automatically do (a,) -> a for single column selects would be inconsistent

hard rapids
#

hey guys

#

could i drop a question here?

#

ive got a pretty dumb question but i cant for the life of me find an answer

unreal tartan
#

bot.tags['ask']

delicate fieldBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

โ€ข Don't ask to ask your question, just go ahead and tell us your problem.
โ€ข Try to solve the problem on your own first, we're not going to write code for you.
โ€ข Show us the code you've tried and any errors or unexpected results it's giving
โ€ข Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

hard rapids
#

yeah alright then

#

AttributeError: 'pyodbc.Cursor' object has no attribute 'callproc'

#

im basiavlly getting that error

#

when following this documentation

#

and im clueless as to why an almost direct replica doesnt work in my scripts

ornate abyss
#

what is pyodbc

#

@hard rapids

#

Oh nvm i found the repo

#

This is not yet supported since there is no way for pyodbc to determine which parameters are input, output, or both.

You will need to call stored procedures using execute(). You can use your database's format or the ODBC escape format. For more information, see the Calling Stored Procedures page.```
hard rapids
#

@ornate abyss thanks I will look into it more tomorrow

#

but it seems weird that they include it in the docs without there being actual supporrt to me....

ornate abyss
#

That was taken from their docs

novel wharf
#

@light summit How's Redis with expiring data? Is there a default or do I have to specify?

#

I'm having some pretty big problems with client sessions that get stuck in the database. If they or the server crash, they aren't removed properly.

#

I'd actually like to call a redis.flushall() everytime the server restarts, but I have no idea how to pull that off nicely in Django.

torn sphinx
#

Hello. I am trying to create a currency system. I have 2 questions. How can I add coins to people database without having to reset the database? and then how can I make it add up coins and not replace the previous one? Fir example if he levels up he gets 10 coins. on the next level he gets 40 coins. but it wont add 40 to 10 it will jsut replace 10 to 40 it shouldbe 50

#

lv.update({'crystals': 10}, Levels.id == message.author.id)

#

How can I instert to everyones data ````crystals` :0```

ornate abyss
#

@novel wharf You can specify a TTL on keys with redis if thats what you mean?

#

@torn sphinx I dont understand your question

novel wharf
#

I want to make a simple user list, or any list really of connected clients. If expire only works on keys I'm not sure how it's helpful.

light summit
#

@novel wharf you're wanting to completely erase your database every time it restarts?

#

What?

novel wharf
#

Because I only use Redis for temporary game sessions

light summit
#

I thought you were storing play records in it, too

novel wharf
#

Nah, that's stored in Django's models

light summit
#

รต.รด

novel wharf
#

But I guess we figured it would be faster to use Redis and expire whatnot for game sessions that are to disappear the moment they're finished.

#

Like storing userdata and statistics in the regular database, and using Redis for disposable data. The game has to be stored somewhere while it's active

sick badge
#

hey I'm doing db management through python and i'm getting an error that says db is locked whenever i try and change anything

#

is there a way i can fix that

#

I'm using sqlite3

ornate abyss
#

@novel wharf When you say a list, do you literally mean the list type in redis, and would you want the entire list to expire or each individual element of that list to expire at their own rates?

novel wharf
#
"users":
    {
        "name": "Golen",
        "session": "<sessionId>",
        "time": ...
    }
    ...
#

This is what I'd like to store, and is how I'm currently doing it. Whenever a client connects they create a new consumer websocket connection, but I have no idea how to track that unless I do it myself.

#

And since you can visit the same page with multiple tabs, I use sessionId to separate the users to avoid some issues.

#

Then using my own timestamp thing to keep track of expired sessions, which happens all too often, such as when the client crashes or server resets.

ornate abyss
#

So how are you currently storing

    {
        "name": "Golen",
        "session": "<sessionId>",
        "time": ...
    }
#

like each connection

novel wharf
#

redis.set("users", userlist)

#

That dict is one user. Imagine a list of 10 such.

ornate abyss
#

Ah i see

#

Yea you cant individually set a TTL per set item with redis

#

Could you not instead have the sessionID as the key and use a hash?

novel wharf
#

So I'm actually using this, and they're doing a handful of redis stuff behind the scenes.

#

Like zadd whenever a new user connects, and a lot of hashing. I don't understand half of the source.

#

Here they add a TTL to each group_add thing, such that a user is disconnected within certain time, although it doesn't detect dead clients.

#

So if you play around for a while, everything starts slowing down immensely because of redis trying to group_send messages to a million dead clients.

#

And if you decreate the TTL time to something decently small, the package doesn't have a way of updating it in case a client pings or whatnot. They could be in the middle of a game and get kicked.

#

When you say using session as the key and use a hash, do you mean redis hset?

#

Like perhaps hset("users", sessionId), and then hscan to retrieve all sessions.

ornate abyss
#

Sorry was away for a bit

#

Well hset yea because then you can have each individual connection have its own TTL and expire through redis

novel wharf
#

That sounds really handy!

#

How would I increase the expiry upon a ping? I want to keep it low, but refresh it every so often.

ornate abyss
#

There is a Redis command called EXPIRE

#
127.0.0.1:6379> set t 10
OK
127.0.0.1:6379> expire t 100
(integer) 1
127.0.0.1:6379> ttl t
(integer) 97
127.0.0.1:6379> ttl t
(integer) 95
127.0.0.1:6379> ttl t
(integer) 94
127.0.0.1:6379> ttl t
(integer) 94
127.0.0.1:6379> expire t 100
(integer) 1
127.0.0.1:6379> ttl t
(integer) 99
#

Just as like a little example

#

apologies for the late reply again

novel wharf
#

Don't worry 'bout it

orchid charm
#

In SQL is there a way to wait for the current things that are reading/writing to the DB to finish?

#

Cause i got a "reroll" loop and every hour it does some SQL stuff

#

But it usually locks when another SQL event is happening at the same itme

#

Like a user chatting, or using one of my commands, ect.

ornate abyss
#

You will have to wait to acquire the lock, so im not sure what you mean

#

@orchid charm

orchid charm
#

?

#

Well what is locking my SQL then if it ain't the Every hour DB function and a user executing SQL stuff at the same time?

#

@ornate abyss

ornate abyss
#

im not sure how you thought i was saying nothing is locking your db??

orchid charm
#

Then what were you saying XD

#

Brain.exe never worked in the first place

ornate abyss
#

I was saying, basically i thought you were thinking it didnt wait to try to acquire the lock (it does) however i didnt know that you were meeting the timeout

#

which iirc is 5 seconds by default

orchid charm
#

So how would i fix this

#

And prevent it from locking

ornate abyss
#

A quick workaround could be try to increase the timeout

orchid charm
#

How would i increase the SQL timeout?

#

and what is the disadvantages to increasing the timeout

ornate abyss
#

when you do the sqlite.connect("some_db", timeout=x)

#

when its waiting to send the connection, that timeout will be blocking

#

so it could take up to 10 seconds for the next line of code to be executed

#

assuming you choose 10 to be your timeout

orchid charm
#

Ah

#

Well thats p simple ๐Ÿ‘

#

Ima do that

ornate abyss
#

yea, if you still get exceptions then youll have to handle them and retry the queries at a later date

#

Or if this becomes a massive issue, migrate away from sqlite

dull scarab
#

Won't it become an issue if you're using it with an async bot?

ornate abyss
#

tbh i didnt even notice it was a bot

#

Yes it will

orchid charm
#

Ah

#

So how would i do it and not have that be a issue then

ornate abyss
#

I think migrating away from sqlite in this instance is your best bet

dull scarab
#

๐Ÿ‘Œ

ornate abyss
#

Using something like postgres with an async library will work best

orchid charm
#

Well what works almost exactly like SQL and can write multiple times at once?

ornate abyss
#

sqlite is based on postgres so the SQL queries themselves wont need changing

dull scarab
#

Not "at once", but seemingly

orchid charm
#

Also how exactly do i migrate to postgres ;-; ive been trying XD

#

I am using a Mac OSX

ornate abyss
#

Are you running this bot on your mac?

orchid charm
#

Yes

#

Soon i will probably get a VPS tho

ornate abyss
#

I see, well youll need to install postgres and set that up

orchid charm
#

postgres.app?

#

If so i think i already got it

ornate abyss
orchid charm
#

@ornate abyss so i should use postgres.app?

ornate abyss
#

i dont know what that is

orchid charm
ornate abyss
#

what i linked is the postgres website, there is a download tab

#

looks good

orchid charm
#

Ok opening it

ornate abyss
#

Then youll need to find an async library to interface with it

orchid charm
#

@ornate abyss Which one would work most like SQL?

#

SQL3*

#

Also is commiting needed

ornate abyss
#

I don't understand the question

dull scarab
orchid charm
#

@ornate abyss Commiting is Saving to a Database

ornate abyss
#

No I didn't mean that part

#

And I know what committing is

orchid charm
#

Oh then what library would work most like SQL

ornate abyss
#

That doesn't make sense sorry

#

SQL is a language in its own right

orchid charm
#

ยฏ_(ใƒ„)_/ยฏ

ornate abyss
#

You use SQL to interact with postgres or well any relational database

dull scarab
#

Do you know what sql stands for weeb

orchid charm
#

sqlite

ornate abyss
#

SQL is structured query language

#

Sqlite is just a single file database

#

But yea, the library you choose is entirely up to you

#

Just make sure it's async really

orchid charm
#

How to use asyncpg correctly then cause i heard it is good

ornate abyss
#

Surely it has documentation?

dull scarab
#

I sent an example on how to implement asyncpg, connect and query a few messages up

ornate abyss
#

Not all heros wear capes

dull scarab
orchid charm
#

Ive already tried using that example to try and use Postgresql

ornate abyss
#

Just gonna have to keep reading the docs and trying

#

Dunno what else to suggest

orchid charm
#

Oh yeah, so how does increasing the timeout affect a d.py rewrite bot?

#

sqlite3

#

Does it just make it a bit slower?

ornate abyss
#

No, in the event of a timeout it will block your entire bot

#

Basically means for that timeout period your bot won't respond to anything

torn sphinx
novel wharf
#

Even though it's unoptimized code, the if-statements cost next to nothing.

#

If you wish to make them faster, you could group them together with elif instead of a new if every time. I doubt you can be two ranks at once, can you?

#

Although I supposed you've done it just in case someone somehow gets enough xp to bypass several ranks, in which case you might only want to display the latest rank anyhow.

#
if lvl == "RANK" and xp >= XP_REQ:
    lv.update({'level': "NEXT_RANK"}, Levels.id == message.author.id)
    lv.update({'rank': "NEXT_RANK_IMAGE"}, Levels.id == message.author.id)
    embed=discord.Embed(title="Tanki Online", url="...", color=0x00ffff)
    embed.set_thumbnail(url='...')
    embed.add_field(name=":sparkles: Rank up! :sparkles:", value="Congratulations **{}**! Your rank is now **NEXT_RANK**\n   โ€   ".format(message.author.display_name))
    await bot.send_message(message.channel, embed=embed)
#

This particular piece of code is repeated about 44 times, but with only a few changes. Try move this into a function and use loops! You'd need to store the data for RANK and XP_REQ, etc, elsewhere.

#

@torn sphinx

torn sphinx
#

So I will just use elif instead of if everytime. okay thanks

novel wharf
#

What's with Field Marshal that only requires 100 xp for the next rank?

#

As for your ranks, are they all in order, or are there any branches?

torn sphinx
#

I fixed the 100xp in marshal rank I forgot to change that from copy pasting. Also Yeah they are in order

#

Btw I want to create a curreny system but now I cant add for example coins because they already have a database. Or I can instert coins to their database?

novel wharf
#

There is a really nice way you can decrease all this code to just the code I pasted above.

#

If you can insert ranks, you should be able to insert coins the same way?

torn sphinx
#

I did made to instert ranks when they didn have a profile set so the bot would do. If the user is not in the database then

    lv.insert({'id': message.author.id, 'xp': 1, 'level': 'Recruit', 'premium': 'No', 'rank': 'image_link'})

But now they alreadyare in the database. :/

novel wharf
#

Right, at the bottom.

#

But they have a rank, don't they? What if you also give them 'coins': 0?

#

Then you update that the same way as you do with ranks~

#
coins = asd["coins"]
coins += 20
lv.update({'coins': coins}, Levels.id == message.author.id)
torn sphinx
#

I did add coins at the bottom but it didnt instert them in my profile. it will only add coins to people that talk for the first time I mean when they send their first message so the bot will add them in the database.
Because I made the bot check if the user is in the database if lv.contains(Levels.id == message.author.id):. If its not then instert him. else: lv.insert({'id': message.author.id, 'xp': 1, 'level': 'Recruit', 'coins': 0, 'premium': 'No', 'rank': 'https://i.imgur.com/tlyR0dt.png'})

#

But if someone is already in the database it wont add coins

novel wharf
#

Right, that makes sense. You have a lot of users with the old database.

torn sphinx
#

yeah

#

about 3.5k users

novel wharf
#

Oh boy.

torn sphinx
novel wharf
#

That's why you need to check whether a user has coins, and then you can add it! Consider this:```python
if "coins" not in asd:
lv.update({'coins': 0}, Levels.id == message.author.id)

torn sphinx
#

isn't is insert?

#

not update

novel wharf
#

Oh, sure.

torn sphinx
#

or it doesnt matter?

#

ok

novel wharf
#

Alternatively, if you have the database as a file someplace, you could write a short python script to update it and insert "coins":0 for everyone.

torn sphinx
#

Well I am not that pro with python so I would just use the first method you told me Xd

#

Thanks though

novel wharf
#

Cmon, should be easy peasy~ You're in a python server.

torn sphinx
#

wow you did all this for me?

novel wharf
#

If you store them in a list like this in python, you can do the rank check with a simple for-loop and test if a user has reached past a new rank.

#

I'm using macros in my editor, so it takes only a minute or two~

torn sphinx
#

damn lol It took me 2 days to do what you say in the hastebin XD Actualy 1 day for writing. cuz I spent 1 day trying to figur out how to make a leveling up system

novel wharf
#
for rank in reversed(ranks):
    if xp >= rank["xp"] and my_rank != rank:
        # New rank!
        return
#

And here's a quick example of how you could use that ranks list. Loop over it backwards, check if the xp is past the required xp, then update!

#

Gonna brb for a minute.

torn sphinx
#

Damn dude. You are so helpful. People in disord.py are so mean lol

#

Thanks

#

a lot

dull scarab
#

d.py is straight forward, and expect you to know python

#

Here it's more about helping you learn most of it

novel wharf
#

So what does the database look like? Is it json?

#

Let's make a script to add coins to it.

orchid charm
#
async def check_all_members():
    bot.c.execute('SELECT UID from Profile')
    rows = bot.c.fetchall()
    for member in bot.get_all_members():
        if not any(row[0] == member.id for row in rows):

So i got a problem with this, it is making Multiple of the same "Accounts"

torn sphinx
#

@novel wharf yes json

#

Let me upload it to sendspace

novel wharf
#

As long as it doesn't contain sensitive information.

#

I dont need to see it really. You can try opening it in a new Python script.

orchid charm
#
async def check_all_members():
    bot.c.execute('SELECT UID from Profile')
    rows = bot.c.fetchall()
    for member in bot.get_all_members():
        if not any(row[0] == member.id for row in rows):
            bot.c.execute('INSERT INTO Profile (UID, XP, LEVEL, SCROLLS, SCN, Snails, LevelUp, Rank, GCN, XPBooster, SCNBooster, InkBay) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',(member.id, 5, 1, 0, 0, 0, 100, 1, 0, 0, 0, 0))

Forgot to put in the insert

#

Anyways, do you know what i am doing incorrectly? it is making multiple of the same row

torn sphinx
#

I Dmed it to you

novel wharf
#

Could be something silly like string vs int comparison

orchid charm
#
async def check_all_members():
    bot.c.execute('SELECT UID from Profile')
    rows = bot.c.fetchall()
    for member in bot.get_all_members():
        if not any(row[0] == member.id for row in rows):
            bot.c.execute('SELECT UID From Profile where UID = ?', (member.id,))
            result = bot.c.fetchone()
            if not result:
                print('Woomy!')
#
TabError: inconsistent use of tabs and spaces in indentation
#

No Matter what i do it gives this error?

torn sphinx
#

fix your identation

#

youre mixing up tabs and spaces

#

use one or the other

orchid charm
#

Also, How to get x amount rows with the highest value

#

Its like a "Leaderboard"

#

Also i am making a "Owned Items" Command
How would i get all the rows with a Users ID in them and put each row into a variable

#

Sqlite3

dull scarab
#

Sort by value, get x first-

#

Query members ID, and just put it in a list/dict or simply stick to the response object

orchid charm
#

Oh?

dull scarab
#
 fetchall()

    Fetches all (remaining) rows of a query result, returning a list.```
#

So you don't need to convert to a list, but you can still make it a dict if you need to assign values to specific names

orchid charm
#

so fetchall
then how to insert parts of it into variables?

#

result[1] result[2] ect?

dull scarab
#

Is each item stored as a row connected to a member?

orchid charm
#

yeah

dull scarab
#

Then yes.

orchid charm
#

How to check how many rows it grabbed? @dull scarab

dull scarab
#

len(results)

orchid charm
#

Ah

#

@dull scarab Also how to convert the tuple it is giving to something else? like a Str

#

or do i do something like str(result[1)

vestal apex
#

these seem like really trivial questions you could answer yourself in a matter of seconds

dull scarab
#

You don't have to test on your actual bot either

#

open the python interpreter

# You know it's a tuple, create a dummy
>>>test_tuple = (1, 2, "a")

# Now simply test...
>>>print(test_tuple[0])
1

# Keep in mind print calls str() on it's arguments

>>>type(test_tuple[0])
<class 'int'>
>>>type(test_tuple[2])
<class 'str'>

>>>test_tuple[1]
2

>>>str(test_tuple[1])
"2"```
rain karma
#

Could someone come along side me and help me structure my tables for a project? I understand that what I'm asking for is vague and time consuming, however, I have been trying to sketch out my table structure for a few weeks now and I still can't seem to get things well organized

novel wharf
#

Give us a description in here of what you're trying to do.

torn sphinx
#

Hey! Im trying to get my crypto miner machine to rapport its hashrate and gpu temps so a simpla database on the internet! Any tips on what librarys i whould look in to ?

vestal apex
#

not sure what this has to do with databases...

#

and it probably depends on what software you're using to mine

compact owl
#

hello! I am currently learning about databases and websites and stuff with python and I just started creating a simple database to understand how it works.

#

I am having a problem with the insert function as part of the database code

#

I am using "/t" as a delimiter to seperate the key from the value after being read.

#

and I was trying to find ways to encode the backslash as a different sequence of characters to prevent it from corrupting my table

#
def insert(filename, key, value):
    file = open(filename, "r")
    ogn = file.read()
    key = key.replace('''\\''', '''\\\\''')
    value = value.replace('''\\''', '''\\\\''')
    if key in ogn:
        print("This key has already been used.")
    elif value in ogn:
        print("This value has already been used.")
    else:
        print(key)
        print(value)
        file = open(filename, "a")
        file.write(key + '/t' + value + ' /n')
    file.close()

insert("data.txt", "prsdf6@outlook.com", "Rashim Kesa\ni")
#

I tried doing it such a way that the backslash would be replaced by the escape character for backslash

#

or do I need to change it to somehting else

dull scarab
#

I wouldn't call appending to a txt file a database.

#

Also, you're opening 2 instances of the file, and only closing one from what I can tell

#

Are you getting any errors @compact owl

compact owl
#

nope

#

well a simplified database

#

I guess

#

the text file is the table

dull scarab
#

Mkai, and what's the issue?

compact owl
#

if you look at where I called the function

#

I purposely put a backslash next to the "n" in teh name

#

I am also using /t as my delimiter for when I read off the text file

#

so I am trying to figure out ways to turn the backslash into two backslashes before storing

#

and then decoding after reading from the txt file

#

so I am trying to use the replace() string method

#

but for whatever reason, the value remains unchanged

#

I tried assigning the "value" parameter's value to another variable and then applying replace() to that

#

but I am unable to change the single backslash to two backslashes

#
def insert(filename, key, value):
    file = open(filename, "r")
    ogn = file.read()
    file.close()
    key1 = key
    value1 = value
    key1.replace("\\","\\\\")
    value1.replace("\\", "\\\\")
    if key in ogn:
        print("This key has already been used.")
    elif value in ogn:
        print("This value has already been used.")
    else:
        print(key1)
        print(value1)
        file = open(filename, "a")
        file.write(key1 + "\t" + value1 + "\n")
    file.close()
#

any help would be appreciated

dull scarab
#

How do you want this to look in your data.txt file?
Kesa\ni

#

like Kesa\\ni?

compact owl
#

kesa\ni

#

sorry the latter

#
Kesa\\ni
#

in the txt file itself

#

but when I write my read function

#

I need to be able to change it back to Kesa\ni

#

and print that to console

#
def insert(filename, key, value):
    file = open(filename, "r")
    ogn = file.read()
    file.close()
    key1 = key
    value1 = value
    key1.replace("\\","\\\\")
    value1.replace("\\", "\\\\")
    if key in ogn:
        print("This key has already been used.")
    elif value in ogn:
        print("This value has already been used.")
    else:
        print(key1)
        print(value1)
        file = open(filename, "a")
        file.write(key1 + "\t" + value1 + "\n")
    file.close()

insert("data.txt", "prsdf6@outlook.com", "Rashim Kesa\ni")
#

here is the full code

dull scarab
#

Well, your text viewer will view \n as a new line, but you could just convert that back to \n with py def read(filename): with open(filename, "r") as data: data_string = data.read().replace("\n", "\\n")

compact owl
#

okay

dull scarab
#

prints
prsdf6@outlook.com/tRashim Kesa\ni /n

compact owl
#

hmm

#

so its fine?

dull scarab
#

the \n is still in the txt, sort of

#

But it's viewed as a new line

compact owl
#

so I can just leave it the way it is?

#

and read it and get the result I want?

dull scarab
#

You could also pass write a raw string

compact owl
#

yeah that's another thing

dull scarab
#
r"somestring\n that wont be formated"
compact owl
#

it keeps giving me weird stuff when I type r in front of my strings

dull scarab
#
def insert(filename, key, value):
    file = open(filename, "r")
    ogn = file.read()
    if key in ogn:
        print("This key has already been used.")
    elif value in ogn:
        print("This value has already been used.")
    else:
        print(key)
        print(value)
        file.close()
        file = open(filename, "a")
        file.write(key + '/t' + value + ' /n')
    file.close()

insert("data.txt", r"prsdf6@outlook.com", r"Rashim Kesa\ni")```I changed your code slightly, and it writes `prsdf6@outlook.com/tRashim Kesa\ni /n`  to my data.txt now
compact owl
#

okay here's another question

dull scarab
#
def insert(filename, key, value):
    file = open(filename, "r")
    ogn = file.read()
    file.close()
-    key1 = key
-    value1 = value
-    key1.replace("\\","\\\\")
-    value1.replace("\\", "\\\\")
    if key in ogn:
        print("This key has already been used.")
    elif value in ogn:
        print("This value has already been used.")
    else:
        print(key1)
        print(value1)
        file = open(filename, "a")
        file.write(key1 + "\t" + value1 + "\n")
    file.close()

-insert("data.txt", "prsdf6@outlook.com", "Rashim Kesa\ni")
+insert("data.txt", r"prsdf6@outlook.com", r"Rashim Kesa\ni")```
compact owl
#

hmm

dull scarab
#

I used the old code you sent. whopsie

compact owl
#

is there a way to change the strings into raw strings within the function?

#

also

#

what if the email has a "\t" in it

#

how would I change that backslash to something else before storing

#

then decode after reading?

#

thanks for the help btw

dull scarab
#
    key = f"{key!r}"
    value = f"{value!r}"```
#

That should convert your input to a raw string, I think

compact owl
#

wats this?

#

hmm

#

can I leave it as just a string and it would still be fine without the raw string?

dull scarab
#

It's more or less the same as ```py
key = "{!r}".format(key)

or old style

key = "%r"%key```

#

as far as i know

compact owl
#

cool

dull scarab
#

Are you even allowed to use \ in emails

compact owl
#

yea

#

you are

#

but just as a scenario

#

how would I edit my code

#

to encode the backslash

#

which is what I was trying to do earlier

dull scarab
#

I'll be honest, I think this would be a lot easier if you converted it to json or some other data storage method

compact owl
#

lmao it would

dull scarab
#

That way you could just fetch the keys, and do what you wanted with those values

compact owl
#

I guess

#

yeah

#

but I want to know how now

dull scarab
#

Hm

compact owl
#

and then I will be off your back

#

cause for whatever reason

#

when I try to change the parameters within the function

dull scarab
#

Well, you are also using /t, not \t

compact owl
#

sorry

#

i meant \t

dull scarab
#

well currently your data looks like this 'prsdf6@outlook.com'\t'Rashim Kesa\ni' \n

#

Right?

compact owl
#

yeah

dull scarab
#

So you could just use the ' to seperate key and value

compact owl
#

what if the email was like bob\t@gmail.com or something

#

I know, but I am curious about how it would work if I would use \t as delimiter. sorry if I am being stubborn

#

If i were to use any other character

#

this problem wouldn

#

t

dull scarab
#

Honestly, I don't know

compact owl
#

hmm

#

yeah its weird

dull scarab
#

Most of the answers I've given so far I've personally googled and learned myself now

compact owl
#

lmao

#

I have tried to research string literals

#

and raw strings

#

but they don't work really

#

when I am trying to change backslash to escape characer for backslash

dull scarab
#

But feel free to experiment and I'm sure people would be happy to help you solve your erros etc

compact owl
#

yup

#

thank you for the help

#

I appreciate it

dull scarab
#

Also, you'd probably get more and faster help in #help-coconut - 4

compact owl
#

yea

#

that's what I was going to do next

#

XD

#

Again, thanks

dull scarab
#

I'm off to bed though, Good luck

compact owl
#

gn

torn sphinx
#

Anyone got any recommendations for videos to watch on Databases with Python3 so I can get up to speed?

#

Used databses but only in Microsoft Access, never with Python or SQL

ionic pecan
#

Videos? No

#

The SQLAlchemy tutorial is good

sweet nebula
#

is there a way to incorporate a database into an app using python. The database should be app-side and shouldn't require internet access to be able to acquire data from the database. Instead the database should be able to save data given by the user onto the device directly???? (IDRK) and will be able to access that data at a later date. IF this is at all possible that would be great.

ornate abyss
#

SQLite

#

@sweet nebula

sweet nebula
#

should i just research into SQlite and i should find whag i need or is there any specifics i should focus on?

ornate abyss
midnight verge
#

When working with SQLAlchemy, is there any way to apply a default filter to a relationship? For instance I have:

class Foo(Base):
    __tablename__ = 'foos'

    id = Column(Integer, primary_key=True)
    bars = relationship('Bar', back_populates='foo', lazy='dynamic')

class Bar(Base):
    __tablename__ = 'bars'

    id = Column(Integer, primary_key = True)
    foo_id = Column(Integer, ForeignKey(Foo.id)
    foo = relationship('Foo', back_populates='bars')
    deleted = Column(Boolean, default=False)

What I would like to be able to do, with assert isinstance(foo, Foo), is automatically filtering foo.bars so that deleted bars (i.e. with deleted is True) are not returned by default.
I could not manage to find a nice way to do this without using a proxy function, any idea? ๐Ÿค”

unreal tartan
midnight verge
#

@unreal tartan looks perfect, thanks ๐Ÿ‘

glass bough
#

so, when I want to select all from a table where column_name = string

#

correct?

dull scarab
#

wdym?

glass bough
#

nvm, I'll work on it

#

hard to explain

#

I want to select all from a table where in a column it is equal to a string, which I assume would be written as

#

"SELECT * FROM tableWHERE column = {}".format(string)

dull scarab
#

Doesn't your lib have ? variables for queries?

#

If so i strongly recommend using it

glass bough
#

got it

#

was missing a comma

ornate abyss
#

You dont want to use string interpolation to format a query

sweet nebula
#

is it possible to store images in a sqlite databse?

worn stream
#

I don't think so

#

possibly if Base64 encode it

sweet nebula
#

so if i base64 encode it before entering it to the datbase i can save it as TEXT, then when i need the data i can call it and then decode it back to an image for display?

hidden ginkgo
#

Should be possible.

vestal apex
#

you can, you probably shouldn't

sweet nebula
#

XD

#

but idk what else to do

vestal apex
#

can't save to the filesystem?

orchid charm
#

How to Insert multiple selects into multiple variables with one query

vestal apex
#

could you clarify what you mean by "multiple selects"?

orchid charm
#

Multiple "Queries"

vestal apex
#

so you want to perform multiple queries... in one query?

vestal apex
#

it's possible you want the IN clause of SELECT queries, but without additional information I have no idea if that's what you need or not

dull scarab
#

Saw the suggestion about RethinkDB in #discord-bots , is there any big benefits to migrating over using Postgresql?

ionic pecan
#

well idk

#

I use postgreSQL personally and its really great

#

It probably depends on your usecase

#

I remember that rethinkdb advertised thie realtime query result push, but I haven't seen that used anywhere yet

dull scarab
#

Ah, thank you

ornate abyss
#

You really want to have a long think if you are using a NoSQL database

ionic pecan
#

wdym?

compact owl
#

Yay I am using SQL now

ornate abyss
#

Saw the suggestion about RethinkDB RethinkDB is a NoSQL DB

#

NoSQL DB's (as im sure youve seen striking say a lot) are used a lot when a regular RDBMS could be used

compact owl
#

In a SQLite database, how would I check if a table exists? I need to make a table only once.

vestal apex
#

you could use a CREATE TABLE IF NOT EXISTS query

compact owl
#

okay

#

thanks

subtle warren
#

essentially have a relationship that comes from two columns in a table

#

(player1 and player2)

#

also I don't like the duplication. If I want to add more information about a player, I need to copy/paste it and add 2 to it

#

is there a better way to do it?

#

I am 100% certain it will always only stay two players (it's a fighting game), so generalizing it with a player-game-association table to have an arbitrary amount seems like overkill

#

and I would have to have code in some places that checks if there was ever more than 2 players in a game etc. and I don't even want it to get to that

#

this is sqlalchemy btw, but I thought people that know it, would recognize

subtle warren
#

if someone can help me later, please @ me!

unreal tartan
#

If a User needs game-specific data you only have 2 options: the duplicate options where you store it all in the game, or the user-game association table like you suggested yourself.

Both are valid options, yes you have duplicate column names, it's a denormalized model in the first solultion. But denormalizing data gives back the benefit of being quicker if you need all the data, because there's no joins.
Normalizing has the benefit of having no duplication, cleaner, but a slight performance hit because you need joins to retreive all data.

I'd probably start off with the 'clean' model and see if you have any true issues with speed. If not, I see no need to denormalize.

Game:
- game data
- players 

Player:
- Game
- User
- extra data for player for a specific game

User:
- name

@subtle warren

subtle warren
#

if I was to go with the denormalized model, do you know how I could make that relationship work?

#

(I will probably take your advice and go for the association table GameUser or something)

#

also is there maybe a nice way to make the database or sqlalchemy ensure constraints like "only two users per game"?

unreal tartan
#

Well it's basically what you have in the code you posted but you would literally have like

class Game(Base):
    __tablename__ = "games"

    id = Column(Integer, primary_key=True)
    player1Id = Column(Integer, ForeignKey("users.userId"))
    player1 = relationship("User", backref="games")
    player1_hp = Column(Integer)    
    player2Id = Column(Integer, ForeignKey("users.userId"))
    player2 = relationship("User", backref="games")
    player2_hp = Column(Integer)

So you just duplicate the hp column for each player. It's inefficient for data storage, but efficient for querying.

subtle warren
#

I need to query all games of a user every time I want to recalculate the rank, so I think querying is more important than storing

#

but I will still go with it, because it's less ugly to potentially copy&paste 8 columns or something

#

thank you so much for your help @unreal tartan !

unreal tartan
#

Can't quickly think of a way to easily put the 2-player constraint on the DB

subtle warren
#

I guess I will just check it whenever get the players of a game

unreal tartan
#

You could still do player1 and player2 in the game.

#

but the relevant data would be in the player table.

#
Game:
- game data
- player1
- player2

Player:
- Game
- User
- hp
- extra data for player for a specific game

User:
- name
subtle warren
#

oh jeez, that sounds like a good solution too

#

in what way is denormalization in this case bad?

#

I mean: what kind of stuff is problematic with this structure?

#

or can go wrong more easily

#

*this specific structure

unreal tartan
#

Well let's say you denormalize and put player back into game basically

Game:
- game data
- User1
- user1_hp
- User2
- user2_hp

User:
- name

There's nothng terribly bad, but you just have duplciate column names.
It's acceptable with 2 players, but you can imagine the repetitiveness with more.

The main problem comes that now if you like to add an extra field in, let's say, a weeks time. You have to do add it X times depending on players (2 in this case)
Same for deleting. A delete of a single atttribute, means deleting more than 1 field in the database.

#

It's not a very bad case really. It'd get worse if you merged the User's table as well.
After 2 games you might have this:

Game
id | player1_hp | player2_hp | player1_name | player2_name
0  | 0          | 60         | xxx          | yyy
0  | 56         | 0          | xxx          | yyy
#

Clearly you see there's duplicate data in the table: the names.

subtle warren
#

yeah, absolutely, but I was more talking about the last suggestion of yours

unreal tartan
#

Yea there it's not all that bad except for future database changes that you have to do twice.

subtle warren
#

where all the data is in an extra table and I juse have two references to rows of that table in a game

#

I think I will take that gamble

unreal tartan
#

Oh in my last example there's even less things bad.

#

I think it might even be better to have player1_id and player2_id.

subtle warren
#

why do you think that?

unreal tartan
#

Because then it satisfies the maximum of 2 players requirement.

subtle warren
#

yeah, that's why I like it

#

okidoki!

#

thank you so much for your help again! also for writing it up with so much detail!

subtle warren
#

I think in all the examples with an extra table i need to save the user and the player, so I can easily get User.games

#

but maybe that's not worth the duplication

torn sphinx
#

does anyone know if sqlalchemy has unique random indentifiers for the databases it connects to?

#

or maybe not random

#

basically I want to see if my two applications connect to the same database

ionic pecan
#

welll, look at your auth credentials?

torn sphinx
#

I don't have any. It's a sqlite database. And my two applications are two docker containers

#

main flask app container and celery container

#

i suspect they each create their own db.sqlite file

unreal tartan
#

If you don't specify any connection parameters, that sounds like a fair assumption

#

Use docker run -it <image name> /bin/sh to go into both docker images and see if you can find the sqlite files.

torn sphinx
#

I'm changing over to devops channel

orchid charm
#

It is not grabbing the info, why?

#
    async def on_message(self, message):
        self.bot.c.execute('Select Censor from CensorList where GID = ?', (message.guild.id,))
        result = self.bot.c.fetchall()
        print(result)
        print(len(result))
        print(message.guild.id)
        censorint = 0
        censormessage = message.content
        for item in result:
            if result[censorint][0] in censormessage:
                censormessage = censormessage.replace(result[censorint][0], '*' * len(result[censorint][0]))
        if censorint > 0:
            await message.channel.send(f'{censormessage}')
#

This is the full event

#

But this is mostly a Database question so i put it here

orchid charm
#

NVM. Fixed it.

rancid bronze
#

hey yall i'm moving to production pretty soon -- i'm putting my db on my vps where the webapp is hosted -- how should I backup the db?

shadow sphinx
#

ok so i have a tkinter program
and i want to store data from it into a sqlite database
but everytime i close the app
the tables get cleared
how do i prevent this
(i have the database made into a class)

#

heres the code

low berry
#

When using parameterized SQL with python does it automatically put the single quotes around the argument?
ex:
SELECT * FROM ss_orders where ao_MergedIds like %s
turns into:
SELECT * FROM ss_orders where ao_MergedIds like '1234'
?

ionic pecan
#

pretty sure that's the case, although if you're using something like SQLAlchemy you can print the query it sends

#

doesnt parametrization use ? though

fringe gale
#

code

def add(num1, num2):
    return num1 + num2    

def main():
    operation = input("what calculation do you want to make (+,-,*,/):")
    if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
            #if invalid operation
            print("you must enter a valid operation")
        else:
            var1 = int(input("Enter num1: "))
            var2 = int(input("Enter num2: "))
            #adds var1 and var2
            if (operation == "+"):
                print(add(var1, var2))

            
main()

error:

C:\Users\Vadim\Desktop>python test.py
  File "test.py", line 10
    else:
        ^
IndentationError: unindent does not match any outer indentation level```
#

what am i missing?

#

wrong chat whoops

#

just noticed

unreal tartan
shadow sphinx
#

@fringe gale ur else is indented to far in

#

remove and

fringe gale
#

@shadow sphinx already fixed it, thanks though ๐Ÿ˜ƒ

shadow sphinx
#

k

bright pelican
shadow sphinx
#

ok so i have a tkinter program
and i want to store data from it into a sqlite database
but everytime i close the app
the tables get cleared
how do i prevent this
(i have the database made into a class)

#

heres the code

unreal tartan
#

you don't actually execute the commit methods

#

You just retrieve them from the object

shadow sphinx
#

That means?

unreal tartan
#

you should add ()

cinder pelican
#

using flask-sqlalchemy, and anytime I commit a second user it gives me an IntegrityError

UNIQUE constraint failed: user.email [SQL: 'INSERT INTO user (username, email, first_name, last_name, password) VALUES (?, ?, ?, ?, ?)']
#

I checked the database and it does add the record

#

should I try to try/except this and do a rollback? what is even happening?

ionic pecan
#

are you sure it adds the record?

#

if the constraint fails, it probably shouldn't ..

#

can you show your model definition?

cinder pelican
#
class User(db.Model):
    """
    User model for database
    """
    id = db.Column(db.Integer, primary_key=True)  # Unique identifier
    username = db.Column(db.String(16), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    first_name = db.Column(db.String(256), nullable=False)
    last_name = db.Column(db.String(256), nullable=False)
    password = db.Column(db.String(60), nullable=False)

    def __repr__(self):
        return (f'User({self.username}', f'{self.email}', f'{self.first_name}', f'{self.last_name}', f'{self.password})')
#
def on_register(form_data):
    """
    Fired when user passes validation.
    """
    new_user = User(
        username=form_data['username'],
        email=form_data['email'],
        first_name=form_data['first_name'],
        last_name=form_data['last_name'],
        password=form_data['password']
    )
    db.session.add(new_user)
    db.session.commit()
#

this is what I do when someone registers

shadow sphinx
#

how to i get rid of the brackets when i pull data out of the table

#

using sqlite

#
        c.execute("SELECT * FROM Favs")
        x=c.fetchall()
        self.favlist=[]
        for i in x:
            self.favlist.append(i)
            self.favlist.append("##")
patent glen
#

what do you mean get rid of the brackets

shadow sphinx
#

@patent glen

#

the brackets and shit around the entrys

patent glen
#

what exactly are you doing to display that

#

it looks like your "i" is actually a data row with three columns, not a string

#

but also you're creating a list

#

what do you want it to look like

shadow sphinx
#

a straight line

#

with all of the rows in it

patent glen
#

ok but what do you want between the title, the date, and the description

shadow sphinx
#

space

patent glen
#

ok

#

how are you putting the favlist in the window

shadow sphinx
#
def addintodatabase(name,rdate,plot):
    try:
        db.execute("INSERT INTO Favs (Name,release_date,Plot) VALUES(?,?,?);",(name,rdate,plot))
        db.commit()
    except Exception as e:
        removefromdatabase(name,rdate)
patent glen
#

i would suggest doing self.favlist.append(' '.join(i)), and then when you display it using '##'.join(self.favlist) instead of whatever you're doing

#

i said how are you putting it in the window, not how are you putting it in the database

shadow sphinx
#

oh

#
    def showfavs(self):
        self.favwin=Toplevel(self)
        c.execute("SELECT * FROM Favs")
        x=c.fetchall()
        self.favlist=[]
        for i in x:
            self.favlist.append(i)
            self.favlist.append("##")
        self.favlist=str(self.favlist).replace("##","\n")
        favlabel=Label(self.favwin,text=self.favlist)
        favlabel.pack()
#

using a label

patent glen
#

or just '\n'.join (why are you using ##?)

shadow sphinx
#

idk i did that once before it just showed \n

patent glen
#

so like python for i in x: self.favlist.append(' '.join(i)) self.favlist="\n".join(self.favlist)

shadow sphinx
#

ty

cinder pelican
#

weird.. database fixed itself ๐Ÿค”

dull scarab
#

Could someone give me a quick rundown on relational keys in postgres

#

Say I have 2 tables, one for people and one for pets and I put a pets id as a relational key in people. Do I still have yo querry pets etc to fetch info about a pet assigned a person

subtle warren
#

@unreal tartan I was here a few days before and I hope it's not rude to ping you. I asked about how to create a relationship from two columns, like this: https://hastebin.com/eharuhasuq.py

#

and I did a lot of other stuff since then and just now could really try it out and it errors

#

sqlalchemy.exc.ArgumentError: Error creating backref 'games' on relationship 'Game.clientUser': property of that name exists on mapper 'Mapper|User|users'

#

this seems to me the clientUser relationship can not be created, because hostUser has already created a "games" property

#

so there must be some other way to do this (if there is at all)

#

I guess specifying a custom (primaryjoin?) for a games property in User could be an option.

#

games = relationship("Game", primaryjoin="or_(Game.hostUserId==User.userId, Game.clientUserId==User.userId)") like this?

#

this does not error, but it's gonna take a while to really try it out. this was more a "just so you know" kind of thing

gleaming frost
#

Dont store passwords ๐Ÿ˜ 

#

Without hash and salt

gusty spindle
#

^ this.

dull scarab
#

Does anyone know what i'd need to do to connect 2 tables?

#

So i dont have to query both, and find matching results

viral crag
#

That's called a join query

#

Left join, right join, inner join

#

Kind of an advanced topic but useful to know

dull scarab
#

I've used inner join a bit during my database and datahandling course

#

And know kinda... how it works

#

Basically creates a new table with other tables right?

dull scarab
#

Can you store data is postgresql in the form of a dict?

#

I'm setting up configs to be saved in my db, with lot's of different types for each key.. like lists, strings etc

#

Or would i be better off just making a json file for it

quick marlin
#

if your config is read-only (as it should be) then why would you want a db for it

dull scarab
#

I guess config is the wrong term then

quick marlin
#

a json file should do, though for configs something with comments, like yaml, may be better

dull scarab
#

But generally stuff my bot needs to keep track of like blacklisted text channels etc

#

Blacklisted channels in general, and that would just be (text, anyarray) for storage, but I thought i'd create it.. a bit more flexible for future things

#

Actually... is a db query faster than checking for element in list?.. could just make a blacklisted table and call it a day GWcmeisterPeepoShrug

knotty snow
#

element in list time complexity is O(n)

#

if you used a set or dictionary, it's O(1), though. blacklisted table is a good solution.

dull scarab
#

How efficient are databases in general?

#

Would it ever be considered bad to create a table for just a bit of data?

knotty snow
#

databases are efficient for large amounts of data, but they also can add overhead to your program. it's probably not worth the time or effort to seriously add a database for a small amount of data

#

and it may actually end up slowing down your program ( inter process communication is slower than having something in local memory)

#

but if it's for learning about databases, go for it

dull scarab
#

I'd like to know more about it, like down to the bare bones. If you got any reads that would be great

knotty snow
#

do you want to learn how databases work internally orfrom a outside perspective

dull scarab
#

Stuff like, what happens with open connects, with queries, executions, opening/quering/closing etcetc

#

Just get a good feel for databases behind the scenes, and from an outside perspective

#

Probably not the deepest of deep layers within database builds Monksass

knotty snow
#

maybe something you can try before you read about is to try and implement a database yourself

dull scarab
#

I have multiple with my discord bots, and studied datastructure (which had basic sql) at uni a year ago

knotty snow
#

never watched this, but it's by the creator of SQLite, so i imagine it's in depth

dull scarab
#

Neat

#

I'll make sure to give it a watch

torn sphinx
#

guys i'm sorry to ask this here but I have an Excel related question

#

may I ask here?

knotty snow
#

it's vaguely a database

gusty spindle
#

@torn sphinx if it's about interacting with excel spreadsheets using python then yes, you could ask here. if it's just about excel in general, it would be better to go to #ot0-fear-of-python, especially as it's already almost not about databases anyways :P

grim reef
#

Would it be a bad idea to use google spreadsheet to store large amounts of data?
If so, does anyone have a suggestion for a database that can be stored on a cloud and accessed by two or more pc's at once?

#

just @ me when anyone responds thanks

ionic pecan
#

Postgres would work

#

Depends on your usecase though

knotty snow
ionic pecan
#

that's not what they asked

grim reef
#

Postgres is a local database is it not? what happens if the hdd of the pc its on goes?

#

Is it possible to Postgres's data on something like OneDrive?

vapid cairn
#

i am working with postgres in my bot and had a questions about how to handle the initial creation of tables and then altering the table at a later date to add columns that you didn't plan for. Right now, I only have one table and it shouldn't need to change, but I wanted to create another table and over time i think there will be columns i will want to add/remove. My one table i currently have I created with something like "CREATE TABLE IF NOT EXISTS table_name ( row_id SERIAL PRIMARY KEY, etc.....).

Would a better method to create tables be to create a blank table (or maybe with just a primary key ) then add the columns with "ALTER table_name ADD COLUMN IF NOT EXISTS".....that way if i need to add another row, i can just another ALTER command? I hope this makes sense...i may just be missing something simple since i really don't know sql that well.

dull scarab
#

First rule of databases, plan it out :'P.

#

I aint got your answer though SadHug3

dull scarab
#

How would i Increment a value in a row, while decrementing another value? Transfer money from person a to b in one query

#

Just pass 2 queries in one execute?

#
await bot.db.execute("""
        UPDATE users
            SET money = money + $1
        WHERE id = $2 AND guild_id = $4;

        UPDATE users
            SET money = money - $1
        Where id = $3 AND guild_id = $4;""",
        amount, fid, tid, gid)``` Or is there a fancier way of doing it
ionic pecan
#

@vapid cairn you really shouldnโ€˜t be doing this from your bot programmatically, use migrations

vapid cairn
#

@ionic pecan can you point me to to some docs to understand what you mean by that ๐Ÿ˜ฌ

ionic pecan
#

Like, instead of dynamically changing your tables from your program, you should manage the tables it uses through something else

#

Django also has an amazing migrator built-in

#

Depends on what you're using

orchid charm
#

In SQLITE, how to wait for All Processes to be done before doing something?

patent glen
#

what do you mean by that

orchid charm
#

@patent glen Wait for All other Sqlite things to be finished

#

Like, i got a on_message event in d.py that does SQLite

#

And another event that uses SQLite

#

Then a command that uses SQLite

#

I want it to wait until those "Processes" are complete

patent glen
#

this really sounds like more of a discord.py question (but are you even using sqlite asynchronously?)

#

but note that sqlite does support transactions (you may need to use separate connections), if that ends up being relevant to the problem you're trying to solve

orchid charm
#

@patent glen How to use Seperate Connections?

#

Also, how to use SQLite asynchronously

#

Is it Aiosqlite? if so i don't know how to use XD

#

Also this is a Database Question, it just happens to be in a D.PY Bot

patent glen
#

if you're not doing that and you're not doing threads, then it's unlikely you'll have two things going on at the same time anyway

orchid charm
#

Threads?

patent glen
#

and by separate connections i meant just calling sqlite3.connect each time you have an operation instead of keeping one open for the lifetime of the program

orchid charm
#

Oh

#

So i redefine it every time

patent glen
#

ok back up a bit

orchid charm
#

Creating a new "connection"

patent glen
#

you say you want it to wait until those processes are complete

#

but i'm not clear on why you think it's not already waiting

orchid charm
#

Database Locks happen too often

#

Cause of so much SQLite

patent glen
#

if you're not using aiosqlite

#

....what errors are you actually seeing

orchid charm
#

Database is locked

#

Database is closed

patent glen
#

is this database shared between your bot and other processes?

orchid charm
#

Yeah

#

1 Database

#

For Multiple "Cogs"

patent glen
#

ok hmm

#

ok it also looks like i was a bit overly optimistic about the capabilities of sqlite, hold on

orchid charm
#

Once we figure this out i will scrap everything i coded and work on the thing i was making from Square 1

#

Cause #1 Alot of my Code in this bot was never updated cause its a Very Old Bot #2 Terrible Coding #3 Insane Amount of SQLite and database locking

patent glen
#

ok i think your issue probably is caused by keeping the connection (well, the transaction) open too long.

#

are you remembering to call commit after each operation?

#

(well, each logical stopping point that it's in a consistent state, anyway)

orchid charm
#

Yeah

#

I do Commit after every Operation

#

The Only Operation that really is buggy is one that uses a While Loop Gonna be fixed in the new ver of the bot

patent glen
#

ok maybe you do need to be opening and closing the connection each time instead of just holding it open

orchid charm
#

Oh?

#

How does that work

#

And what does Closing a connection do exactly

#

And how many connections can be open at once?

patent glen
#

ok from what i can tell

orchid charm
#

I am a idiot

patent glen
#

the database is locked error should only show up when another process has the database open and in a write transaction for longer than five seconds.

orchid charm
#

Oh

#

Ive tried using Timeout

dusk sparrow
#

5 seconds. HOly smokes

orchid charm
#

It just makes stuff slow

dusk sparrow
#

๐Ÿค”

orchid charm
#

Oof

patent glen
#

...that just makes it wait longer than five seconds, it won't help if the other process is keeping it forever

orchid charm
#

Still it slows stuff down

dusk sparrow
#

why exactly is a db used for bot prgarmming?

orchid charm
dusk sparrow
#

or rather what is a db used fr

#

?

orchid charm
#

@dusk sparrow Profile system

patent glen
#

anything you want the bot to keep track of

orchid charm
#

And Holding Info

dusk sparrow
#

oh

#

and it's slow because of the query

#

or the size of the db

#

or sqlite?

patent glen
#

they're having file locking problems, which probably means that one process is keeping it locked forever because it doesn't commit the transaction and/or close the connection

orchid charm
#

I don't exactly know why it gets so slow, maybe cause so many processes at once?

dusk sparrow
#

Hmm

patent glen
#

how many processes are you accessing this database with

orchid charm
#

The on_message event handles the most important bot stuff

dusk sparrow
#

so this is not a central db but a db for your app I assume

orchid charm
#

Ima show you the code for on_message

patent glen
#

uhh

#

do you know what a process is

orchid charm
#

I just call Query/Write/Reads "Processes"

patent glen
#

that's not what a process is

#

what i meant is how many instances of your bot (or other programs) are using this database

#

at the same time

orchid charm
#

Also only one Instance of bot is using stuff, multiple .py files are using this database

#

And that is my on_message

patent glen
#

ok for one thing you're not committing after the insert

#

(you don't have to do it after every insert, but you should do it after the account create operation as a whole, at the end)

orchid charm
#
    while len(shoesset) < 6:
        bot.c.execute('Select ShellaFresh1 from Botinfo')
        ShellaFresh1 = bot.c.fetchone()
        bot.c.execute('Select ShellaFresh2 from Botinfo')
        ShellaFresh2 = bot.c.fetchone()
        bot.c.execute('Select ShellaFresh3 from Botinfo')
        ShellaFresh3 = bot.c.fetchone()
        bot.c.execute('Select ShellaFresh4 from Botinfo')
        ShellaFresh4 = bot.c.fetchone()
        bot.c.execute('Select ShellaFresh5 from Botinfo')
        ShellaFresh5 = bot.c.fetchone()
        bot.c.execute('Select ShellaFresh6 from Botinfo')
        ShellaFresh6 = bot.c.fetchone()
        bot.c.execute('Update BotInfo set ShellaFresh1 = ?',(random.choice(shoes_set),))
        bot.c.execute('Update BotInfo set ShellaFresh2 = ?',(random.choice(shoes_set),))
        bot.c.execute('Update BotInfo set ShellaFresh3 = ?',(random.choice(shoes_set),))
        bot.c.execute('Update BotInfo set ShellaFresh4 = ?',(random.choice(shoes_set),))
        bot.c.execute('Update BotInfo set ShellaFresh5 = ?',(random.choice(shoes_set),))
        bot.c.execute('Update BotInfo set ShellaFresh6 = ?',(random.choice(shoes_set),))
        bot.conn.commit()

This is probably the most Problamatic thing, but i think i got a idea how to fix it

patent glen
#

what is bot.c and what is bot.conn? is c the cursor?

orchid charm
#
bot = commands.Bot(command_prefix='//')
bot.conn = sqlite3.connect('profiles.db')
bot.c = bot.conn.cursor()
patent glen
#

ok

#

where exactly are you getting the database locked error, anyway? it should only happen in connect, which you only do once, right?

orchid charm
#

It happens when alot of Sqlite is being used

patent glen
#

ok is there anything other than your bot using this database

orchid charm
#

Like lets say my 1 Hour Reroll thing happens, i do a command, and on_message all at the same time

patent glen
#

i don't understand how you can get the error if there is only one process with only one connection

orchid charm
#

It would Almost Guranteed Lock

patent glen
#

huh???

#

what function is raising the exception, exactly

#

what is a 1 hour reroll

orchid charm
#

It Updates Database info for multiple things

#

And "Rerolls" their info

patent glen
#

ok what does 1 hour mean in this context

orchid charm
#

If it is a hour

#

So

#

Like 1:00PM

patent glen
#

like, after an hour? with no activity before

orchid charm
#

2:00PM

patent glen
#

ok, i think i get it

orchid charm
#

It always does it on the hour mark

patent glen
#

ok maybe it's bad to leave a transaction open that long

orchid charm
#
if now.minute == 0:
#
                self.bot.c.execute('Update BotInfo set Headspace1 = ?',(random.choice(headgear_set),))
                self.bot.c.execute('Update BotInfo set Headspace2 = ?',(random.choice(headgear_set),))
                self.bot.c.execute('Update BotInfo set Headspace3 = ?',(random.choice(headgear_set),))
                self.bot.c.execute('Update BotInfo set Headspace4 = ?',(random.choice(headgear_set),))
                self.bot.c.execute('Update BotInfo set Headspace5 = ?',(random.choice(headgear_set),))
                self.bot.c.execute('Update BotInfo set Headspace6 = ?',(random.choice(headgear_set),))
                self.bot.c.execute('Update BotInfo set YeOldeClothShoppe1 = ?',(random.choice(shirt_list),))
                self.bot.c.execute('Update BotInfo set YeOldeClothShoppe2 = ?',(random.choice(shirt_list),))
                self.bot.c.execute('Update BotInfo set YeOldeClothShoppe3 = ?',(random.choice(shirt_list),))
                self.bot.c.execute('Update BotInfo set YeOldeClothShoppe4 = ?',(random.choice(shirt_list),))
                self.bot.c.execute('Update BotInfo set YeOldeClothShoppe5 = ?',(random.choice(shirt_list),))
                self.bot.c.execute('Update BotInfo set YeOldeClothShoppe6 = ?',(random.choice(shirt_list),))
                self.bot.c.execute('Update BotInfo set ShellaFresh1 = ?',(random.choice(shoes_set),))
                self.bot.c.execute('Update BotInfo set ShellaFresh2 = ?',(random.choice(shoes_set),))
                self.bot.c.execute('Update BotInfo set ShellaFresh3 = ?',(random.choice(shoes_set),))
                self.bot.c.execute('Update BotInfo set ShellaFresh4 = ?',(random.choice(shoes_set),))
                self.bot.c.execute('Update BotInfo set ShellaFresh5 = ?',(random.choice(shoes_set),))
                self.bot.c.execute('Update BotInfo set ShellaFresh6 = ?',(random.choice(shoes_set),))
                self.bot.conn.commit()
#

This is what it is Updating

patent glen
#

i don't even see that function in your paste

#

but there are places in the paste you sent that don't commit

orchid charm
#

That is a on_message

#

This is a loop

patent glen
#

ok but

#

any of your problems could be caused by any code that ran before that failing to commit

orchid charm
#

This is the Loop

patent glen
#

so you need to fix all the places you didn't commit

orchid charm
#

Also when you were talking about opening and closing connections, how to do that

patent glen
#

forget that for now

#

you'd have to rewrite the whole thing

orchid charm
#

Yeah i know

#

I am rewriting the whole bot

patent glen
#

and i'm not sure it's necessary

#

there are at least two or three places in on_message you need to add commit

orchid charm
#

Well my bot already has stupid code

patent glen
#

anyway i meant instead of having a global bot.conn and bot.c

orchid charm
#

Define it in every cog?

patent glen
#

create the connection and the cursor in each function that uses it, and then commit and close the connection at the end

#

cog?

orchid charm
#

Cog is a .py file

#

That has a class

patent glen
#

no, each function

orchid charm
#

Oh

#

Any downsides to that?

patent glen
#

so that it only connects when it runs the function, and disconnects at the end of the function (or when it's done using the database)

orchid charm
#

Oh it disconnects when it is done automatically?

patent glen
#

...you need to call close()

orchid charm
#

so

#

conn.close

patent glen
#

yeah

orchid charm
#

Sweet

#

Thanks Mate

patent glen
#

just fixing the commits might deal with 90% of the problem though

hollow tiger
#

why no mongodb

orchid charm
#

@hollow tiger Wat ๐Ÿ‘€

orchid charm
#

@modest haven Wait autocommit?

#

How to Enable ๐Ÿ‘€

#

This would be so damn useful

orchid charm
#

How to "Query" Multiple things at once and Insert them into Multiple Variables

#

In SQLite

#

Instead of something like this
cur.execute('SELECT SOMETHING FROM SOMETHING')
result1 = cur.fetchone()
cur.execute('SELECT SOMETHINGELSE FROM SOMETHINGELSE')
result2 = cur.fetchone()

Just do it in one Query and insert the info into the variables all at once

ionic pecan
#

select x, y from z

#

look up sqlite sql syntax

#

you can then just unpack the result

#

x, y = cur.fetchone()

orchid charm
#

so i just use comma

#

Sweet this works Perfectly

#

This is gonna save me so much Code

#

Does it work the same with Set?

#

If i wanted to set multiple things to multiple things in one query

orchid charm
#

So Ally was talking about a Autocommit, how to do that?

dull scarab
#
async def dump_log(bot):
    logs = bot.msg_log
    query = """
        INSERT INTO messages
        (msg_id, author_id, channel_id, guild_id, content, date)
        VALUES($1, $2, $3, $4, $5, $6)
        ON CONFLICT(msg_id, author_id)
        DO NOTHING
            """
    args = list(logs.items())

    async with bot.db.transaction():
        await bot.db.executemany(query, args)
    bot.msg_log = []``` Would this be a good way to dump a log of my bot? Or are the more efficient ways to do so with asyncpg
#

Mostly thinking about this part py async with bot.db.transaction(): await bot.db.executemany(query, args)

#

This happens every 5 min, or shutdown of bot

ionic pecan
#

hmm

#

apart from preparing the insert i don't think so

dull scarab
#

Had to change it back, since i couldn't directly convert a record to list it seemed

#
async def dump_log(bot):
    logs = bot.msg_log
    query = """
        INSERT INTO messages
        (msg_id, author_id, channel_id, guild_id, content, date)
        VALUES($1, $2, $3, $4, $5, $6)
        ON CONFLICT(msg_id, author_id)
        DO NOTHING
            """
    args = []

    for log in reversed(logs):
        msg = log["msg"]
        if not msg:
            msg = "<Media transmitted>"
        args.append((log["id"], log["author"], log["channel"], 
                        log["guild"], msg, log["date"]))

    async with bot.db.acquire() as connection:
        async with connection.transaction():
            await bot.db.executemany(query, args)
    bot.msg_log = []```
#

So not as pretty anymore

ionic pecan
#

hmm

#

are you building some ingestor kind of bot?

dull scarab
#

Also bot.db is a pool

#

Not connectiong, so i'd have to fetch the connection to create a statement wouldn't i?

#

It's a twitch stream bot

#

So keeping logs for moderation

ionic pecan
#

ohh

dull scarab
#

All encrypted and secure, worry not dblSmile

ionic pecan
#

i'm not entireley sure myself, I use peewee_async as an ORM in my bot

dull scarab
#

It's not a big issue if it's not super efficient, was just curious if anything could be done at this moment

#

It's a rare feature, only available to administrators

#

So won't be used a lot

lavish ferry
#

i need help

#

my bot is hosted on heroku, and there I also hosted the .json file, where the points of the people on my server are stored, the problem that every 1 day, my .json file resets, and this is bad because the points of the people of my server resets too, I would put in a database, could someone help me?

cinder pelican
#

bot.tags.get ask

delicate fieldBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

โ€ข Don't ask to ask your question, just go ahead and tell us your problem.
โ€ข Try to solve the problem on your own first, we're not going to write code for you.
โ€ข Show us the code you've tried and any errors or unexpected results it's giving
โ€ข Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

cinder pelican
#

have you looked into what sort of databases you want to use?

lavish ferry
#

no, I wanted one that stores my json and keeps updating forever, without resetting

cinder pelican
#

even though SQLite doesnโ€™t have support with async it shouldnโ€™t slow it down too much, unless your bot is really big

lavish ferry
#

know if there is another site that I can host my bot and that does not reset my files? why the heroku resets, and that's awful

#

glitch ?

#

.... great help

torn sphinx
#

heroku is meant to be for testing not actually putting stuff there

dull scarab
#

Can I so similarity searches in postgres?

#

Like sort by closest match to string query, and return a limit of 10 for top 10 matches

pallid schooner
#

Hey

#

Im working on a employee db app

#

but

#

I dont know how to store user input to a db

#

Any help?

fair laurel
#

Have you tried searching for any tutorials on Google?

pallid schooner
#

@fair laurel I see things about relational db

#

But it doesnt help with what I have in mind

fair laurel
#

What do you have in mind?

hollow tiger
#

Are there any databases that store data in a dictionary format? I currently use a huge json file and my Discord bot is starting to slow down

#

I'm also looking for a database service that's easy to use since i'm new to databases

restive violet
#

yaml maybe?

#

or just sqlite

hollow tiger
#

but like in a dictionary format

#

{'like':'this'}

#

not a table

#

yaml?

restive violet
#

do you know how a dictionary works?

wispy fable
#

@hollow tiger If you want a more permanent solution, use an sql database

#

iirc, sqlite3 is included with python

restive violet
#

some sqlite comes with it

#

i think it's 3

hollow tiger
#

yeahh but like my current bot stores data in a dict format and i don't wanna have to change everything into a table format

wispy fable
#

An actual .db file is special because when reading or writing to it, the entire file does not need to be loaded into memory, only the part that is being modified does

restive violet
#

idk what you mean dict format

wispy fable
#

You can make a table behave like a dict

#

But if you want a performance improvement, then this is an obstacle you'll have to overcome

hollow tiger
#

well

restive violet
#

sql does a lot of clever shit under the hood for speed

wispy fable
#

If you're not using an actual database, then your performance gains will only be marginal

hollow tiger
#

idk how i'd implement it

#

    "Rob and Many's hangout": {
        "apps": {
            "junior mod or junior admin": {
                "intro": "Apply for Junior mod or junior admin: Many_Roblox2\nThanks for applying for Junior mod or junior admin, Many_Roblox2! Remember to answer all the questions truthfully.",
                "app": [
                    "Will you follow the rules?",
                    "How active are and how mature are you?",
                    "What can you bring to the server?",
                    "Do you have any ideas to improve the community server?",
                    "Do you have any experience in moderating a discord server?",
                    "Why do you wanna become a moderator?",
                    "How would you handle a issue (A troller for example)",
                    "Will you respect everyone?",
                    "How active are you? From a scale to 1 to 10."
                ]
            },
            "suggestions for the server": {
                "intro": "Apply for Suggestions for the server: {user}\nThank you for applying for Suggestions for the server! Answer all questions truthfully.",
                "app": [
                    "Do you have any suggestions?",
                    "Are you an staff member?",
                    "What is your suggestion?",
                    "Do you think we will add it?",
                    "Do you understand you are not aloud to rage if it's gets denied."
                ]
            },
            "cancel": {
                "intro": "cancel"
            }
        },
        "prefix": [
            "/",
            "-"
        ],
        "members": {
            "gagi12": {},
            "Many_Roblox2": {},
            "TheDutchSwagBoi": {}
        }
    }```
#

that's for one item i have in my dict

#
    "\ud83d\udd25Server's_United\ud83d\udd25": {
        "apps": {},
        "prefix": [
            "/"
        ],
        "members": {}
    }```
wispy fable
#

You could also opt to split all the data into multiple json files to emulate what an db file does

hollow tiger
#

that's true

#

it's just that my data is like a huge tree structure

#

and simply having it in a grid i think wouldn't be enough

restive violet
#

you need to load it into memory

#

that's what will give you speed

#

reading and writing to some file will be a big bottleneck

wispy fable
#

Your sql table could be just two columns, both strings representing a key and the contents of each key's location

hollow tiger
#

well i was thinking for one db file

#

each table would represent a server

#

but idk how i'd go from there

restive violet
#

read up on sqlite

#

people do it all the time

hollow tiger
#

how do ppl do it with a huge structure :(

#

here's how my data's organized:

wispy fable
#

We're not going to do your reorganizing for you

restive violet
#
c.execute('insert into tablename values (?,?,?)', [dict['id'], dict['name'], dict['dob']])
wispy fable
#

But we'd be more than happy to help with specific issues

hollow tiger
#

if i were to use tables, how would I put a tree in?

#

a multilevel dict

#

if i figure out how to do that then i'd be glad to try to learn sqlite

restive violet
#

use executemany

hollow tiger
#

but atm idek how i'd put data in

#

executemany?

restive violet
hollow tiger
#

i mean like how i'd organize a dictionary if there's more dicts and lists inside

#

that example only has one big dict

#

but i kinda have dicts and lists in the big dict

#

and it's like lists in dicts that are in a bigger dict

#

i can't think of an organized way to keep the data in a table format

restive violet
#

why not just combine data of x depth in and just append to db

#

and when you read it out you split it up

hollow tiger
#

what are all the benefits of a database anyways?

#

compared to having multiple json files storing data

versed coyote
#

Performance, scalability, integrity and concurrency guarantees, redundancy

hollow tiger
#

performance?

#

that's a lot of things i do'nt get

#

imma research

#

"integrity and concurrency guarantees, redundancy"

#

sry i'm pretty dumb i'm still learning

restive violet
#

sql is not simple under the hood

#

does a lot of cool stuff

#

but the idea is to stay in memory as much as possible

versed coyote
#

SQL is a language

#

Look up ACID

#

In computer science, ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties of database transactions intended to guarantee validity even in the event of errors, power failures, etc. In the context of databases, a sequence of database operations that satis...

#

One of several fundamental concepts behind relational databases

#

Which is what SQL is a language for

hollow tiger
#

i heard about NoSQL?

midnight verge
#

@hollow tiger NoSQL are databases that do not use SQL, in general, do not use NoSQL DBs unless you really need it

#

(protip: you do not need it 99% of the time)

hollow tiger
#

why not?

midnight verge
#

Because SQL provides structure and constraints

#

(among other things)

hollow tiger
#

i heard big companies used mongodb

#

y they didn't hav problems?

midnight verge
#

and companies using MongoDB do not only use MongoDB most of the time, and only use Mongo for a very specific part of their database

dull scarab
#

I read in a recent thread about some firm having issue with mongo as well

#

They migrated to postgres and never looked back

hollow tiger
#

oh

midnight verge
#

tl;dr: do not use NoSQL unless you need it (and this is usually not the case)

hollow tiger
#

i just have a huge structured database

dull scarab
hollow tiger
#

not database

#

big json file with a dictionary in it

#

but it has lists in dicts in a bigger dict

midnight verge
#

if your dictionnary items follow a structure, then you can very easily store the data in a SQL data

hollow tiger
#

it sorta does

midnight verge
#

then go with SQL DB ๐Ÿ‘

hollow tiger
#

here's a base thing

#
"Testing": {
    "apps": {},
    "prefix": [
        "/"
    ],
    "members": {}
}```
#

that's one item of the biggest dict

#

each dict item will be a table for me

#

but

#

sometimes

midnight verge
#

depends

hollow tiger
#
"apps": {
            "crew": {
                "intro": "Thank you for applying to the COVL crew, {applier}! Please fill these qeustions truthfully and dont hesitate to ask one of the staff if there is qeustions!",
                "app": [
                    "What is your Gamertag?",
                    "What is your social club account name?",
                    "What is your age?",
                    "From wich country are you?",
                    "Do you speak English or Dutch?",
                    "What is your gender?",
                    "Why do you want to be in \"COVL\"?",
                    "Do you agree to have a saved outfit of the crew?",
                    "How often are you online playing?"
                ]
            }
        },```
#

this is what "apps" became in a server

midnight verge
#

yeah

restive violet
#

@hollow tiger can i ask if you know what differs between a list and dict

hollow tiger
#

['this','is','a','list']

restive violet
#

under the hood though

hollow tiger
#

{'this':'is','a':'dict'}

#

under the hood?

restive violet
#

they are very different

hollow tiger
#

well i kinda like to think of dicts as lists but u can name each item instead of having 0, 1, 2, and 3

#

etc

restive violet
#

see that's why i asked

#

dicts operate totally different

#

easier question would be

hollow tiger
#

:o

restive violet
#

how does a set differ from a list

hollow tiger
#

set?

restive violet
#

myset = set(1,5,6,7)

hollow tiger
#

idk what a set is

restive violet
#

ok so

#

when you want to find an item in a list

#

what do you do

hollow tiger
#

like[3] for the 2nd item

restive violet
#

nah but you don't know which index

#

just value inside

#

["asd","sdfh","gyu","dfd4"] find "gyu"

hollow tiger
#

like

#

.index

#

()

#

["asd","sdfh","gyu","dfd4"].index("gyu")

#

2

restive violet
#

ehh aside from that

#

what is common method

#

.index is rly just abstraction of it

hollow tiger
#

uhmawei

#

i do'nt get what u mean

restive violet
#

you do for....

#

for k,item in enumerate(mylist):
if item == "gyu": return k

#

right?

hollow tiger
#

oh yea

#

that works too

restive violet
#

index is same just abstracted

#

now.. how about a dict

#

how do you find something in a dictionary

#

the value i mean

hollow tiger
#

for k,item in enumerate(mydict):
   if item == "gyu": return k``` ig?
restive violet
#

nah given a key i mean

hollow tiger
#

if key == 'gyu'

#

return item

restive violet
#

if dict[key] == 'gyu' right?

hollow tiger
#

yeah

restive violet
#

the point is

#

from a dict you shouldn't/don't have to iterate through and check this and that

#

it'll get it instantly with the key