#databases

1 messages Β· Page 144 of 1

signal cloak
#

I need to add it to notes list

torn sphinx
#

Coming back to this real quick, kinda confused still.

a user can have 1 role, shouldn't that be a 1 - many instead of many to many?

shy shuttle
#

are you sure a user can only have 1 role? if so, you dont need 3 tables. But i would rethink that to make sure it's what you want

signal cloak
#

like I need the pythonic way to insert in a list of an existing document

torn sphinx
#

but a normal user, should have 1 role which is the 'user' one

#

then the developer should get the developer role

shy shuttle
torn sphinx
#

okay, i'll just keep it many to many for now

#

maybe it will click tomorrow, pretty tired too atm

shy shuttle
torn sphinx
#

it's a ERM anyways πŸ˜›

#

sure sure! thanks.

#

user with subcription should be 1 - many right

#

a user can have a subscription

#

but a subscription can be bought by multiple users

shy shuttle
# torn sphinx but a subscription can be bought by multiple users

that depends on what a "subscription" means. If its a generic object that is assigned to users, then that is many to many (users may have many subscriptions, and a subscription can be assigned to many users). but if it is treated more like an account, then it's one to many (a user may have many subscriptions, but each entry in the subscription table is only for 1 user)

torn sphinx
#

Makes sense, thanks for your help

#

I've got to watch a crash course in the morning

signal cloak
#

any idea guys, I need like the method on how to do it

#

in python

#

add json to list in exitsting item in collection

torn sphinx
signal cloak
#

ty

torn sphinx
#

1 user is able to have 1 subscription in the account

#

a user has a subscription, that's 1-1 right

shy shuttle
# torn sphinx a user has a subscription, that's 1-1 right

if they can only ever have 1 subscription at a time, then that is right. But in that case, what really is the difference between an account and a subscription? does it make sense to have separate tables, or can you merge the subscription columns into an existing table?

signal cloak
#
collection.update_one(
        {'_id': user_id},
        {"$set": {"notes": [].append(note)}},
    upsert=True)```
#

This should work or not cause rn its not working

#

i get a null value in mongo

signal cloak
gloomy canopy
signal cloak
#

also its giving me a null value still

gloomy canopy
signal cloak
#

Ok thanks

#

also i see now

#

its giving them like a json file

#

like that

gloomy canopy
signal cloak
#

There is no way to remove the 0: or 1:

#

and do it like

#
    {"id": 1},
    {"id":"asdas114=-ads"}

]```
#

smt like that

#

like a list of objects

signal cloak
#

or i think its in my code the problem

gloomy canopy
#

Yes, that is possible. You've got to make sure the value you're setting is a Python dictionary, looks like it was an empty string, then None, then a string of a dictionary (from json.dumps()?)

signal cloak
#

I did json.loads(str)

#

can I show you haha

#
                note = Journal(str(id),title.content,details.content, "")
                note = note.toJSON()
                note = json.loads(note)
                print(ctx.author.id)
                await insertNote(ctx.author.id, note)
#
collection.update_one(
        {'_id': user_id},
        {"$addToSet":{"notes": note}},
    upsert=True)```
#

the second one is the function

#
def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__, 
            sort_keys=False, indent=4)```
crystal aspen
#

hey i am using sqlite3 and i am trying to pass this query but getting syntax error how should i fix it ?
f"insert into k_cards(print, card_name,series_name,ed2_code) values(?,?,?,?) on conflict(print,card_name,series_name) do update ed2_code = {code}",prints,name,series,code

shy shuttle
rocky moth
#

I have two database tables:
Table A
Receipt_ID Line_Number
abc 1
abc 2
Table B
Receipt_ID Line_Number Ship_Number
abc 1 1
abc 2 2
How do I validate if there is a 1:1 or 1:many relationship between Tables A & B?
I don't want to check 1 Receipt_ID at a time manually. I'd like to find some sort of query logic.

obtuse glacier
#

Can someone help me with databases cus I'm not understanding

torn sphinx
#
    await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, levelup_id int, PRIMARY KEY (guild_id,))")

Im asking at this part

PRIMARY KEY (guild_id,))

Do i need the ,
or can i just have (guild_id))

twin palm
#

How can we create ER diagram of NoSQL Database(Firebase)?

worthy lance
#

Hello πŸ™‚ I need to store NACE codes (https://www.ssb.no/en/klass/klassifikasjoner/6) in a Postgres db (will be using Python and SQLAlchemy). Could use some help regarding the structure. As you can see, the codes are organized in levels and typically take on this structure:

  Level    Code    Desc    Short_desc   
 ------- -------- ------ -------------- 
      1   A        Text   Shorter text  
      2   01       Text   Shorter text  
      3   01.1     Text   Shorter text  
      4   01.11    Text   Shorter text  
      5   01.110   Text   Shorter text  
rich trout
#

It would probably make the most sense to attach each code to an ID, and then store them straightforwardly as level being an int, code a varchar, desc a text, and short as a text as well

#

While you could go with a composite datatype for Code, that feels like overkill, is not portable, and is essentially no faster

worthy lance
#

@rich trout I (we) are trying to normalize to the greatest extent possible. The SSB API gives us a useful field "parentCode", which in the case above would be the "Code" for the row above.

#

So we're thinking of maybe having a relation between code and parentCode

rich trout
#

Well, consider that in many cases normalizing to the maximum amount possible is not always a good thing

worthy lance
#

But the problem is code and parentCode wouldn't be unique (as a composite primary key)

#

Yeah, I think this might be one of those cases honestly

rich trout
#

Me too

#

Protip: do not use string primary keys

worthy lance
#

Thanks πŸ™‚ Why not? πŸ˜„

rich trout
#

Because they're hard

#

numeric primary keys are very easy to work with, store, compare, etc

worthy lance
#

Thanks for pointing out. We'll avoid it where we can, but some of the API's we use do it (e.g. some kind of UUID)

#

And we're creating a system for automated data retrieval (with historic data), so we need to rely on the API response for primary key selection

rich trout
#

Well, uuids have their own type distinct from text for this purpose

worthy lance
#

Oh, that's good to know!

rich trout
#

A very common solution is to ensure each table has an integer primary key, and use that for within-database operations, ensuring everything links the same way, and then exporting out to the more complex representation when needed

#

In your case, where each entry can have a ton of parents, and the resultant code is the combination of them

#

someone smarter than me could write queries to simply have parent and a one character code.. but that's not me

#

and I'd just advocate updating them as a group

worthy lance
#

You'd have to traverse all the way up the parent tree to get a unique value

rich trout
#

Hm

#

I've found something

worthy lance
#

Wow, thanks! I've been thinking about lately how google-fu is really what makes the programmer

#

And I couldn't figure out how to google this one lmao

rich trout
#

Yeah, took me a moment lol

#

It's a tree structure, so I should have searched postgres tree

#

wish you luck!

worthy lance
#

Thanks again πŸ™‚

#

@rich trout I have one final question though - how should I define the primary key, considering I need to match it against API responses in the future?

rich trout
#

oh nice

#

The primary key is the path to the node

worthy lance
#

Oh okay - so the ltree column actually stores the entire path?

#

If so, I didn't get that initially πŸ˜„

rich trout
#

Pretty much. But the example you linked has an id column on top of that

#

Which I do recommend. It's essentially free

worthy lance
#

Yeah, in one way it makes sense to me. I guess it "helps" the db engine to have reasonably typed primary keys. In another way, a generated primary key wouldn't help in mapping API data to the db

#

I guess we'd typically have to query the ltree column then to get the mapping right

rich trout
#

well, consider

#

If you have the path -> query ltree

#

if you have a db row -> query database normally with ids

worthy lance
#

Of course, that absolutely makes sense

#

So store relations using id, and map against API using path

#

Now I'm hearing you πŸ™‚

#

Is there some type of command I can execute here to appreciate your helpfulness? πŸ˜„

rich trout
#

nope, and I'm thankful. Just here to help and hope I'm finding the right things and not the wrong ones lemon_sweat

civic schooner
#

anyone here that knows databases

#

well I need help to understand one thing

#

is it possible to add data from a login system to SQL database? and how will i do this?

cunning jolt
#

wdym data based on a login system?

elder vessel
#

hey!

#

can i have 2 permissions in @commands.has_permissions(kick_member=True or ban_member=True) ?

#

hmm??

burnt turret
#

Wrong channel, #discord-bots would be the place, but check out commands.check_any

signal cloak
#

Can somebody come voice and explain me how mongo db arrrays waork?

north locust
#

how do i use google firebase in python?

civic schooner
cunning jolt
#

you can add any relational data to sql

#

also wdym with "login system"

civic schooner
#

yes but i have a login system how can i link that with the database?

cunning jolt
#

a login system can mean anything

tame mauve
#

Hi there, just wondering if you have ever got your question replied :) I'm kind of going through the same path. Cheers

cunning jolt
#

you need to be a bit more specific

civic schooner
cunning jolt
#

insert the data and request it when you need it

civic schooner
cunning jolt
civic schooner
#

btw I have no experience with SQL

cunning jolt
#

yes this is a tutorial intended for beginners

civic schooner
#

yes i get it check a tutorial, but all i need is to know how to link it then actually start coding in SQL

cunning jolt
#

?

#

you dont code in sql

civic schooner
#

No

civic schooner
cunning jolt
civic schooner
#

i dont think you are answering my question

#

I just want to low key link SQL database to my python login system file. Am I able to do this?

cunning jolt
#

so if you want to store data on a database you do these things:
install the db
set it up
and tell your program how to interact with it

civic schooner
#

i don't feel like you are answering my question

cunning jolt
#

i am

civic schooner
#

so with what you are saying I can't link it to a SQL database

#

uh .. dear programmers

cunning jolt
#

you dont link a database

#

a database is like google for example

#

a really bad comparison but it'll do for now

#

you can ask it for data and it'll give it to you

#

also the other way around

#

so if you want to "link" your program to an sql database you have to install one first

#

then find the appropriate library for your database

#

and then your program can add/remove/request data from the database

civic schooner
#

hm ... okay so what if I want to push all the data from the login system to the database, how will I do this?

cunning jolt
#

how does it work currently

civic schooner
#

I have no idea, I have just worked with flat files

cunning jolt
#

can you maybe send the code?

civic schooner
#

there is nothing to send

#

like i said i have just operated with flat files through a link

#

i have not started coding in SQL

cunning jolt
#

no i meant the code of how the system currently works

civic schooner
#

what .. ?

#

my Login system?

cunning jolt
#

yes

civic schooner
#

is that what you mean? ... Well why do you want to see it

cunning jolt
#

to get an understanding of what you want to do

civic schooner
#

there is no errors there is really nothing to see

civic schooner
cunning jolt
#

also for a login system with a db it usually works this way: you have a user stored in a db the user has a hashed password attribute when the user enters a password it gets hashed and the program requests the hashed password stored in the db if they are equal the user authentication is successful

civic schooner
#

I just want to push data to a database from a login system which I have made

cunning jolt
#

so

#

i have no idea what this data is you're talking about

#

i have no idea how the login system you have works

civic schooner
#

have you not seen a login system?

cunning jolt
#

i have no idea what the login system you have even protects

cunning jolt
civic schooner
#

nope

#

a login system made in tkinter

cunning jolt
#

a operating system login?

civic schooner
#

no a login system made in tkinter

cunning jolt
#

what for

civic schooner
#

for learning

cunning jolt
#

then sql isnt what you're looking for

civic schooner
#

why?

cunning jolt
#

because sql is intended for storing much more data

#

ie a website authenticating thousands of users

#

if its just for a single password its not really worth it

#

if you really want to use sql use sqllite

civic schooner
#

Look ... I have decided to learn SQL no matter what and all I need is to push data from a login system and I do not know how to do this?

cunning jolt
#

what data do you even want to push?

civic schooner
#

any data accessed in the Login system... Look do you know how to do this or not?

cunning jolt
#

i know how to do this

civic schooner
cunning jolt
#

i just dont know what exactly you're trying to do

civic schooner
#

why I need it is not really your business besides I already told you learning purposes

cunning jolt
#

look if you're not telling me what you want to do i cant help you

north locust
#
Extension 'cogs.socialv2' raised an error: NameError: name 'db' is not defined```
```py
import firebase_admin
from firebase_admin import credentials

cred = credentials.Certificate("beta/cogs/whiskeybotdatabase-firebase-adminsdk-g9ckh-c52eb0824a.json")
firebase_admin.initialize_app(cred)
ref = db.reference("/")```
is that code valid?
civic schooner
cunning jolt
#

there is a library called sqllite

proven arrow
#

There’s a dozen ways to answer that question, so you need be more specific

cunning jolt
civic schooner
cunning jolt
#

doesnt work that way

north locust
cunning jolt
#

data just isnt somewhere magically

proven arrow
cunning jolt
#

would be nice if it were that way tho

civic schooner
#

Well Like I said I don't know anything about databases and I do not know which library I should use based out of hearing what I want to do ... Which one do u recommend for me.

cunning jolt
#

so if its just local use sqllite

#

its a library that you can store/retrieve data from using sql

north locust
#

what should i define db =
what should i put in it?

civic schooner
proven arrow
civic schooner
cunning jolt
#

also dont work automatically

north locust
north locust
# proven arrow I think you need to import it from firebase admin
freeCodeCamp.org

This article a detailed guide that'll help you set up your Firebase database and perform simple CRUD operations on it using Python. Firebase, as you might know, is a platform provided by Google to accelerate app development. It offers BaaS or backend as a service, which means that Firebase takes

civic schooner
proven arrow
civic schooner
#

the data is accessed dynamically

north locust
proven arrow
north locust
proven arrow
#

Also the official firebase docs had good examples

north locust
#

lol im dumb i apparently accadentally deleted this line

#
from firebase_admin import db```
#
    @commands.command(name='boop', description='boop someone', alias=['boops', 'Boop', 'Boops'])
    async def boop(self, ctx):
        ref.set({
            "Books":
            {
                "Best_Sellers": -1
            }
        })

        ref = db.reference("/Books/Best_Sellers")
        import json
        with open("book_info.json", "r") as f:
            file_contents = json.load(f)

        for key, value in file_contents.items():
            ref.push().set(value)

where do i put the database url?

proven arrow
#

In the db.reference

signal cloak
#

How can I customize 0,1,2

#

like push my variables there

#

as ekys

#

keys

burnt turret
#

you mean you don't want 0, 1, 2..there, you want your own keys? then that wouldn't be an array anymore

#

those are indices

untold robin
#

suppose i have dataframe:

id  tstamp  val  day
1   2021-03-etc  63.9  2
4   2021-03-etc  89.3  4
#

imagine that there are ids from 1 to 6 240k rows. i want to cut my dataframe down in aggregate by:

  • compute the mean of the value for the given day associated with it (this day was acquired by stringformat time, takes the day of the tstamp column)
  • then, also, retrieve the max timestamp value for the given day associated with it
#

so i am left with a dataframe that has the average value for the day as well as max timestamp

#

i am new to pandas and stuff and when I use groupby I tend to lose the timestamp, i can do one or the other and lose information, but not both

#

any help would be very much appreciated.

#

crap, i realised this might be the wrong section

#

sorry..

signal cloak
#

smt like that

#
{
  "notes": [
    {
      "id": 1,
      "name": "john"
    },
    {
      "id": 456478548,
      "name": "Smiths"
    }
  ]
}```
#

smt like that

#

Would be the best

burnt turret
#

this is just the way that the mongodb UI displays it

#

if you use the shell to display it, it'd look like this

signal cloak
#

Ok great then

#

how Can I retreive them now?

signal cloak
burnt turret
#

to query? that'd be something like collection.find({"notes.id": <ID you want to retrieve>})

signal cloak
#

so note.id is not going to check the numbers there, its going straight to the object?

burnt turret
#

yeah it won't check by the index

#

The docs I linked explains all this quite well

signal cloak
#

I read I understand now

#

I so if I need to check 2 coinditions

#

I can go like

#

collection.find ({"_id": "my_custom_user_id", "notes": {"id": "my_custom_note_id"}})

#

as you say above

burnt turret
signal cloak
#

both correct?

burnt turret
#

what you've written searches for an exact match

#

like the object in the array should be just {"id": "my_custom_note_id"} and nothing more

signal cloak
#

oh ok

#

it itterates in all note objects

#

and checks their id

burnt turret
#

yep

signal cloak
#

cool

#

thank you soo much

signal mica
#

Hi

austere portal
#

Is there a way to generate a postgres uri using python?

fringe dock
#

can someone help me in class 12 python

#

indian syllabus

#

and sql

#

i have a good hold on networking

#

can someone help

prisma girder
torn sphinx
#

Im trying to make a login system that fetches the mongodb inputs and checks

#

def login():
user = input("What Is Your Username: ")
password = input(f"What Is Your Password {user}? ")
print("Please Wait While I Log You In")
time.sleep(1)
name = mycol.find_one(name)
print (f"Found {name}")

delicate fieldBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

torn sphinx
#
def login():
    user = input("What Is Your Username: ")
    password = input(f"What Is Your Password {user}? ")
    print("Please Wait While I Log You In")
    time.sleep(1)
    name = mycol.find_one(name)
    print (f"Found {name}")
prisma girder
# torn sphinx

The error message stays clear for me - you are using variable that is not created

torn sphinx
#

im trying to make it find the input inside the databse

prisma girder
torn sphinx
#

then it returns non

#

none

#

and i did put in my username

prisma girder
torn sphinx
#

the collection

#
db = myclient["logins"]
mycol = db["logins"]

def main():
    username = input("Whats Your Username: ")
    password = input("Choose A Password: ")
    password2 = input("Choose A Password: ")
    if password2 == password:
        name = { "name": username, "password":password}
        x = mycol.insert_one(name)
        print (x)
        login()
    else:
        pass
    
def login():
    user = input("What Is Your Username: ")
    password = input(f"What Is Your Password {user}? ")
    print("Please Wait While I Log You In")
    time.sleep(1)
    name = mycol.find_one(name)
    print (f"Found {name}")
    

main()
```\
prisma girder
torn sphinx
#

pymongo

#

myclient is the mongodb connector

#

myclient = pymongo.MongoClient("string")

torn sphinx
#

still finds none

prisma girder
torn sphinx
#

omg

#

im an idiot

#

lol

#

tysm

prisma girder
#

Obvious typo

torn sphinx
#

i now understand mongodb a bit better, it is case sensitive

#

im hoping to make my first webapp

prisma girder
torn sphinx
#

is there a way to encode a password when entering it to databse?

#

and it can still be read?

prisma girder
#

!pypi bcrypt

delicate fieldBOT
#

Modern password hashing for your software and your servers

torn sphinx
#

docs?

#

tys

#

tys

#

tysm

#

my M key dosent want to work

prisma girder
#

No worries

torn sphinx
#

so before entering the pwd

i would go

password = input(Whats your pwd)
hashedpwd = bcrypt.hashpw(password, bcrypt.gensalt())

#

@prisma girder is this correct?

prisma girder
torn sphinx
#

whats salt?

prisma girder
# torn sphinx whats salt?

Salt is (almost always) random data to protect against offline cracking
https://en.wikipedia.org/wiki/Salt_(cryptography)

In cryptography, a salt is random data that is used as an additional input to a one-way function that hashes data, a password or passphrase. Salts are used to safeguard passwords in storage. Historically a password was stored in plaintext on a system, but over time, additional safeguards were developed to protect a user's password against being ...

torn sphinx
#

Traceback (most recent call last):
File "main.py", line 31, in <module>
main()
File "main.py", line 12, in main
encryptedpw = bcrypt.hashpw(password, bcrypt.gensalt())
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\bcrypt_init_.py", line 80, in hashpw
raise TypeError("Unicode-objects must be encoded before hashing")
TypeError: Unicode-objects must be encoded before hashing

prisma girder
#

!e

string = "xyz"
print(string)
print(string.encode())
delicate fieldBOT
#

@prisma girder :white_check_mark: Your eval job has completed with return code 0.

001 | xyz
002 | b'xyz'
torn sphinx
#

what do i import

#

does that look correct

torn sphinx
prisma girder
#

Use verify method

torn sphinx
#

bcrypt.checkpw?

prisma girder
torn sphinx
#

so what?

passwordcheck = bcrypt.checkpw(password)
password = mycol.find_one({"password": passwordcheck})

#

like that?

prisma girder
torn sphinx
#

hmm, how would i do this?

prisma girder
torn sphinx
#

how would i do this?

prisma girder
#

I don’t know, I am not using pymongo and I am away of computer now

torn sphinx
#

how do i create an SQL database with salted hashes

torn sphinx
#

Is there a reason this isnt working??

cursor.execute("INSERT INTO balance (user_id, amount) VALUES (?, ?) ON CONFLICT(user_id) DO UPDATE SET balance = balance + ?;", [user, amount, amount])```
And its weird because im not even getting a error so i added prints and this is line is where it stops
#

ping if someone can help

prisma girder
torn sphinx
#

Login database

prisma girder
torn sphinx
#

sqlite3

proven arrow
#

Did you commit() ?

torn sphinx
#

that is at the end of the command

prisma girder
#

How about database logs?

torn sphinx
#

this is my full command```py

@commands.command()
@commands.cooldown(1, 10, commands.BucketType.user)
async def beg(self, ctx):
dbase = sqlite3.connect('economy.db')
cursor = dbase.cursor()

    user = ctx.author.id

    names = [
        'Carl',
        'Jimmy',
        'Bob',
        'Lily',
        'Gerald',
        'Joe',
        'Karal'
    ]

    print('hello')
    amount = random.randint(0, 1000)
    print('hellodsgasdf')

    cursor.execute("INSERT INTO balance (user_id, amount) VALUES (?, ?) ON CONFLICT(user_id) DO UPDATE SET balance = balance + ?;", [user, amount, amount])
    print('henlo')
    amount = ('{:,}'.format(amount))
    await ctx.send(f'{random.choice(names)} Gave you :dankmerchants: **{amount}**!')

    dbase.commit()
    dbase.close()```
prisma girder
#

Is there info about this query?

torn sphinx
#

feel stupid but where are the db logs?

#

nvm

prisma girder
torn sphinx
#

huh?

#

so i have something similer to this in another command and it works like a charm but this wont work it is basicly the same code

#

but thee table name changed

proven arrow
#

What is balance? Name of table or column ?

torn sphinx
#

both

#

or can the name of table and colum not have the same name??

proven arrow
#

It can be same

torn sphinx
#

hmm then idk whats going wrong

#

because its just not even executing it

proven arrow
#

You need to share more info. How you created table etc.

torn sphinx
#

i created table in the sqlite browser

#

idk what else to share ig

prisma girder
#

How about logs? Are there any info?

torn sphinx
#

this```
PRAGMA database_list;
SELECT type,name,sql,tbl_name FROM "main".sqlite_master;
SELECT "rowid",* FROM "main"."balance" WHERE ("rowid" LIKE '%765322777329664089%' ESCAPE '' OR "user_id" LIKE '%765322777329664089%' ESCAPE '' OR "balance" LIKE '%765322777329664089%' ESCAPE '') ORDER BY "balance" DESC LIMIT 0, 49999;
SELECT COUNT() FROM "main"."balance" WHERE ("rowid" LIKE '%765322777329664089%' ESCAPE '' OR "user_id" LIKE '%765322777329664089%' ESCAPE '' OR "balance" LIKE '%765322777329664089%' ESCAPE '')
PRAGMA database_list;
SELECT type,name,sql,tbl_name FROM "main".sqlite_master;
SELECT COUNT(
) FROM "main"."balance" WHERE ("rowid" LIKE '%765322777329664089%' ESCAPE '' OR "user_id" LIKE '%765322777329664089%' ESCAPE '' OR "balance" LIKE '%765322777329664089%' ESCAPE '')
SELECT "rowid",* FROM "main"."balance" WHERE ("rowid" LIKE '%765322777329664089%' ESCAPE '' OR "user_id" LIKE '%765322777329664089%' ESCAPE '' OR "balance" LIKE '%765322777329664089%' ESCAPE '') ORDER BY "balance" DESC LIMIT 0, 49999;

prisma girder
#

No inserts here, how about error log?

torn sphinx
#

one sec

#

nothing

#

its literly clear

north locust
#

what did i do wrong?

import discord
from discord.ext import commands
from cogs.listvar import scritch

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate("beta/cogs/whiskeybotdatabase-firebase-adminsdk-g9ckh-c52eb0824a.json")
firebase_admin.initialize_app(cred)
ref = db.reference("https://whiskeybotdatabase-default-rtdb.firebaseio.com/")
def setup(bot):
    bot.add_cog(socialv2(bot))

class socialv2(commands.Cog):
    """A couple of simple commands."""
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        print('loading socialv2 cog')
    
    @commands.command(name='boop', description='boop someone', alias=['boops', 'Boop', 'Boops'])
    async def boop(self, ctx):
        ref.set({
            "Books":
            {
                "Best_Sellers": -1
            }
        })

        ref = db.reference("https://whiskeybotdatabase-default-rtdb.firebaseio.com/Books/Best_Sellers")
        import json
        with open("book_info.json", "r") as f:
            file_contents = json.load(f)

        for key, value in file_contents.items():
            ref.push().set(value)


Exception has occurred: ExtensionFailed
Extension 'cogs.socialv2' raised an error: ValueError: Invalid database URL: "None". Database URL must be a non-empty URL string.```

prisma girder
torn sphinx
prisma girder
torn sphinx
north locust
#

the vscode one would work

torn sphinx
#

ok

#

lemme try

prisma girder
#

Is this whole code?

torn sphinx
#

i have to go eat atm but i will be back soon

north locust
#

yes it is

#

i couldnt find it lol

prisma girder
north locust
#

oops i think i forgot this code

default_app = firebase_admin.initialize_app(cred_object, {
    'databaseURL':databaseURL
    })```
#

i found this ina guide

twilit oyster
#

What would be better? Having a table for every person and then in that table every server they are in or having a table for every server and then in that every person in that server?

north locust
north locust
#

how many people?

twilit oyster
#

It could be any number

#

Since it is a discord bot

proven arrow
#

It’s not recommended

twilit oyster
proven arrow
#

Have a table of users, a table for guilds

#

And then a table in the middle if you want it so a user can be in many guilds.

north locust
#
default_app = firebase_admin.initialize_app(cred_object, {
    'databaseURL':https://whiskeybot[redacted].firebaseio.com
    })```
or
```py
default_app = firebase_admin.initialize_app(cred_object, {
    'https://whiskeybot[redacted].firebaseio.com':databaseURL
    })```
which one is correct?
twilit oyster
#

How would that be more efficient?

proven arrow
#

Those are just some reasons. Also when your database grows it creates unnecessary complexity, and databases are not designed for that kind of design.

twilit oyster
#

Hmm okay

north locust
#

lol does anyone know which codebox is correct? ^

proven arrow
#

Don’t you just pass it the credentials?

north locust
#

i pass the credentials in a json file

proven arrow
#

What’s the dict for

north locust
#

which dict?

#

the cred_object?

proven arrow
#

I see one dict there, so obviously that one.

north locust
#

the cred_object is a var defined above to tell it where the cred file is

#
cred = credentials.Certificate("beta/cogs/whiskeybotdatabase-firebase-adminsdk-g9ckh-c52eb0824a.json")
default_app = firebase_admin.initialize_app(cred, {
    'databaseURL':databaseURL
    })```
proven arrow
#

What do the docs say on how to use that? Do you have a link?

proven arrow
#

It’s explained there, if you scroll to that method

north locust
#

so i got the code

#

that looks like

firebase_admin.initialize_app(credential=None, options=None, name='[DEFAULT]')```
#

do i put databaseURL into options?

torn sphinx
proven arrow
#

It’s not required no. They are all optional args you can give

#

Just give the creds

north locust
#

ok how do i add the url tho

north locust
north locust
# proven arrow Just give the creds

hows this look?
the new code

cred = credentials.Certificate("beta/cogs/whiskeybotdatabase-firebase-adminsdk-g9ckh-c52eb0824a.json")
firebase_admin.initialize_app(credential=cred, options=None, name='[DEFAULT]')```
proven arrow
#

There’s examples there, which I sent you earlier today as well.

#

It has the code too so you should maybe take a look at the links people send

north locust
#

i looked at the link you sent

#

i came up with this code

cred = credentials.Certificate("beta/cogs/whiskeybotdatabase-firebase-adminsdk-g9ckh-c52eb0824a.json")
firebase_admin.initialize_app(credential=cred, {
    'databaseURL': 'https://whiskeybotdatabase-default-rtdb.firebaseio.com'
})```
but now im getting this error
```Extension 'cogs.socialv2' raised an error: SyntaxError: positional argument follows keyword argument (socialv2.py, line 10)```
#

so i apparently mistyped something here is the code i got to work

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate("beta/cogs/whiskeybotdatabase-firebase-adminsdk-g9ckh-c52eb0824a.json")
firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://whiskeybotdatabase-default-rtdb.firebaseio.com'
})

ref = db.reference("/")```
#

thanks

north locust
north locust
#

nevermind im dumb and accadentally deleted the database code : /

torn sphinx
#

I still dont understand why this code wont do anything also than stop the code

cursor.execute("INSERT INTO balance (user_id, amount) VALUES (?, ?) ON CONFLICT(user_id) DO UPDATE SET balance = balance + ?;", [user, amount, amount])
north locust
#
        users_ref.set({
    'alanisawesome': {
        'date_of_birth': 'June 23, 1912',
        'full_name': 'Alan Turing'
    },
    'gracehop': {
        'date_of_birth': 'December 9, 1906',
        'full_name': 'Grace Hopper'
    }
})```
is there a way that i can use variables in the json? so i can use inputs from the user?
proven arrow
#

Or you can just replace it with a variable you define some where else

north locust
#

like

        users_ref.set({
    f'var': {
        'date_of_birth': 'June 23, 1912',
        'full_name': 'Alan Turing'
    },
    'gracehop': {
        'date_of_birth': 'December 9, 1906',
        'full_name': 'Grace Hopper'
    }
})```?
proven arrow
#

Yeah

north locust
#

it didnt work

proven arrow
#

Oh yeah I missed that

#

The variable needs to be in curly braces

signal cloak
#

I try to get a field from an inner object in the mongo DB

#

but I cant

#
x = collection.find_one({"notes.id": "1e5d719d"})
print(x["notes"]["title"])```
#

and with dot

#

but nothing works

north locust
prisma girder
signal cloak
#

nop

#

not working

prisma girder
prisma girder
signal cloak
#

ye I was using an array

#

so

#

thats the prob

#

i ll switch to nested now

torn sphinx
#

hi

#

Is there a way to select all the records from a table?
example:

SELECT * FROM table WHERE column = %s

The problem with that code is that it only returns with the first thing that matches the condition, but it doesn't return everything.

exotic sand
#

SELECT *
FROM table;

Returns all records.

torn sphinx
#

but not when I add WHERE

exotic sand
#

Then it will return all records which meet you WHERE condition

torn sphinx
#

it doesn't

exotic sand
#

It definitely does. There is probably some other issue you are running into.

torn sphinx
#

@trim wave how tall r u

trim wave
#

<@&267629731250176001> can someone ban for harassment ^^

torn sphinx
#

wtf

torn sphinx
analog sigil
#

@torn sphinx I'm not sure why you've decided to ask a random user personal details but please keep discussions relevant to the channel's topic.

torn sphinx
#

lol

#
+--------------------+-----------+--------------------+--------------------+-------------+
| guildid            | expressive | physical             | mental             | occupational |
+--------------------+-----------+--------------------+--------------------+-------------+
| 781918826312892437 |      NULL |               NULL | 827911893447344139 |        NULL |
| 781918826312892437 |      NULL |               NULL | 827911893447344139 |        NULL |
| 781918826312892437 |      NULL |               NULL | 827911893447344139 |        NULL |
| 781918826312892437 |      NULL | 827911893447344139 |               NULL |        NULL |
| 781918826312892437 |      NULL | 781930115708747827 |               NULL |        NULL |
+--------------------+-----------+--------------------+--------------------+-------------+β€Š

Using SELECT expressive, physical, mental, occupational FROM levels WHERE guildid = %s returned (None, None, 827911893447344139, None)

#

Is there a way to select all the records from a table?
example:

SELECT * FROM table WHERE column = %s

The problem with that code is that it only returns with the first thing that matches the condition, but it doesn't return everything.

trim wave
#

@torn sphinx btw what is your %s

#

condition

torn sphinx
#

guildid

trim wave
#

are there a list of ids you're looking for?

torn sphinx
#

I think, it is a table with completely BIGINT columns, representing the id.

trim wave
#

wait are you just trying to return all the rows?

#

im not sure what you mean by that

trim wave
#

then just use SELECT * FROM table

#

are you trying to just get specific columns?

#

returned

torn sphinx
trim wave
#

oh ok guild id is just one number right

torn sphinx
#

sure

trim wave
#

and which row are you trying to match with the guildid

#

like are you trying to match a particular id under a column under guildid

#

or are you trying to match a constant guildid with a number in a different column

#

oh wait sorry my b i couldnt read the table properly cuz my screen was too small

#

i think you just do

SELECT * FROM table_name WHERE guildid = "id ur looking for"
#

it shouldnt return one value

#

but all the results

torn sphinx
trim wave
#

??

#

yeah thats the code

torn sphinx
#

yes, the problem now is that it only returns a tuple that represents a row

trim wave
#

that means there is only one match

torn sphinx
#

(None, None, 827911893447344139, None), knowing that the code is correct and the table is fine, I have no idea what the problem is.

trim wave
#

hmm yeah i would assume only one match is found

torn sphinx
#

yeah I hope it returns all the rows that match the condition but only returns what matches first.

#

and surely the search ends when it finds the first match. I'm getting something wrong.

keen rain
#

hello guys can anyone help me with MongoDB?

lunar kettle
#

while installing mysqlclient in virtaulevn i got this error

     command: /Users/mac/rohil/user_api_django/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup.py'"'"'; __file__='"'"'/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-pip-egg-info-trjspjto
         cwd: /private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/
    Complete output (12 lines):
    /bin/sh: mysql_config: command not found
    /bin/sh: mariadb_config: command not found
    /bin/sh: mysql_config: command not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup.py", line 15, in <module>
        metadata, options = get_config()
      File "/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup_posix.py", line 65, in get_config
        libs = mysql_config("libs")
      File "/private/var/folders/w4/76p33pr92x59lq3slgfw6p200000gn/T/pip-req-build-z6i7lulh/setup_posix.py", line 31, in mysql_config
        raise OSError("{} not found".format(_mysql_config_path))
    OSError: mysql_config not found
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
prisma girder
celest rain
#

just asking, is there a way i can change the output format of sqlite3? for example, for fetchall(), it sends this
[('a',), ('b',), ('c',), ('d',), ('e',), ('f',)]
how can i make it so it outputs:
a
b
c
d
e
f

Thanks!

prisma girder
celest rain
#

yes

#

and there would only be 1 value per column

prisma girder
#

!e

data = [('a',), ('b',), ('c',), ('d',), ('e',), ('f',)]
for entry in data:
  print(*entry)
delicate fieldBOT
#

@prisma girder :white_check_mark: Your eval job has completed with return code 0.

001 | a
002 | b
003 | c
004 | d
005 | e
006 | f
celest rain
#

oh alright, thanks!!

celest rain
prisma girder
#

!e

data = ["a", "b", "c"]
print(data)
print(*data)
delicate fieldBOT
#

@prisma girder :white_check_mark: Your eval job has completed with return code 0.

001 | ['a', 'b', 'c']
002 | a b c
celest rain
#

ah okay

#

thanks again!

torn sphinx
#

Hi

#

Help me

#

Database required int array extensio

#

n

proven arrow
# torn sphinx help

Issue is not with the sql. So you need to show the full code including how you use it with python.

torn sphinx
#

that's something I don't expect when the code is in good condition

proven arrow
#

Are you going to show the code or not?

torn sphinx
#

yes

#

lol

torn sphinx
#

Cause the rest I guess is unrelated

torn sphinx
#

Help me pls

torn sphinx
# proven arrow Are you going to show the code or not?
levelchannels = await temp.execute(
                """CREATE TABLE IF NOT EXISTS levelchannels(
                guildid BIGINT,
                expressive BIGINT,
                physical BIGINT,
                mental BIGINT,
                occupational BIGINT)""")
requests = await obj.execute("SELECT * FROM levelchannels WHERE guildid = %s",
                                             (message.guild.id))
requests = await obj.fetchone()
print(requests)
proven arrow
#

What does fetchone() tell you?

#

It’s literally in the name

torn sphinx
#

lol

#

true

proven arrow
#

You need fetchall()

torn sphinx
#

now yes returns everything. thanks!

proven arrow
torn sphinx
#

@proven arrow Is there a way to group the tuples by column and that does not collect what would be NULL?
example:

((expressive column), (physical column), (mental column), (occupational column))

and that it is not like that

((None, None, 827911893447344139, None), (None, None, 827911893447344139, None), (None, None, 827911893447344139, None), (None, 827911893447344139, None, None), (None, 781930115708747827, None, None), (801137870622556181, None, None, None), (781930022374080562, None, None, None), (781930022374080562, None, None, None))
proven arrow
#

I don’t understand what you mean

torn sphinx
#

sort the columns in the tuple it will return, because normally it will return all the content of the columns in row order, But I would like it to be grouped or sorted by column and None does not appear.

proven arrow
#

You can specify the columns you need instead of doing *

celest rain
#

thanks!

proven arrow
torn sphinx
prisma girder
celest rain
prisma girder
torn sphinx
torn sphinx
twilit oyster
#

if I need to store data inside each user, should I do it where I create a Table for each guild or create a table for each user? I will be storing data inside of it such as XP.

#

I am using mongodb

torn sphinx
valid vault
#

I’m constantly getting a β€œToo many connections” error using aiomysql but I’m sure all my connections are being closed after use and the max is set to 225 which should be plenty - do I need to wrap all my connections things in try/except to make sure it always closes connections or something? or is there a way to force a connection to time out?

#

Not really sure how to debug the issue. Any ideas?

wind sand
#

hello, I am using asyncpg and upon running on query which is await cursor.execute("DELETE FROM roles WHERE role = $1 and guild = $2 and type $3", role.id, guild, type) I get an asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "$3" Everything looks correct so I am not sure what I am missing. Any ideas?

wind sand
valid vault
wind sand
#

yeah, look into connection pooling, should fix your issue

valid vault
#

brilliant, thanks for that!

wind sand
#

if it is still a problem, you can increase the number of allowed connections using the SET GLOBAL command and/or decrease the wait_timeout

valid vault
#

yeah I tried to increase the connections and the same issue was caused but after a slightly longer period of time haha. wait_timeout was something I saw, might have to play around with that if pools don't help

#

thanks for the help!

wind sand
#

np!

lost pebble
#

to connect to a remote database via ssh tunnel should I just ssh -L or use the sshtunnel library

#

ssh-L seems like it would have the advantage of not putting login info in a python script

#

other may be the proper way though its whats in all the tuts

summer nimbus
#

like how do i find keys only having guild id as ctx.guild.id?

torn sphinx
#
await guild.update_one({"guildid":message.guild.id}, {"$set": {"deleted_message_channel":message.channel.id, "content": {"deleted_message_content":message.content, "deleted_message_author":message.author}}}, upsert=True)
bson.errors.InvalidDocument: cannot encode object: <Member id=457137840820715522 name='dendo' discriminator='6341' bot=False nick=None guild=<Guild id=no name='no' shard_id=None chunked=True member_count=2873>>, of type: <class 'discord.member.Member'>

Why am I getting this error and what does it mean?

torn sphinx
uneven lion
#

(MONGODB / PYMONGO) How would i make commands like this: Welcome channel set, goodbye channel set, and prefix set? Every server would be different btw | ping if answer

ornate fulcrum
#

https://paste.pythondiscord.com/dequcumefi.py
This is piece of cog file from Message of the day bot. User can do !addline "thisismsgoftheday" and line gets saved into database. The bot posts random line from database daily at specific time. Problem with this !showdatabase is it posts every line like one at a time, and i want the bot post the lines in a single post instead. So all lines from database should be inside a single post instead of multiple. How to do that?

tranquil totem
#

Code:```py
@commands.command()
async def enable(self, ctx, feature = None, channel: discord.TextChannel = None):
if feature == "suggest":
if channel is None:
embed = discord.Embed(description = "You need to mention a channel also", color = 0xf04947)
await ctx.send(embed=embed)
else:
collection.update_one({"_id": ctx.guild.id}, {"$set": {"suggestion_channel": channel } } )
await ctx.send(f"Suggestions enabled on {channel.mention}")

Error:```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidDocument: cannot encode object: <TextChannel id=831048029276340224 name='suggestions' position=8 nsfw=False news=False category_id=831045454749761566>, of type: <class 'discord.channel.TextChannel'>
#

why tho

#

someone help me pls

#

asap

prisma girder
tranquil totem
round agate
#

Hello there! A little suggestion please! I was using Moon Modeller software for modelling E-R, unfortunately it's paid and with the free version you can have only 10 tables. Any suggestion for a free tool for relational databases? Thanks!

tranquil totem
#

its related to databases tho so ill ask it here

#

how to change the datatype of a value to int

#

and then post it

#

i.e. { "channel_id": ...} which can only take int values

prisma girder
#

!e

num = "10"
print(type(num), num)
num = int(num)
print(type(num), num)
delicate fieldBOT
#

@prisma girder :white_check_mark: Your eval job has completed with return code 0.

001 | <class 'str'> 10
002 | <class 'int'> 10
tranquil totem
prisma girder
delicate fieldBOT
#

@prisma girder :x: Your eval job has completed with return code 1.

001 | valid_num 10
002 | Traceback (most recent call last):
003 |   File "<string>", line 5, in <module>
004 | ValueError: invalid literal for int() with base 10: '10!'
austere portal
#

what is the postgresql uri?

prisma girder
# austere portal what is the postgresql uri?

Connection URI is a string which contains several informations like host, port, database name and others

postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp

See more here: https://www.postgresql.org/docs/9.3/libpq-connect.html#SECT3

austere portal
#

Thanks

tranquil totem
#

okay

#

okay

#

simpler question

#

how do you store a channel as a value in a database

#

that can be used in the code to send a msg in it

burnt turret
#

Store the channel's ID

#

You can retrieve the channel object later with guild.get_channel/bot.get_channel

tranquil totem
#

you know how discord.Member always works with the id or the mention

#

is there a way to do the same with discord.TextChannel?

cedar surge
#

with mysql can i use brackets for the optional things.

    `id` INTEGER [PRIMARY KEY] [AUTO_INCREMENT],
```  like that?
prisma girder
torn sphinx
#

hi

thorn geode
torn sphinx
#

I have a problem execute this

"DELETE expressive, physical, mental, occupational FROM levelchannels WHERE guildid = %s"

return 109, "Unknown table 'expressive' in MULTI DELETE"

#

in the row only one column has a value, the others are NULL

#

and I would like to delete the whole row where the id and column is located

tranquil totem
#

but i get an error here

#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Int64' object has no attribute 'send'
#

hold on

thorn geode
#

You need to convert it to a text channel object

tranquil totem
#

yeah

tranquil totem
thorn geode
#

Guild or bot, yea

#

@tranquil totem ^

green raptor
#

hey i am using sqlite to store links of gifs, i am sometime getting "none" instead of link (gif)

prisma girder
green raptor
#

how i access db

    fetch = sql.execute("SELECT Url FROM tbl_Hug ORDER BY RANDOM() LIMIT 1;").fetchall()
    conn.commit()
    result = fetch[0][0]
    return result```
#

how i send the gif in chat
await ctx.send(f"{url}")

cedar surge
green raptor
#

@prisma girder i added some info

prisma girder
prisma girder
green raptor
prisma girder
green raptor
prisma girder
green raptor
#

hahahahahaha

#

omg

#

bro sorry for being stupid, i forgot that i wanted to fill them

#

omfg haha

prisma girder
prisma girder
green raptor
#

thank u for help! ❀️

prisma girder
tranquil totem
craggy pawn
#

would a mysql database wreck my 2gb rpi?

prisma girder
brazen charm
#

cuz of that slow SD speed

prisma girder
#

That's right

craggy pawn
#

would a usb 3 drive be any faster?

prisma girder
prisma girder
cedar surge
prisma girder
cedar surge
#

hmm?

#

you said this "Use rather DEFAULT NULL pithink Make sure that column is nullable"

proven arrow
# cedar surge hmm?

To your intiial question the optional arguments don’t need to be in brackets.

#

You can leave them out or put them in your query without the brackets.

scarlet geyser
#

(MONGODB / PYMONGO) How would i make commands like this: Welcome channel set, goodbye channel set, and prefix set? Every server would be different btw | ping if answer

torn sphinx
thorn geode
#

Note that there is no SQL

jagged cove
#

how do database APIs work and can i still use them with SQL?

#

or does that depend on the API

median swift
#

I need some help with PGAdmin4, I have a table but I want to reset the primary keys so the start from 0 again. I had around 10 records and deleted them though the PK starts at 11 now

jagged cove
#

nvm got an answer from another source, thanks anyhow

ebon skiff
#

You'd have to make some queries to save the data, i wanna know where you at now, then i can help you better.

median swift
#

I think I found a solution

median swift
#

Doesn't matter

proven arrow
#

Ok πŸ‘πŸ˜†

distant radish
#

for the issue I was having where python wasn't connecting to the database on mac

#

it's because xampp's default installation on mac was as a VM

#

just in case anyone is looking for a fix to a problem similar to mine

torn sphinx
#

How can I make a range table?

#

I try to see the ones that have a bigger int and I would like to select maximum 10 for a classification table

storm sierra
#
    async def whitelist(self, ctx, user_id=None):
        self.client.db = await aiosqlite.connect('whitelist.db')
        cursor = await self.client.db.cursor()
        result = await cursor.fetchall()
        
        await cursor.execute(f"SELECT wl FROM whitelist WHERE guild_id == {ctx.guild.id}")
        print(result)
        
        await cursor.execute("INSERT INTO whitelist(wl, guild_id) VALUES (?,?)", (user_id, ctx.guild.id, ))
        await self.client.db.commit()``` why result is []?
#

I also tried printing result in other command almost the same and result is [] too, I also noticed it inserts but result is []

burnt turret
#

You're fetching before executing a query

#

Also you shouldn't be using f-strings with SQL queries, this message explains why

storm sierra
#

Also why? Even if I run the command twice its []

burnt turret
#

so there's nothing to fetch, so it gives you []

#

just fetch after the query

storm sierra
#

Ok

#

Worked xd

ornate fulcrum
#

https://paste.pythondiscord.com/yadicotule.py
Hey, this is Message of the day bot. It posts random message from database at specific time set by user. This piece of code is from cog that checks the time from database each 5 sec(will change this into 10min, 5sec is for testing) and should make the post with sleep.until. However, this thing doesn't sleep at all. It posts each 5 sec it lets the loop go through. What would be the correct way to do this? Bot shouldn't post when the time doesn't match.

upbeat slate
#

Hello, IDK if this is the right place to ask, but how can i get many PY scripts to read a file that is being edited IRT by another script, and how can i get multiple files not to edit a file at the same time? Also is it possible to import a variable without having to run the whole program inside another without using text files?

#

ik that is alot of questions but i need answers

#

again sorry if I asked in the wrong channel

dull cypress
#

what are you trying to accomplish?

upbeat slate
dull cypress
#

this is architecture issue

upbeat slate
#

like how can i get to my goal

#

is it even possible?

dull cypress
#

I need to know your project scope and goals, and implementation constraints. it's not uncommon for the issue you're stuck with being the results of poor implementation.

upbeat slate
#

I see

#

i didnt actually start doing it

#

i tried it once before

#

but it didnt go well

#

I basically want to make an RPG like bot, just for practice, and I i want it to have idle miners

#

to make those work, I thought of a system that checks how many miners an ID has, multiplies that number by some amout, and adds it to the ID's money

#

this is why I need many programs to edit at once

#

To make the bot faster, I thought of an autosave system that exports all JSON vars and stuff from the programs and edits them

#

cuz editing at every action is long asf

#

@dull cypress

elfin palm
#

hello

#

i'm getting an error 'NoneType' object is not subscriptable when i trying to fetch cursor py return cursor.fetchone()[0]

#

but this cursor shouldn't return none

#
 cursor.execute(f"SELECT 1 FROM information_schema.tables WHERE table_name = '{table_name}'")
#

if the table doesn't exists should return en empty tuple right?

#

where i cna find the values?

slow kettle
#

does anybody have pointers to guides for setting up a DB eg postgres on Windows ? i have been avoiding using databases for too long :'(

pliant robin
#

Hey i was making a bot on replit, how do i open my base.sql database file?

#

On opening the file in db browser after downloading the zip folder, i noticed the entries weren't properly updated, whats wrong?

cyan yacht
#

You have to commit whenever you update

gaunt garden
#

Error:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.```

Code:
```py
db = sqlite3.connect('punish.sqlite')
c = db.cursor()
results = c.execute("SELECT * FROM tempbans WHERE active = ?", ('True',)).fetchall()
c.close()
db.close()

Sorry if this is a noobish question, but i don't know why im getting this error...

#

holdup, im in the wrong location. sorry should be looking at mutes, not tempbans.

pliant robin
#

t

delicate fieldBOT
#

Hey @lunar kettle!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

lunar kettle
#

i cant install mysqlclient in windows pc

  Downloading mysqlclient-2.0.3.tar.gz (88 kB)
     |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 88 kB 99 kB/s
Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed.
Installing collected packages: mysqlclient
    Running setup.py install for mysqlclient ... error

it is installing tar.gz file

quick saddle
#

Trying to figure out what this is doing in some custom programs I'm trying to understand

#

At this point I'm guessing it's binary?

prisma girder
torn sphinx
#

Question time

I've a user table and a settings table, the settings table has columns that are set to NOT NULL and some can be NULL.

In user i've a FK that refers to settings, does this FK needs to be set to NOT NULL aswell or not?

#

I'm quite confused

#

The settings table has columns that are set to NOT NULL, which means they NEED to provide data to set it, but how can I do this if a user registers first, then later on creates their settings?

quick saddle
#

So this file is used to unlock a mdb file?

prisma girder
quick saddle
#

Because I've been trying to open a. Mdb file to no success so I'm guessing this is the key

molten hound
#

sudo apt install libpq-dev python3-dev

#

sudo apt install build-essential
sudo apt-get install python3-dev default-libmysqlclient-dev

quick saddle
#

OK here's where I'm at

#

What is this code on the right? Is it decompiled incorrectly?

proven arrow
glad marten
#

is it necessary to create a class for your table if all you are doing is accessing the data and not creating or writing

#

new to flask

#

or better yet, does someone have a good example of connecting to an existing database and setting up queries

candid coral
#

im using mysql with python to write data to a database, but counting affected rows returns -1. Any help? what causes this?

prisma girder
glad marten
candid coral
#
conn = sqlite3.connect('pythonDB.db')
c = conn.cursor()

c.execute('CREATE TABLE IF NOT EXISTS notifList (sentid INTEGER, onoff TEXT)')
tiname = '.3060ti'
  sendid = ctx.author.id
  sendid = int(sendid)
  c.execute("SELECT COUNT(*) FROM notifList WHERE sentid = (?)", (sendid,))
  row_count = c.rowcount
  print ("number of affected rows: {}".format(row_count))
  if row_count == 0:
    c.execute("INSERT INTO notifList VALUES (?, ?)", (sendid, 'on'))
    conn.commit()
    await ctx.send('Added!')
  else:
    c.execute("DELETE FROM notifList WHERE sentid = (?)", (sendid,))
    await ctx.send('Removed!')```
I'm also using discord.py
prisma girder
candid coral
prisma girder
# candid coral ```py conn = sqlite3.connect('pythonDB.db') c = conn.cursor() c.execute('CREATE...

Have you checked out the documentation? https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.rowcount

As required by the Python DB API Spec, the rowcount attribute β€œis -1 in case no executeXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface”. This includes SELECT statements because we cannot determine the number of rows a query produced until all rows were fetched.
Try to call c.fetchall() pithink

#

However I may be wrong, I am not sqlite3 user

prisma girder
candid coral
prisma girder
candid coral
#

im not sure, just started sql today soooo

candid coral
prisma girder
#

Can you show how you used .fetchall()?

candid coral
#

just with a c.fetchall() (no idea how to 😭) @prisma girder

candid coral
lunar kettle
molten hound
#

Just change te sudo command for those that u use

lost pebble
#

how can I speed up database queries.

#

I am currently using mysql

#

with sqlachemy

#

typical query
query = current_app.config["DiscordDB"].query.order_by(desc('message_id')).filter(current_app.config["DiscordDB"].content.contains(q)).limit(size)

#

This takes about 2 seconds of maxed cpu

#

on a 800mb table

proven arrow
#

Make sure to have the proper indexes on your columns

lost pebble
#

indexes?

#

I have the primary key set

proven arrow
proven arrow
lost pebble
#

yes its the first WHERE

#

the message_id

proven arrow
#

That’s order by?

lost pebble
#

oh wrong query

#

meant to post the one that queried that

#

I do have other queries that do other columns

#

what other indexes are their? I can't do unique

proven arrow
#

It’s not always about unique

#

You can index most data types/columns

#

Read the post, I sent which explains it in a few different ways

#

In most cases indexing can speed it up a lot. However, remember indexing comes at a cost as well.

lost pebble
#

ah interesting

#

yea I have plenty of storage

#

not sure about the fragmentation... but eh I have to do something

#

so I assume that fields that query parameters would be good for indexes

#

i.e. guild_id, server_id, channel_id

proven arrow
# lost pebble yea I have plenty of storage

Storage is not an issues as well today because it’s cheap. But writing can take longer when you have more indexes. Anyways in your use case this shouldn’t be a big concern.

proven arrow
lost pebble
#

will indexing take a long time?
with ALTER TABLE table_name ADD INDEX column_name

#

wondering if I need to run it in a screen to avoid being stuck in a ssh session for 5 hrs lol

#

eh will just screen it

lost pebble
#

such as message_content?

#

or should I index that too.

proven arrow
#

Depends what you store or how you query it

#

Because sometimes it might still use a full table scan instead of using the index.

lost pebble
#

ah true. I'm my way i'm pretty sure it scans full table

#

since its looking for %text%

proven arrow
#

Yeah

lost pebble
#

well thank you. The post linked discussed what makes a good index but I didn't really get it.

proven arrow
#

MySQL also has full text searching which you can look into

lost pebble
#

I used them and oh my god its instant now

#

db go brr

#

thank you a bunch

scarlet geyser
#

Is the Rsk a good visor for the Sq88 daatabse? Im talking about using 5-10 collections btw

austere portal
#

Are there any libs that I can use to query the db like django's db api?

austere portal
#

I want a to do something like py Model.objects.all() # returns everythinglike django's query api

whole condor
#

Depends what you store or how you query it
Because sometimes it might still use a full table scan instead of using the index.

whole condor
grave eagle
#

can i open a sqlite3 db multile times? like 1 db for more scripts

proven arrow
#

Many readers, single writer.

warm rain
#

when using yield from in aiomysql.Cursor.execute
It tells me can't use that since it's an async function

burnt turret
#

the aiomysql doc is rather outdated

#

it still uses old style @asyncio.coroutine in many spots

burnt turret
#

i'd made an issue about it on their repo but to no avail lemon_pensive

warm rain
#

what should I use instead?

burnt turret
#

instead of yield from, use await

warm rain
#

I mean as an entire better lib?

#

which is also async

burnt turret
#

ah right, i haven't heard of any other async mysql lib sadly

warm rain
#

Wanna use it for discord bots

#

And the code doesn't work

weak tinsel
#

async/await syntax works in aiomysql

austere portal
#
def create(name, expiry):
    with psycopg2.connect(uri) as conn:
        with conn.cursor() as cur:
            cur.execute("INSERT INTO FoodProducts(Name, Expiry) VALUES (%s, %s);", (name, expiry))
            conn.commit()```
How can I make this return the id of the new row created (the table already has a id column). Thanks
torn sphinx
#

yo anyone good with database

ornate fulcrum
#
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def requestdata(self, ctx):
                print("Requested data into dbstorage.txt")
                ssslsst = []
              
                async for result in collection.find({}):
                            ssslsst = str([result["writeup"]]).strip("[]'")
                            f=open ('dbstorage.txt', 'a')
                            f.seek (0, 0)
                            f.write(ssslsst + "\n")                          
                            f.close()``` This should get any values from keys "writeup" from database, but i don't get any values if the document has more keys than "writeup" only. How should this be done. I need only "writeup" values saved inside a file but doesn't save anything if doc have for example "author" key and value exist in doc
torn sphinx
#

anyone good with database that knows how to make a server sided command toggle

#

Hey, i have a problem. I have this dict ```py
{'name1': [20, 10, 2, 2, 9, 10], 'name2': [1, 1, 1, 1, 1, 1], 'name3': [2, 2, 2, 2, 2, 2], 'name4': [3, 3, 3, 3, 3, 3], 'name5': [4, 4, 4, 4, 4, 4]}

dense barn
#

can you use enabled=True for per server commands?

ornate fulcrum
#

Yayyy i found solution myself, there was one entry that didn't have whole key "writeup" which caused the error

lost pebble
#

I am using aiomysql with a query INSERT IGNORE
... it ignores it but it also write a warning to stdout

#

can I suppress this warning?

dusky siren
#

I'm using SQLite3 for this
currently my code is doing this:

calenderCards = ["poketcb-15", "poketcb-16", "poketcb-17", "poketcb-18", "poketcb-19", "poketcb-20", "poketcb-21",
                 "poketcb-22", "poketcb-23", "poketcb-24", "poketcb-25", "poketcb-26", "poketcb-27", "poketcb-28",
                 "poketcb-29", "poketcb-30", "poketcb-31", "poketcb-32", "poketcb-33", "poketcb-34", "poketcb-35",
                 "poketcb-36", "poketcb-37", "poketcb-38"]

superCards = ["poketcb-12a", "poketcb-39a", "poketcb-7"]


async def pointRefresh(cardID):
    c.execute("SELECT * from cards WHERE id = ?", [cardID])
    i = c.fetchone()
    basePoints = pointDict.get(i[7].lower(), 1)
    releaseDate = setReleasedict.get(i[6], 2099)
    if releaseDate < 2010:
        multiplier = (0.96 * ((releaseDate - 2010) ** 2)) + 1
    else:
        multiplier = 1
    if i[17] is not None:
        gradeMulti = 9.7 * ((i[17] / 10) ** (4 ** (0.199 * i[17]))) + 0.4
    else:
        gradeMulti = 1
    cardPoints = (basePoints * multiplier) * gradeMulti
    if i[6] is not None and i[6].lower() == "shiny vault":
        cardPoints += 2000 * gradeMulti
    if i[2] in calenderCards:
        cardPoints /= 100
    elif i[2] in superCards:
        cardPoints *= 100
    c.execute("UPDATE cards SET points = ? WHERE id = ?", [cardPoints, cardID])
    conn.commit()

With 1 million+ database rows.
Every bit of code in there seemingly runs fast enough except the queries. The queries take long enough the entire code is going to take days to run. Anyone have better ideas on how to make this more efficient? Say, a way to create a query that will take a list of card ids and a list of card points and insert all at once to save on some time?

thorn geode
#

You can try using aiosqlite

#

Which isn't blocking.

brazen charm
#

well you sorta have a few things you can do

#
  1. doing it for each card individually is very slow, you want to use execute many (more on this in a sec)
  2. you should really try move all those calculations closest to the data SQL does a great job at this
  3. You want to really use a bigger DB for this like postgres which is multi processed and able to handle much bigger and heavier loads than SQLite (also gives you executemany which reduces your round trips needed on every query)
round agate
#

some one know how to change data type of a column in dBeaver?!?! I'm getting mad..

#

in sqlite

south charm
#

hello

#

anyone knows MySQL here?

#

anyone knows the answer of the third question?

pure cypress
#

Use a SELECT with a WHERE. The WHERE can use the > operator to compare dates.

warm rain
#

I'm setting up postgre DB
When I type psql (I already added the bin folder to PATH)
I get this error:

        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?```
How do I see if port 5432 is blocked/occupied by another app>
flint salmon
#
import sqlite3
import os
connection = sqlite3.connect("user_data.db")
cursor = connection.cursor()

# cursor.execute("""CREATE TABLE users(
#     username integer
# )""")
pass_var = os.environ['PASS_VAR']
pass_input = input('Enter administration login password(ALP): ')
if pass_input == pass_var:
    username_input = int(input('Enter a username: '))
    cursor.execute(f"INSERT INTO users VALUES({username_input})")
    print('Username added succesfully.')
    cursor.execute("SELECT * from users")
    print(cursor.fetchall())
#

i got this and it returns a key error

#

KeyError: 'PASS_VAR'

#

in my .env file that is in the same dir , i got that:

PASS_VAR="z0hFd"
#

what do i do wrong

tranquil totem
#

how to individually fetch data from different collections in pymongo?

flint salmon
#

getone

#

getone(var)

torn sphinx
#
res = await collection.find_one({"id":ID})
await ctx.reply(res)

Why does this give me cannot send an empty message error and how can I fix that?

tranquil totem
#

collection.find_one({"_id": member.guild.id})["welcome_channel"]

#

This is an example and its in a cog where the login info is specified

#

now what would i do if i were to remove the login details from this cog and add them only in my main file?

#

heres my login info
||```py
client = pymongo.MongoClient(os.environ["DB_login"])
db = client.discord_database
collection = db["server_data"]

#

and this is for one collection

#

i need to fetch data from several collections
what would i do in that case?

upbeat slate
#

How to append in json from python 😫

#

friend_json[author].append(mentionned) does not work

#

append is not recognized

devout girder
#

is it a dict?

lost pebble
#

I have more mysql questions

#

Should I be using varchar instead of text

#

for storing values such as names and emails I am presently using text

#

According to some stack posts it seems that varchar queries faster and works better with indexing

#

however this seems to be a point of contention as other benchmarks disagree

proven arrow
#

@lost pebble for MySQL yes varchar would be the better choice for things like email and names

proven arrow
torn sphinx
#

selecting a row that doesn't exist in postgres, will it return None or will an error be raised?

shell ocean
shell ocean
#

but it depends on which method of the driver you use of course

torn sphinx
#

what about fetchval

#

asyncpg.fetchval

shell ocean
torn sphinx
#

okie

#

thx

burnt turret
#

fetchval should be giving None iirc

tepid cradle
#

When I run the following code, I get an error saying RuntimeError: Event loop is closed. How do I run this? I'm just trying to get started with Asyncpg and not able to figure out how to connect and run a statement using this library.

import asyncio
import asyncpg

async def connect_db():
    conn = await asyncpg.connect('postgresql://******')
    return conn


async def test():
    conn = await connect_db()
    async with conn.transaction():
        cur = await conn.cursor("select * from pizza_mst")
        print(await cur.fetchrow())

asyncio.run(test())
tranquil totem
#

😩

rain plank
#

actually no thonk

#

What's the full error you get?

pastel yoke
#

Is there any library other than sqlite to interact with databases?

burnt turret
#

there are other libraries to interact with other databases πŸ™‚

#

to elaborate; SQLite is just one database, and python has the sqlite3 module to interact with it
If you were to use another database, you'd use the corresponding module. For example if you were using mysql, you could use mysql-connector-python, if you were using postgresql, you could use psycopg2 etc

torn sphinx
#

How would i select last 5 rows from table without having id in my table -> sql

brazen charm
#

or tbh even then that doesnt guarantee the order

proven arrow
#

If you don’t have anything that can be ordered then you can use a window function, to give a number to each row as inner query. And then use this to order by/ limit.

torn sphinx
#

hey, i have a database that looks like this:
Posts: ID, title, image
Subreddit: Subr

i want to know how many times a post is posted in a certain subreddit. does someone know a good way to save this data? The thing i came up with is:

another table that looks like this:
Link: postid, subreddit, how_many_posts

with 2 subreddits and 2 posts itd look like this then:
postid_1, subr_1, 0
post_id1, subr_2, 0
post_id2, subr_1, 0
post_id2, subr_2, 0

proven arrow
#

That way you don’t need keep track manually

torn sphinx
#

it needs to post the post where how_many_posts is the lowest amount

rocky crypt
#

but i dont get how one post can be posted many times in the same subreddit

#

that doesnt make sense

normal carbon
#

hi, can any one help me with a django project?
i need to create a DB for users

unkempt prism
#

im new to databases. I wrote a python script to query the database every 3 seconds (its a tiny database, SUB 30 rows) and i get the error "Too many clients already" but i dont understand this. https://i.imgur.com/wmtUT5Y.png

#

the script should be closing the database once it is done (uses a with statement)

#

im using Postgresql

torn sphinx
#

So i dont need to do it manually?

quick radish
#

Hey does anyone know why this query doenst round up my result?

SELECT nom, salaire, ROUND(salaire * 1.0525, 2) AS AugmentationSalariale
FROM employe
WHERE no_emp_resp BETWEEN 2 AND 4 AND (salaire * 1.25 <= 70000)
rocky crypt
rocky crypt
unkempt prism
#

πŸ™

rocky crypt
#

i dont think i can really help without looking at the code directly.
youre basically opening more connections than allowed (probably in a for loop?)

#

try to debug with this in mind

unkempt prism
#

i cant seem to find anything that wouldnt close a connection. I dont have any database connections in a for loop. so that out

#

hmmm

#

is there a way to change my database settings to time out a connection when its passed a certain time?

#

say, if something is older than 5 minutes, it times out?

proven arrow
unkempt prism
#

im using a lib called dataset

#

all my database connections are opened with with statements

#

so i would think it would close automatically right?

dull cypress
#

looks like you spawn a new connection for every loop

#

what you should do instead is init a db conn at the start, and reuse it throughout your code. that way your script only spawns "one connection"

tranquil totem
#

@burnt turret whats this

#

:/

burnt turret
#

.find isn't .find_one

#

i explain why we don't await the find towards the end of that gist

tranquil totem
#

oh

#

i thought it was for any type of .find

#

ty

#

@burnt turret what abt if statements?

#
if (collection.count_documents({"_id": ctx.author.id}) == 0) or (collection.find_one({"_id": ctx.author.id})["note"] is None):
```do i add await here as well?
burnt turret
#

there's nothing special about if statements, you'll have to await them there too

tranquil totem
#

ok thank you

#

switched to motor successfully

signal cloak
#

How can I delete the 1 object in that array

#

its I only have the id

#

I need like the code

#

I know its something like